无法通过 python paramiko 获取远程服务器上的 cpu 利用率
Unable to fetch cpu utilization on remote server through python paramiko
我正在尝试使用 python paramiko 获取远程服务器上的 CPU 利用率。
import paramiko
from socket import error as socket_error
import os
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect('10.10.0.1', username = 'test1', pkey = mykey)
idin, idout, iderr = ssh_remote.exec_command("ps aux | grep -i 'test' | grep -v grep | awk '{print }'")
id_out = idout.read().decode().splitlines()
id_out_1 = id_out[0]
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'cpu'))
cp = reout.read().decode().splitlines()
print cp
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
接收以下输出
[u'CPU', u' -']
而不是
[u'%CPU', u'0.1']
不确定这里有什么问题。请帮忙解决这个问题。
您需要 %cpu
而不是 cpu
因此您需要更改:
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'cpu'))
到
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'%cpu'))
这会给你 CPU 使用百分比。
我正在尝试使用 python paramiko 获取远程服务器上的 CPU 利用率。
import paramiko
from socket import error as socket_error
import os
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect('10.10.0.1', username = 'test1', pkey = mykey)
idin, idout, iderr = ssh_remote.exec_command("ps aux | grep -i 'test' | grep -v grep | awk '{print }'")
id_out = idout.read().decode().splitlines()
id_out_1 = id_out[0]
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'cpu'))
cp = reout.read().decode().splitlines()
print cp
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
接收以下输出
[u'CPU', u' -']
而不是
[u'%CPU', u'0.1']
不确定这里有什么问题。请帮忙解决这个问题。
您需要 %cpu
而不是 cpu
因此您需要更改:
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'cpu'))
到
rein, reout, reerr = ssh_remote.exec_command("ps -p %s -o %s" %(id_out_1 ,'%cpu'))
这会给你 CPU 使用百分比。