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秒统计周期