python 監(jiān)測內(nèi)存和cpu的使用率實例
更新時間:2019年11月28日 15:40:58 作者:ajiong314
今天小編就為大家分享一篇python 監(jiān)測內(nèi)存和cpu的使用率實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了,直接上代碼吧!
import paramiko
import pymysql
import time
linux = ['192.168.0.179']
def connectHost(ip, uname='shenyuming', passwd='ajiongqqq'):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=uname, password=passwd,port=22)
return ssh
def MainCheck():
try:
while True:
time.sleep(1)
for a in range(len(linux)):
ssh = connectHost(linux[a])
# 查詢主機(jī)名稱
cmd = 'hostname'
stdin, stdout, stderr = ssh.exec_command(cmd)
host_name = stdout.readlines()
host_name = host_name[0]
# 查看當(dāng)前時間
csj = 'date +%T'
stdin, stdout, stderr = ssh.exec_command(csj)
curr_time = stdout.readlines()
curr_time = curr_time[0]
# 查看cpu使用率,并將信息寫入到數(shù)據(jù)庫中(取三次平均值)
cpu = "vmstat 1 3|sed '1d'|sed '1d'|awk '{print $15}'"
stdin, stdout, stderr = ssh.exec_command(cpu)
cpu = stdout.readlines()
cpu_usage = str(round((100 - (int(cpu[0]) + int(cpu[1]) + int(cpu[2])) / 3), 2)) + '%'
# 查看內(nèi)存使用率,并將信息寫入到數(shù)據(jù)庫中
mem = "cat /proc/meminfo|sed -n '1,4p'|awk '{print $2}'"
stdin, stdout, stderr = ssh.exec_command(mem)
mem = stdout.readlines()
mem_total = round(int(mem[0]) / 1024)
mem_total_free = round(int(mem[1]) / 1024) + round(int(mem[2]) / 1024) + round(int(mem[3]) / 1024)
mem_usage = str(round(((mem_total - mem_total_free) / mem_total) * 100, 2)) + "%"
sql = "insert into memory_and_cpu values('%s','%s','%s','%s')" % (
host_name, curr_time, cpu_usage, mem_usage)
db = connectDB()
sqlDML(sql, db)
except:
print("連接服務(wù)器 %s 異常" % (linux[a]))
def connectDB(dbname='test11'):
if dbname == 'test11':
db = pymysql.connect("localhost", "root", "shen123", "test11")
return db
def sqlDML(sql, db):
cr = db.cursor()
cr.execute(sql)
db.commit()
cr.close()
#
if __name__ == '__main__':
MainCheck()
以上這篇python 監(jiān)測內(nèi)存和cpu的使用率實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python scipy.spatial.distance 距離計算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計算函數(shù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
python通過ftplib登錄到ftp服務(wù)器的方法
這篇文章主要介紹了python通過ftplib登錄到ftp服務(wù)器的方法,涉及Python使用ftplib模塊的相關(guān)技巧,需要的朋友可以參考下2015-05-05
python 將dicom圖片轉(zhuǎn)換成jpg圖片的實例
今天小編就為大家分享一篇python 將dicom圖片轉(zhuǎn)換成jpg圖片的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
pandas使用QGraphicsView自動排列項目的實現(xiàn)
本文主要介紹了pandas使用QGraphicsView自動排列項目的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04

