我现在的工作中,除了统计cpu个数和cpu使用率,暂时没想起来还需要统计哪个指标。开始不知道每执行一次命令都可以开通一次paramiko通道,颇费一番周折,后来看到一个大神这样用了,那么我的程序实现就简单多了。
下面是我的server.txt文件。
def get_cpu():
with open('server.txt', 'r', encoding='utf-8') as rfile:
servers = rfile.readlines() # 按行读取
for item in servers: # 遍历列表,
d = dict(eval(item)) # 列表中的第一个元素,编写成字典
d.update(username="XXX", password="XXX", port='22') # 第一个元素更新
value_list = []
value_list.append(d['id'])
value_list.append(d['username'])
value_list.append(d['password'])
value_list.append(d['port'])
hostinfo = value_list[0] + ',' + value_list[1] + ',' + value_list[2] + ',' + value_list[3]
hostinfo = hostinfo.strip()
hostip, username, password, port = hostinfo.split(',')
print(hostip)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostip, port=port, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command('cat /proc/cpuinfo')
str_out = stdout.read().decode()
str_err = stderr.read().decode()
cpu_num = re.findall('processor.*?(\d+)', str_out)[-1]
cpu_num = str(int(cpu_num) + 1)
cpuinfo = stdout.readlines()
print(cpuinfo)
print('******************************cpu监控,对应主机[name:%s]*********************************' % hostip)
print("*******************时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************")
print (u"CPU个数为:", cpu_num)
stdin, stdout, stderr = ssh.exec_command("top -b -n1 | sed -n '3p'|awk '{print $2}'")
str_out = stdout.read().decode()
print('当前CPU使用率为:' + str_out.strip() + '%')
ssh.close()