远程查看服务器资源使用情况
单机实现
import paramiko
# 定义远程服务器的连接信息
hostname = '192.168.2.198'
username = 'root'
password = '123456'
# 创建SSH 客户端对象
client = paramiko. SSHClient ( )
client. set_missing_host_key_policy ( paramiko. AutoAddPolicy ( ) )
try :
# 连接到远程服务器
client. connect ( hostname, username= username, password= password)
# 获取CPU 使用情况
stdin, stdout, stderr = client. exec_command ( 'top -bn1 | grep "Cpu(s)"' )
cpu_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'CPU使用情况:{cpu_output}' )
# 获取IO 使用情况
stdin, stdout, stderr = client. exec_command ( 'iostat -d' )
io_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'IO使用情况:{io_output}' )
# 获取内存使用情况
stdin, stdout, stderr = client. exec_command ( 'free -m' )
memory_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'内存使用情况:{memory_output}' )
# 获取磁盘使用情况
stdin, stdout, stderr = client. exec_command ( 'df -h' )
disk_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'磁盘使用情况:{disk_output}' )
except Exception as e :
print ( f'发生错误:{str(e)}' )
finally :
# 关闭SSH 连接
client. close ( )
多机实现
import paramiko
def check_server_info ( hostname, username, password) :
# 创建SSH 客户端对象
client = paramiko. SSHClient ( )
client. set_missing_host_key_policy ( paramiko. AutoAddPolicy ( ) )
try :
# 连接到远程服务器
client. connect ( hostname, username= username, password= password)
# 获取CPU 使用情况
stdin, stdout, stderr = client. exec_command ( 'top -bn1 | grep "Cpu(s)"' )
cpu_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'主机 {hostname} 的CPU使用情况:{cpu_output}' )
# 获取IO 使用情况
stdin, stdout, stderr = client. exec_command ( 'iostat -d' )
io_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'主机 {hostname} 的IO使用情况:{io_output}' )
# 获取内存使用情况
stdin, stdout, stderr = client. exec_command ( 'free -m' )
memory_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'主机 {hostname} 的内存使用情况:{memory_output}' )
# 获取磁盘使用情况
stdin, stdout, stderr = client. exec_command ( 'df -h' )
disk_output = stdout. read ( ) . decode ( 'utf-8' ) . strip ( )
print ( f'主机 {hostname} 的磁盘使用情况:{disk_output}' )
except Exception as e :
print ( f'连接主机 {hostname} 发生异常:{str(e)}' )
finally :
# 关闭SSH 连接
client. close ( )
# 定义多台主机的连接信息
hosts = [
{ 'hostname' : '192.168.2.198' , 'username' : 'root' , 'password' : '123456' } ,
{ 'hostname' : '192.168.2.166' , 'username' : 'root' , 'password' : '123qwe' } ,
#{ 'hostname' : '192.168.2.200' , 'username' : 'root' , 'password' : '123456' }
]
# 连接每台主机并获取信息
for host in hosts :
check_server_info ( host[ 'hostname' ] , host[ 'username' ] , host[ 'password' ] )