#!/usr/bin/python
# -*- coding:utf8 -*-
# Email:[email protected]
__author__ = 'chenwx'
 
import paramiko
import re
from time import sleep
 
linux_info=(
            ['ssoweb12','192.168.5.32'],
            ['ssoweb17','192.168.5.37'],
            ['ssoweb18','192.168.5.38']
            )
 
def cpu_r(cpu_stat):
    sys_cpu_info_t = re.findall(r'cpu .*\d',cpu_stat)
    z_str = ' '.join(sys_cpu_info_t)
    z_list = list(z_str.split())
    z_list.remove("cpu")
 
    f_line_a=[]
    for i in z_list:
        i=int(i)
        f_line_a.append(i)
    total = sum(f_line_a)
    idle = f_line_a[3]
    return total,idle
 
server_user='root'
server_pw='passw0rd'
server_info={}
 
for i in linux_info:
    server_id=i[0]
    server_ip=i[1]
    ss = paramiko.SSHClient()
    ss.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
    ss.connect(server_ip,22,server_user,server_pw)
    stdin,stdout,stderr=ss.exec_command('cat /proc/stat')
    sys_cpu_stat = stdout.read()
    total_a,idle_a=cpu_r(sys_cpu_stat)
    sleep(3)
    stdin,stdout,stderr=ss.exec_command('cat /proc/stat')
    sys_cpu_stat = stdout.read()
    total_b,idle_b=cpu_r(sys_cpu_stat)
    ss.close()
 
    sys_idle = idle_b - idle_a
    sys_total = total_b - total_a
    sys_us = sys_total - sys_idle
    cpu_a = (float(sys_us)/sys_total)*100
    cpu_b = str(round(cpu_a,2))+'%'
 
    server_info_list=[server_id,server_ip,cpu_b]
    server_info[server_id]=server_info_list
 
print server_info
登录后复制
08-18 22:22