def os_get_data(host,user,password): ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(host, 22, user, password) std_in_net, std_out_net, std_err_net = ssh_client.exec_command('cat /proc/net/dev') std_in_cpu, std_out_cpu, std_err_cpu = ssh_client.exec_command('cat /proc/stat | grep "cpu "') stdout_net = std_out_net.read().decode() stderr_net = std_err_net.read().decode() stdout_cpu = std_out_cpu.read().decode() stderr_cpu = std_err_cpu.read().decode() if stderr_net != "": print(stderr_net) else: list_net = stdout_net.split('\n') for each_net in list_net: if each_net.find('eth0') > 0: list_eth0 = each_net.split(":")[1] recv = float(list_eth0.split()[0]) send = float(list_eth0.split()[8]) list_eth0 = list_net[3].split(":")[1] recv = float(list_eth0.split()[0]) send = float(list_eth0.split()[8]) if stderr_cpu != "": print(stderr_cpu) else: cpu_time_list = re.findall('\d+', stdout_cpu) cpu_idle = cpu_time_list[3] total_cpu_time = 0 for t in cpu_time_list: total_cpu_time = total_cpu_time + int(t) return (recv, send ,total_cpu_time,cpu_idle) # NIC traffic, CPU usage def os_get_info(host,user,password): # first collection recv_first,send_first,total_cpu_time1,cpu_idle1 = os_get_data(host,user,password) time.sleep(1) # second collection recv_second,send_second,total_cpu_time2,cpu_idle2 = os_get_data(host,user,password) recv_data = round((recv_second - recv_first)/1024,2) send_data = round((send_second - send_first)/1024,2) cpu_usage = round(1 - (float(cpu_idle2) - float(cpu_idle1)) / (float(total_cpu_time2) - float(total_cpu_time1)), 2) return(recv_data,send_data,cpu_usage) if __name__ == '__main__': print os_get_info('192.168.48.10','root','oracle')
Python monitors network card traffic and CPU usage
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324735306&siteId=291194637
Recommended
Ranking