4

SSH登录服务器发送提醒

 1 year ago
source link: https://shidawuhen.github.io/2022/05/31/SSH%E7%99%BB%E5%BD%95%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%8F%91%E9%80%81%E6%8F%90%E9%86%92/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

当有人登录服务器后,如何感知?本文讲述当有人通过SSH登录服务器后,将登录信息发送到微信企业号。

shell

先创建shell脚本,用于获取登录信息。

#!/bin/bash
#获取登录者的用户名
#user=$USER
user=$(getent passwd `who` | head -n 1 | cut -d : -f 1)
if [ "" = "$user" ]; then
user="default"
fi
#获取登录者的IP地址
ip=${SSH_CLIENT%% *}
echo $ip
if [ "$ip" = "" ]; then
ip="default"
fi
#获取登录的时间
time=$(date +%F-%k:%M)
#服务器的IP地址
server=`ifconfig eth1|sed -n '2p'|awk -F ":" '{print $2}'|awk '{print $1}'`
if [ "$server" = "" ]; then
server="default"
fi
python /etc/ssh/a.py $user $ip $time $server

python

创建python代码,用于将信息发送到企业号上。上面的shell脚本调用该python程序。企业号的信息填充到init中。如果不想用企业号,也可以使用邮件。以前最方便的是直接使用方糖,但被大家玩坏了。

## 微信推送脚本

import requests
import json
import sys

class Wechat_Info():
"""
微信推送
"""

def __init__(self):

self.partyID = '1'
self.corpID = '**'
self.secret = '**'
self.agentID = '**'

def __get_token(self, corpid, secret):

Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
Data = {
"corpid": corpid,
"corpsecret": secret
}
r = requests.get(url=Url, params=Data)
token = r.json()['access_token']

return token

def send_message(self, message, messagetype): # text textcard markdown

token = self.__get_token(self.corpID, self.secret)

url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"

data = {
"toparty": self.partyID,
"msgtype": messagetype,
"agentid": self.agentID,
messagetype: {
"content": message
},
"safe": "0"
}

result = requests.post(url=url, data=json.dumps(data))

return result.text

def send_file(self, path, filetype): # image, vioce, video, file

token = self.__get_token(self.corpID, self.secret)

post_url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={filetype}"
data = {"media": open(path, 'rb')}

r = requests.post(url=post_url, files=data)
media_id = r.json()['media_id']

url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"

data = {
"toparty": self.partyID,
"msgtype": filetype,
"agentid": self.agentID,
filetype : {
"media_id" : media_id
},
"safe": "0"
}

result = requests.post(url=url, data=json.dumps(data))

return result.text

if __name__ == '__main__':
user = sys.argv[1]
ip = sys.argv[2]
time = sys.argv[3]
server = sys.argv[4]
msg = f"用户{user}在{time}登录{ip}服务为{server}"
print(msg)

wechat_info = Wechat_Info()
result = wechat_info.send_message(msg,"text")
print(result)

将上述sh文件命名为sshrc,将sh文件和python文件放到系统的/etc/ssh/ 目录下。

如果只关注指定用户,可将文件放到如下目录:

  • Linux用户登陆都会执行/etc/profile文件
  • Ubuntu/Debian系统环境 编辑根目录下 ~/.bashrc文件
  • CentOS系统 编辑 ~/.bash_profile文件

添加代码:

sh shell文件名

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK