使用Python自动发送服务器信息

本文介绍了一个使用Python编写的系统监控脚本,该脚本利用psutil库收集Linux主机的CPU使用率、内存使用情况、磁盘信息、网络流量等,并通过SMTP服务将收集到的数据以邮件形式发送给管理员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相关Python库
  • email
  • smtplib
  • os
  • psutil
主要过程:

指定Linux主机,可以是跳板机之类的,在登录用户下的~/.bashrc或者全局profile文件中指定本python脚本执行,对于python脚本主要包括:获取系统信息:CPU、磁盘、网络IO、进程相关、等信息将这些信息打包成文件或者直接作为消息正文发送给目标邮箱,以此来汇报系统的运行状态、登录用户等相关信息。

服务器信息获取:
#!/usr/local/bin/python3
#sysinfo.py
import psutil
import datetime
import time
import os
# 检测时间
CheckTime= time.strftime("%Y-%m-%d %H:%M:%S-%p %B-%A",time.localtime())
print("系统检测时间:",CheckTime)
#系统信息
os.system("uname -a")
# 用户登录信息
print("当前有%s个用户,分别是:"%len(psutil.users()))
user_list=[user for user in psutil.users()]
for i in psutil.users():
    print("用户名:%s,pty:%s,登录源设备:%s,进程号:%s"%(i.name,i.terminal,i.host,i.pid))
# 查看cpu相关信息
print("服务器CPU个数: %s" % psutil.cpu_count(logical=False))
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup使用率: %s" % cpu)

#查看内存信息
free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
print("物理内存: %s G" % total)
print("剩余物理内存: %s G" % free)
print("物理内存使用率: %s %%" % int(memory * 100))
# 系统启动时间
print("系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))

#网卡,可以得到网卡属性,连接数,当前流量等信息
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
print("网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))

psutil更多的使用方法可以查看:https://pypi.org/project/psutil/

邮件发送
#!/usr/local/bin/python3
#mail.py
from email.mime.text import MIMEText
import os
import time
import smtplib
os.system("python3 .sysinfo.py >`date +%F`.txt")
file=open("%s.txt"%time.strftime("%Y-%m-%d",time.localtime()),'r')
text=file.read()
Text=MIMEText(text,'plain','utf-8')
server = smtplib.SMTP("smtp.qq.com", 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login('******@qq.com', '******')
server.sendmail('*****@qq.com', '*****@qq.com', Text.as_string())
os.remove("%s.txt"%time.strftime("%Y-%m-%d",time.localtime()))
server.quit()

这里将脚本文件放到用户家目录下并隐藏,将执行脚本放到.bashrc中使得在用户登录时获取脚本信息,也可以设置成定时任务定时执行。
在.bashrc添加执行脚本 python3 .mail.py,python的自动化监测脚本换成shell来写会相对更简洁一些。
执行效果:

Linux localhost.localdomain 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
文件系统                 容量  已用  可用 已用% 挂载点
/dev/mapper/centos-root   17G   12G  5.9G   66% /
devtmpfs                 1.9G     0  1.9G    0% /dev
tmpfs                    1.9G     0  1.9G    0% /dev/shm
tmpfs                    1.9G   13M  1.9G    1% /run
tmpfs                    1.9G     0  1.9G    0% /sys/fs/cgroup
/dev/sda1               1014M  179M  836M   18% /boot
tmpfs                    378M   12K  378M    1% /run/user/42
tmpfs                    378M     0  378M    0% /run/user/0
tmpfs                    378M     0  378M    0% /run/user/1001
系统检测时间: 2019-07-18 01:12:36-AM July-Thursday
当前有2个用户,分别是:
用户名:root,pty:pts/0,登录源设备:192.168.203.1,进程号:19893
用户名:hades,pty:pts/1,登录源设备:192.168.203.1,进程号:23308
服务器CPU个数: 2
cup使用率: 0.0%
物理内存: 3.68 G
剩余物理内存: 2.49 G
物理内存使用率: 32 %
系统启动时间: 2019-07-17 21:08:04
网卡接收流量 0.88 Mb 网卡发送流量 0.57 Mb

部分信息用python写查不到具体的细节(如磁盘)我直接使用调用shell

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值