Python 远程监控 Linux 主机 CPU 与内存使用率实现
本文介绍使用 Python 通过 Paramiko 库远程连接 Linux 服务器,并实时监测 CPU 和内存使用率的方法。代码示例展示了如何获取主机名、当前时间,并通过 vmstat 命令计算 CPU 使用率的平均值,最后将数据写入数据库。
Python 远程监控 Linux 主机 CPU 与内存使用率实现
以下代码展示了如何监测内存和 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])
# 查询主机名称
cmd = 'hostname'
stdin, stdout, stderr = ssh.exec_command(cmd)
host_name = stdout.readlines()
host_name = host_name[0]
# 查看当前时间
csj = 'date +%T'
stdin, stdout, stderr = ssh.exec_command(csj)
curr_time = stdout.readlines()
curr_time = curr_time[0]
# 查看cpu使用率,并将信息写入到数据库中(取三次平均值)
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)) + '%'
# 查看内存使用率,并将信息写入到数据库中
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("连接服务器 %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 远程监测主机资源使用率的完整示例,供参考使用。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









