python运维 获取服务器信息,监控异常,进行通知(邮件/微信/钉钉/短信)
时间: 2023-08-16 16:07:30 浏览: 153
实现这个功能,你可以使用以下几个库:
1. paramiko:用于连接远程服务器并执行命令
2. psutil:用于获取服务器的性能指标,如 CPU 使用率、内存使用率等
3. smtplib:用于发送邮件通知
4. wxpy:用于发送微信消息
5. dingtalkchatbot:用于发送钉钉消息
6. requests:用于发送短信通知
下面是一个简单的实现示例:
```python
import paramiko
import psutil
import smtplib
from email.mime.text import MIMEText
from wxpy import *
from dingtalkchatbot.chatbot import DingtalkChatbot
import requests
# 连接远程服务器
def ssh_connect(ip, port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
return ssh
# 获取服务器性能指标
def get_server_status():
cpu_percent = psutil.cpu_percent()
mem_percent = psutil.virtual_memory().percent
disk_percent = psutil.disk_usage('/').percent
return cpu_percent, mem_percent, disk_percent
# 发送邮件通知
def send_email(receiver, subject, content):
mail_host = 'smtp.xxx.com'
mail_user = 'xxx@xxx.com'
mail_pass = 'xxx'
sender = 'xxx@xxx.com'
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = sender
message['To'] = receiver
message['Subject'] = subject
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.quit()
# 发送微信消息
def send_wechat(content):
bot = Bot()
my_friend = bot.friends().search('朋友的微信昵称')[0]
my_friend.send(content)
# 发送钉钉消息
def send_dingtalk(content):
webhook = '钉钉机器人webhook'
dingtalk = DingtalkChatbot(webhook)
dingtalk.send_text(content)
# 发送短信通知
def send_sms(receiver, content):
url = '短信API地址'
params = {
'receiver': receiver,
'content': content
}
requests.post(url, params=params)
if __name__ == '__main__':
# 连接远程服务器并执行命令
ssh = ssh_connect('服务器IP', '22', '用户名', '密码')
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.read().decode())
ssh.close()
# 获取服务器性能指标
cpu_percent, mem_percent, disk_percent = get_server_status()
if cpu_percent > 80 or mem_percent > 80 or disk_percent > 80:
# 如果有异常,发送通知
send_email('收件人邮箱', '服务器异常', 'CPU使用率:{}%,内存使用率:{}%,磁盘使用率:{}%'.format(cpu_percent, mem_percent, disk_percent))
send_wechat('服务器异常:CPU使用率:{}%,内存使用率:{}%,磁盘使用率:{}%'.format(cpu_percent, mem_percent, disk_percent))
send_dingtalk('服务器异常:CPU使用率:{}%,内存使用率:{}%,磁盘使用率:{}%'.format(cpu_percent, mem_percent, disk_percent))
send_sms('收件人手机号', '服务器异常:CPU使用率:{}%,内存使用率:{}%,磁盘使用率:{}%'.format(cpu_percent, mem_percent, disk_percent))
```
你需要根据自己的实际情况修改代码中的参数,比如服务器的 IP 地址、用户名、密码、收件人邮箱、微信昵称、钉钉机器人 webhook、短信 API 地址等。
阅读全文