基于Python与psutil的服务器端口及系统资源监控脚本
本文介绍如何使用Python编写一个轻量级服务器监控脚本。通过调用psutil模块获取CPU、内存及磁盘I/O状态,结合netstat命令提取特定端口(如3389)的连接IP。脚本利用正则表达式解析数据,并通过SMTP协议将监控结果发送至指定邮箱,实现自动化运维监控。
前言:
此前一直计划开发一款监控类脚本,最终聚焦于运维场景,并完成了该脚本的编写。下文将详细介绍具体实现过程。
准备工作:
需安装psutil模块(基础用法可参考相关文档:https://www.jb51.net/article/65044.htm)
核心实现:
import os
import time
import re
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
import psutil
while True:
def jianca():
print('[+]Write a port to a file')
querys=os.popen('netstat -an').read()
wsd=open('netstat.txt','w')
wsd.write(querys)
wsd.close()
jianca()
def swsd():
global usd,ow
wsd=open('netstat.txt','r')
swd=wsd.read()
odf=re.findall('(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d):(3389)',swd)
usd=odf[0]
print('[+]Query the IP address of a remote connection')
df=usd[0],usd[1],usd[1],usd[3]
wdst=".".join(df)
ow=wdst+":"+usd[4]
print(usd[0],'.',usd[1],'.',usd[2],'.',usd[3]+":",usd[4])
swsd()
def ipdw():
global wdf,ip,timsd
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
dw=s.connect(('8.8.8.8',80))
ip=s.getsockname()[0]
print('[+]loacl IP:',ip)
wdf=os.popen('tasklist').read()
timsd=time.strftime('%Y-%m-%d',time.localtime(time.time()))
ipdw()
def yunwei():
global cput,cp
cput=psutil.cpu_times()
cp=psutil.disk_io_counters()
yunwei()
def stm():
serder="搜狐邮箱@sina.cn"
revw="收件箱@qq.com"
zhengwen='[+]Query the IP address of a remote connection''{}\n' \
'[+]loacl IP:{}\n' \
'[+]A program running in the background:{}\n' \
'[+]The user / system / idle time of statistical CPU:{}\n' \
'[+]Disk I/O usage{}\n' \
'[+]Last send time:{}\n' .format(ow,ip,wdf,cput,cp,timsd)
msg=MIMEText(zhengwen)
msg['From']=Header('你的搜狐邮箱@sina.cn')
msg['TO']=Header('收件箱@qq.com','utf-8')
sub="实时监控"
msg['subject']=Header(sub,'utf-8')
try:
smtp=smtplib.SMTP()
smtp.connect('smtp.sina.cn',25)
smtp.login('搜狐邮箱@sina.cn','登录密码')
smtp.sendmail(serder,revw,msg.as_string())
print('[+]发送出')
except Exception as g:
print('[-]发送失败,原因:',g)
stm()
time.sleep(3600)
脚本首先获取端口状态,并将结果写入txt文件,随后使用正则表达式从中提取所需的IP地址和端口信息。
接着,脚本获取后台运行的程序列表,并采集CPU使用率、磁盘I/O及内存数据,最后通过邮件服务将信息发送至指定收件箱。
邮件发送目标为预设的邮箱地址。
运行效果截图:



总结:
以上内容为本文的全部介绍,希望能为读者的学习或工作提供参考。如有疑问,欢迎留言交流,感谢支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









