在日常的系统管理工作中,监测服务器的资源占用情况至关重要,我们需要及时获得通知以便采取相应措施。我新装了一台UbuntuServer服务器,写了一个可以定期收集服务器的CPU、内存、网络和磁盘信息,并通过邮件将这些信息发送给管理员的Python脚本,分享一下。
看效果:
话不多说,直接上源码:
用到了psutil先安装一下需要的psutil库:
pip install psutilmail.py
import psutil  
import smtplib  
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart  
import datetime  # 配置SMTP服务器和邮箱信息  
smtp_server = # SMTP服务器地址  
smtp_port =   # SMTP服务器端口  
sender_email =    # 发件人邮箱  
password =    # 发件人邮箱密码  
receiver_email =  # 管理员邮箱  def get_system_info():  # 获取当前时间  now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # CPU信息  cpu_count = psutil.cpu_count(logical=False)  cpu_percent = psutil.cpu_percent(interval=1)  # 内存信息  memory = psutil.virtual_memory()  mem_total = round(memory.total / (1024.0 ** 3), 2)  mem_used = round(memory.used / (1024.0 ** 3), 2)  mem_percent = memory.percent  # 网络信息  net_io_counters = psutil.net_io_counters()  bytes_sent = round(net_io_counters.bytes_sent / (1024.0 ** 3), 2)  bytes_recv = round(net_io_counters.bytes_recv / (1024.0 ** 3), 2)  # 磁盘信息  disk_usage = psutil.disk_usage('/')  disk_total = round(disk_usage.total / (1024.0 ** 3), 2)  disk_used = round(disk_usage.used / (1024.0 ** 3), 2)  disk_percent = disk_usage.percent# 格式化信息  system_info = f"""  Time: {now}  CPU Count: {cpu_count}  CPU Usage: {cpu_percent}%  Memory Total: {mem_total} GB  Memory Used: {mem_used} GB  Memory Usage: {mem_percent}%  Bytes Sent: {bytes_sent} GB  Bytes Received: {bytes_recv} GB  Disk Total: {disk_total} GB  Disk Used: {disk_used} GB  Disk Usage: {disk_percent}%  """  return system_info  def send_email(subject, body, sender, password, receiver):  msg = MIMEMultipart()  msg['From'] = sender  msg['To'] = receiver  msg['Subject'] = subject  msg.attach(MIMEText(body, 'plain'))  server = smtplib.SMTP(smtp_server, smtp_port)  server.starttls()  server.login(sender, password)  text = msg.as_string()  server.sendmail(sender, receiver, text)  server.quit()  # 获取系统信息  
system_info = get_system_info()  # 发送邮件  
subject = 'UbuntuServer System Information'  
send_email(subject, system_info, sender_email, password, receiver_email)
注意画框的部分要写填你自己的信息

把mail.py复制下来,现在可以运行测试一下,运行一次即可向管理员邮箱发一次信息。
再打开命令行使用corn让它定时运行:
编辑当前用户的crontab文件
crontab -e打开编辑器中,添加任务(写你自己的路径)
0 */2 * * * /path/to/your/script/mail.py这行的含义是:
0表示在每小时的第0分钟运行。
*/2表示每两个小时。
*表示每天的任意一天。
*表示每个月的任意一月。
*表示每周的任意一周。
/path/to/your/script/mail.py是你的mail.py脚本的完整路径。
我设置的是两个小时执行一次,确保将/path/to/your/script/mail.py替换为你的mail.py脚本的实际路径。
保存并关闭文件后,cron会自动加载新的定时任务。你可以使用以下命令来查看当前用户的cron任务:
crontab -l如果设置成功就可以等待接收邮件了