# paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作
# 基于linux的ssh服务
import paramiko
import requests
import json
import datetime
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(now)
# 钉钉告警接口地址
api_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxx'
headers = {'Content-Type': 'application/json;charset=utf-8'}
# 钉钉告警
def msg(text):
json_text = {
"msgtype": "markdown",
"markdown": {
"title": "状态通知",
"text": text
}
}
print(requests.post(api_url, json.dumps(json_text), headers=headers).content)
def exec_ssh_command(ssh_command):
# 创建一个ssh对象
ssh = paramiko.SSHClient()
# 如果之前没有连接过的ip,会出现Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
key = paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(key)
# 连接服务器
ssh.connect(
hostname='172.16.0.11', port=22, username='root', password='111111', timeout=5
)
# 执行shell命令,返回的是一个元组
# ls /opt/bi/kettle/etljobs_svn/lens_olap/
stdin, stdout, stderr = ssh.exec_command(ssh_command)
# 返回shell命令执行结果
# for i in stdout.readlines():
# print(i)
#
##获取输出结果,decode('utf-8')解码是为了存在中文能够正常显示
result = stdout.read().decode('utf-8')
ssh.close()
return result
if __name__ == '__main__':
# ps -ef 命令就是列出当前所有的进程信息
ssh_command = 'ps -ef|grep "nginx" |grep -v grep|wc -l'
result = exec_ssh_command(ssh_command)
# 5
print(result)
# 当应用程序进程数小于1时推送告警
if int(result) < 1:
text = f"""
时间:{now}
服务器地址:172.16.0.11
告警信息:nginx 程序运行异常,请注意查看
"""
msg(text)