互联网服务 2019 年 7 月 3 日

用Telegram管理VPS:我的5个Telegram机器人脚本

本文介绍了如何在VPS上使用Telegram Bot实现自动化操作。通过Bot的API,我们可以方便地编写各种机器人,进行监测、爬虫等操作,并在需要的时候将消息推送给用户。作者在VPS上部署了5个Telegram机器人脚本,其中包括SSH登陆通知、系统负载监控、网站状态监测、定时备份和定时重启机器人。这些机器人可以帮助我们更好地管理VPS,提高工作效率。
Telegram Bot是Telegram强大、好玩的重要原因之一,借助Bot的API,我们可以非常方便地编写机器人,帮助我们完成各种自动化操作。 VPS就是Telegram Bot的应用平台之一,我们可以使用ShellPython等脚本语言编写自动化机器人进行监测、爬虫等工作,并在需要的时候将消息推送给用户、甚至可以在聊天界面进行交互!下面是我在VPS上部署的5个Telegram机器人脚本。

谁登陆了VPS?SSH登陆通知

telegram-sshd-monitor
telegram-sshd-monitor
当有人通过SSH登陆VPS时,自动给用户发送一条通知,包含登陆的IP、地址、时间等信息,以便快速识别未授权的访问。 将以下脚本保存在/etc/profile.d/目录,并添加可执行权限,注意修改用户ID和KEY,每次用户登陆时该脚本将被调用并发送一条Telegram通知。
#!/usr/bin/env bash

# This script is called on SSH login by /etc/profile.d/sshd_telegram.sh
# Modified from https://github.com/MyTheValentinus/ssh-login-alert-telegram

# Your USERID or Channel ID to display alert and key, we recommend you create new bot with @BotFather on Telegram
USERID=(chat ID here)
KEY="bot key here"

for i in "${USERID[@]}"
do
URL="https://api.telegram.org/${KEY}/sendMessage"
DATE="$(date "+%Y-%m-%d %H:%M:%S")"

if [ -n "$SSH_CLIENT" ]; then
	CLIENT_IP=$(echo $SSH_CLIENT | awk '{print $1}')

	SRV_HOSTNAME=$(hostname -f)
	#SRV_IP=$(hostname -I | awk '{print $1}')

	IPINFO="https://ipinfo.io/${CLIENT_IP}"
	IPQUERY=$(curl -s --connect-timeout 2 https://ipinfo.io/${CLIENT_IP})
	
	IPCITY=$(echo ${IPQUERY} | cut -d "," -f2 | cut -d "\"" -f4)
	IPREGION=$(echo ${IPQUERY} | cut -d "," -f3 | cut -d "\"" -f4)
	IPCOUNTRY=$(echo ${IPQUERY} | cut -d "," -f4 | cut -d "\"" -f4)
	IPORG=$(echo ${IPQUERY} |rev | cut -d "," -f1 | rev | cut -d "\"" -f4)

	TEXT="SSH Login(${SRV_HOSTNAME}):
	User: *${USER}*
	Date: ${DATE}
	Client: [${CLIENT_IP}](${IPINFO}) - ${IPCITY}, ${IPREGION}, ${IPCOUNTRY}, ${IPORG}"

	curl -s -d "chat_id=$i&text=${TEXT}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
fi
done

带宽硬盘用了多少?VPS状态日报

telegram-vps-daily-report
telegram-vps-daily-report
#!/bin/bash

vm_key=SolusVM Key
vm_hash=SolusVM hash
vm_addr=https://manage.myvpssolusvm.com

api_key=bot key here
chat_id=chat ID here

# VPS status monitor to telegram
# Version
ver=$(lsb_release -d)
# Node
node=$(uname -n)
# Kernel
kern=$(uname -r)
# Bandwidth
bwarr=($(curl -s --connect-timeout 5 $vm_addr/api/client/command.php?key=$vm_key\&hash=$vm_hash\&action=info\&bw=true | grep -oP '\<bw\>(.)*\<\/bw\>' | cut -d ">" -f2 | cut -d "<" -f1 | tr "," "\n"))
# Uptime
upth=$(uptime |  cut -d',' -f1)
# Disk
dfh=($(df -h | grep xvda ))
# Memory
freeh=($(free -h | grep Mem ))
# Top Processes
toph=$(ps -eo pmem,pcpu,cmd | sort -k 1 -nr | head -5)
# All
report="VPS STATUS(${node}): \
%0A \
${ver} \
%0A Kernel: ${kern} \
%0A \
%0A UPTIME:  ${upth} \
%0A DISK:  Total: ${dfh[1]} Used:${dfh[2]} Avail:${dfh[3]} Used%:${dfh[4]} \
%0A BANDWIDTH:  Total: $(echo "scale=2; ${bwarr[0]}/1024/1024/1024/1024" | bc -l)TB Used: $(echo "scale=3; ${bwarr[1]}/1024/1024/1024" | bc -l)GB Avail: $(echo "scale=2; ${bwarr[2]}/1024/1024/1024/1024" | bc -l)TB  Used%: $(echo "scale=3; 100*${bwarr[1]}/${bwarr[0]}" | bc -l) % \
%0A MEMORY:  Total: ${freeh[1]} Used:${freeh[2]} Avail:${freeh[3]} \
%0A \
%0A ----------------------------- \
%0A TOP Processes(pmem,pcpu,cmd): \
%0A ${toph}"

curl -s -X POST https://api.telegram.org/$api_key/sendMessage -d chat_id=$chat_id -d text="$report" > /dev/null

exit 0

CertBot证书更新状态报告

telegram-certbot-report
telegram-certbot-report
#!/bin/bash

# Update let's encrypt
# 2019/6/5

api_key=bot key here
chat_id=chat ID here

result=$(/opt/certbot-auto renew --renew-hook "systemctl restart nginx")
$result=$(python -c "import urllib, sys; print urllib.quote(sys.argv[1])" "$result")

curl -s -X POST https://api.telegram.org/$api_key/sendMessage -d chat_id=$chat_id -d \
	text="Let's Encrypt Certbot(s2.shuyz.com): \
	%0A \
	${result}"  > /dev/null

exit 0

把Telegram当网盘,VPS文件自动备份

telegram-baskup-data
telegram-baskup-data
#!/bin/bash

# Backup important files to telegram
# 2019/6/5

api_key=bot key here
chat_id=chat ID here

fList=$(tr '\n' ' ' < /opt/scripts/backuplist)
fName=/tmp/s2_backup_$(date +"%FT%H%M%S").tar.gz

tar -czvPf  $fName $fList
curl -F chat_id=$chat_id -F document=@"${fName}" https://api.telegram.org/$api_key/sendDocument  > /dev/null
rm -rf $fName

exit 0
上面的脚本配合添加一个备份列表文件/opt/scripts/backuplist,将需要备份的文件/文件夹逐行添加:
/etc/sysctl.conf
/etc/sysctl.d
/etc/sysconfig/iptables
/etc/sysconfig/ip6tables
/etc/systemd/system/*.service