使用python监控linux系统资源

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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值