您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在python項(xiàng)目中監(jiān)測(cè)內(nèi)存和cpu的使用率,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
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)前時(shí)間 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()
上述內(nèi)容就是怎么在python項(xiàng)目中監(jiān)測(cè)內(nèi)存和cpu的使用率,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。