通过企业微信机器人实现ssh登陆发送ip警告
因实际网络环境复杂,直接添加ssh白名单风险较大,使用sshrc文件调用企业微信api实现警告白名单。
$ chmod a+x /etc/ssh/sshrc
$ cat /etc/ssh/sshrc
#!/bin/bash #登录用户 user=$USER #发起登陆ip ip=${SSH_CLIENT%% *} #时间 time=$(date +%F%t%k:%M) #服务器名 server=$HOSTNAME #判断如果登录者的IP地址不是指定的IP,则发邮件报警 if [ "$ip" != "12.123.12.12" ] && [ "$ip" != "12.34.12.24" ];then echo -e "被登陆节点:$server \n登陆时间:$time \n用户:$user \n发起登陆 ip:$ip \n" > /tmp/msg #也可以发邮件 # echo -e "time:$time \nuser:$user \nlogin ip:$ip \n"|mail -s "server:$server" xiaoming@qq.com #调用给机器人推消息的脚本 python2.7 /tmp/sent_ssh.py > /dev/null 2>&1 fi
下面是推消息的脚本代码:
$ cat /tmp/sent_ssh.py
## coding: utf-8 # import sys import os import smtplib import pandas as pd import pymysql import requests p=os.popen('cat /tmp/msg') x=p.read() print(x) if not x.strip(): print 'x is null' else: url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxxxxxxxxxxx" headers = {"Content-Type": "text/plain"} data = { "msgtype": "text", "text": { "content": x, } } r = requests.post(url, headers=headers, json=data) print(r.text)
登陆实现效果:


浙公网安备 33010602011771号