实时监控linux服务器登入信息
准备条件:
1、一个带有webhook地址的robot
2、带有requests和json包的Python3环境(也可以使用bash脚本)
Python程序:
#!/usr/bin/python3 # -*- coding: utf-8 -* ##################################################################### # Author : zhoujt # Tel : 186xxxxxx # Date : 2022-11-15 # FileName :login_remote.py # Description: New Login Reminder ##################################################################### import requests import json import re, os def do_post(payload): headers = { 'Content-Type': 'application/json' } try: r = requests.post("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c10e3069-1903-4b781953-tyy3dc", data=payload, headers=headers) if r.status_code == 200: return True else: return False except Exception as e: return False def send_mes(mes_info): msgtype = "text" content = {} content['msgtype'] = msgtype msg_type = {"content": mes_info} content['text'] = msg_type data = json.dumps(content) try: status = do_post(data) if status != False: return 0 else: return 1 except Exception as e: return 1 def message_info(): #适用于本地服务器 #user_ip = os.popen("ifconfig | grep inet| head -1 | awk -F ' ' '{print $2}'").readline() user_ip = os.popen("curl -s ip.sb") whoami = os.popen("whoami").readline() login_ip = os.popen("who am i |awk -F '[()]' '{print $2}'").readline() log_time = os.popen("date '+%Y-%m-%d-%H:%M:%S'").readline() mes_info = "用户: %s成功从 %s登录 %s时间 %s" % (str(whoami), str(login_ip), str(user_ip), str(log_time).replace("\n","")) return mes_info if __name__ == '__main__': msg_today = message_info() send_mes(mes_info=msg_today)
登录通知:
在 /etc/profile 最后一行追加
/usr/bin/python3 /tmp/zhoujt/scripts/login_remote.py > /dev/null 2>&1
这样,用户登录的时候就会加载系统配置,然后机器人通知到机器管理员