程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python remote monitoring script: use paramiko and psutil to monitor the CPU, memory, disk and network usage of the remote machine

編輯:Python

subject

Use python Write a script to get the other server cpu Usage rate 、 Memory usage 、 Disk usage 、 Network bandwidth usage

Premise : Establish a secret free channel

SSH Password free login :https://blog.csdn.net/qq_44212783/article/details/126029102

preparation :

yum -y install python3-devel gcc gcc-devel
pip3 install pycrypto
pip3 install paramiko==1.17.1
pip3 install psutil

Monitoring script psut.py
#!/usr/bin/python3
import psutil
import datetime
def linux_monitor():
# cpu The usage rate of 
cup_per = psutil.cpu_percent()
# Memory usage 
mem_per = psutil.virtual_memory().percent
# Disk usage 
disk_per = psutil.disk_usage('/').percent
# Network usage How much data to send and receive net.bytes_recv、net.bytes_sent
net = psutil.net_io_counters()
# Get current system time 
current_time = datetime.datetime.now().strftime("%F %T")
# Splicing shows 
str = ""
str+= "|---------time--------|---cpu---|----memory----|----disk----|--------------net-------------|\n"
str+= "| %s | %s%% | %s%% | %s%% | recv:%.2fMB sent:%.2fMB |\n" \
% (current_time, cup_per, mem_per, disk_per, net.bytes_recv/1024/1024, net.bytes_sent/1024/1024)
print(str)
linux_monitor()
Remote control script monitor.py
#!/usr/bin/python3
import paramiko
# Designate local RSA Private key file 
key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
# Establishing a connection 
trans = paramiko.Transport(('192.168.22.127', 22))
trans.connect(username='root', pkey=key)
# establish ssh object , take _transport Designated as... Above trans
ssh = paramiko.SSHClient()
ssh._transport = trans
# establish sftp object , Specify the channel to connect 
sftp = paramiko.SFTPClient.from_transport(trans)
# Upload psut.py file 
sftp.put(localpath='/root/psut.py', remotepath='/root/p.py')
# Add executable rights , Run script 
ssh.exec_command('chmod +x /root/p.py')
stdin, stdout, stderr = ssh.exec_command('/root/p.py')
print(stdout.read().decode())
# Close the connection 
ssh.close()

operation : In the local (170) function monitor.py Script , You can monitor remote machines (127) Of cpu、 Memory 、 disk 、 Network usage

operation : function psut.py Script , Check out the local cpu、 Memory 、 disk 、 Network usage , Obviously, it is different from the remote machine


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved