远程监控服务器内存占用——Python

paramiko读取/proc/meminfo,远程监控linux服务器的资源占用(单线程demo)

import paramiko
import time
import openpyxl
from openpyxl.styles import Font
color='ff0000'
font=Font(u'宋体',size=11,bold=True,italic=False,strike=False,color=color)
hostname='127.0.0.1'
port=22
username='root'
password='password'
filepath='C:\\Users\\wqx\\Desktop\\memuseinfo.xlsx'

try:
    wb=openpyxl.load_workbook(filepath)
except FileNotFoundError as e:
    wb=openpyxl.Workbook()
    print('文件{0}不存在,程序已自动创建该文件'.format(filepath))
wb.create_sheet(str(port))
sh=wb[str(port)]
sh.cell(row=1,column=1,value='内存占用率')
sh.cell(row=1,column=2,value='记录时间')
wb.save('C:\\Users\\wqx\\Desktop\\memuseinfo.xlsx')
count=1
wb.close()

while True:
    wb=openpyxl.load_workbook('C:\\Users\\wqx\\Desktop\\memuseinfo.xlsx')
    sh=wb[str(port)]
    client=paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname,port,username,password,compress=True)
    sftp_client=client.open_sftp()#读取“/proc/meminfo文件用于内存占用计算”
    remote_file=sftp_client.open('/proc/meminfo','r') 
    count=count+1
    for line in remote_file: #内存信息获取
        if line.startswith('MemTotal:'):
	        mem_total=int(line.split()[1])
	        #print(mem_total)
        elif line.startswith('MemFree:'):
	        mem_free=int(line.split()[1])
	        #print(mem_free)
        elif line.startswith('Buffers:'):
	        mem_buffers=int(line.split()[1])
	        #print(mem_buffers)
        elif line.startswith('Cached:'):
	        mem_cached=int(line.split()[1])
	        #print(mem_cached)
        else:
	        continue
    remote_file.close()#关闭远程文件连接及ssh连接,防止出现thread.error错误
    client.close()
    physical_percent=(float((mem_total-(mem_free+mem_buffers+mem_cached)))/mem_total)*100
    write_value=str(round(physical_percent,2))+'%'
    print("{0}端口:{1} 内存占用为{2:.2f}%".format(hostname,port,physical_percent))
    if physical_percent > 75: #占用大于75则标红
        sh.cell(row=count,column=1,value=write_value).font=font
        sh.cell(row=count,column=2,value=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())).font=font
    else:
        sh.cell(row=count,column=1,value=write_value)
        sh.cell(row=count,column=2,value=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    wb.save('C:\\Users\\wqx\\Desktop\\memuseinfo.xlsx')
    wb.close()
    time.sleep(30)#30秒统计周期

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值