import paramiko
import re
import time
# 创建SSHClient实例对象
ssh = paramiko.SSHClient()
# 调用方法,标识没有远程机器的公钥,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程机器 地址端口用户名密码
def quwenjian(command,filename):
stdin, stdout, stderr = ssh.exec_command(command)
wen=stdout.read()
with open(filename,'wb') as f:
f.write(wen)
command={'neichun.log':"cat /proc/meminfo",
'xiancheng.log':'vmstat 1 2 | tail -n 1',
'cpu.log':'cat /proc/cpuinfo',
'fuzai.log':'cat /proc/loadavg',
'wangluo.log':'cat /proc/net/dev',
'cipan.log':'df -h',
'duankou.log':'netstat -tplnu'
}
while True:
try:
ssh.connect("192.168.126.128",22,"root","kongziyue")
for i in list(command.items()):
quwenjian(i[1], i[0])
all_info = {}
with open('neichun.log', 'r') as f:
a = f.read()
split_list = a.split('\n')
for i in split_list:
try:
am = re.findall(r'(.*?):.*?(\d+)', i)
all_info[am[0][0]] = am[0][1]
except:
pass
free = int(all_info['MemFree']) + int(all_info['Buffers']) + int(all_info['Cached'])
use_rate = 1 - free / int(all_info['MemTotal'])
# -------------------------------------------------------------------------------------------------
with open('xiancheng.log', 'r') as f:
a = f.read()
split_list = re.findall('(\d+)\s',a)
sheng_yu_cpu=split_list[-3]
xi_tong_use_cpu = split_list[-4]
user_use_cpu = split_list[-5]
yun_xing_jin_cheng_shu=split_list[1]
# ----------------------------------------------------------------
with open('wangluo.log', 'r') as f:
a = f.read()
split_list=a.split('\n')
split_list2=split_list[2]
wang_luo_fa_bao=re.findall('(\d+)\s',split_list[2])
print(wang_luo_fa_bao)
print((wang_luo_fa_bao[0]),wang_luo_fa_bao[8])
print(yun_xing_jin_cheng_shu+','+sheng_yu_cpu+','+xi_tong_use_cpu+','+user_use_cpu+',')
print(use_rate)
# ,sheng_yu_cpu,xi_tong_use_cpu,user_use_cpu
with open('result.csv','a') as f:
wen=str(wang_luo_fa_bao[0])+','+str(wang_luo_fa_bao[8])+','+\
str(yun_xing_jin_cheng_shu)+','+str(sheng_yu_cpu)+','+str(xi_tong_use_cpu)+','+str(user_use_cpu)+','+\
str(use_rate)+','+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'\n'
f.write(wen
)
time.sleep(10)
except TimeoutError:
print('不能被连接上')
exit()
finally:
ssh.close()
使用python监控linux系统资源
最新推荐文章于 2024-05-14 20:00:00 发布