Most domestic cloud servers come with SSH login prompt functionality, which I think is great. However, many cloud server providers that do not have deeply customized system images do not have remote login notification functionality. So I wrote a small script to implement the function of pushing login information to Telegram when logging in remotely.
File name 00-ssh-login-alarm-telegram.sh
(you can also customize it yourself), place the file in the /etc/profile.d
directory.
#!/bin/bash
# Fill in the token of the Telegram bot
token=
# Fill in your own Telegram ID
id=
# VPS IP
vpsip=$(curl -s ip.sb -4)
# Login time
logintime=$(TZ=UTC-8 date '+%Y-%m-%d %H:%M:%S')
# Remote login IP
loginip=$(who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g')
# IP organization name
loginfrom=$(curl -s https://api.ip.sb/geoip/${loginip} | jq .asn_organization)
curl -s "https://api.telegram.org/bot${token}/sendMessage?chat_id=${id}" --data-binary "&text=NewLogin:%0AVPS: ${vpsip}%0ATime: ${logintime}%0ALogin from:%0A${loginip}%0A${loginfrom}" > /dev/null
Because jq
is used as a tool for parsing JSON, it needs to be installed manually in the package manager.
Usage:
NewLogin:
VPS: ***.***.***.***
Time: 2020-09-13 12:41:24
Login from:
***.***.***.***
"asn_organization"
The script uses the API from ip.sb
Updated on October 20, 2021#
The script has been updated several times in the middle, and now the script can implement some functions that were previously missing.
- Display the login username
- Do not block the TTY of the login user
#!/bin/bash
# Fill in the token of the Telegram bot
token=
# Fill in your own Telegram ID
id=
localip=$(who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g')
echo 'localip=$(curl -s ip.sb -4)' > tg.sh
echo 'user=$(whoami)' >> tg.sh
echo 'logintime=$(TZ=UTC-8 date "+%Y-%m-%d %H:%M:%S")' >> tg.sh
echo 'loginip='${localip} >> tg.sh
echo 'loginfrom=$(curl -s https://api.ip.sb/geoip/${loginip} | jq -r .asn_organization)' >> tg.sh
echo 'curl -s "https://api.telegram.org/bot'${token}'/sendMessage?chat_id='${id}'" --data-binary "&text=NewLogin:%0AVPS:${user}@${localip}%0ATime: ${logintime}%0ALogin from:%0A${loginip}%0A${loginfrom}" > /dev/null && rm tg.sh' >> tg.sh
bash tg.sh &