opened image

How to track SSH connections to the server using a Telegram bot

To send a notification about a successful login to the server via SSH, it is necessary to track the moment of such a login. We will use the built-in tools of Linux, namely, the global profile settings located in the folder /etc/profile. This profile (which is essentially the initial user settings) will be applied to all users who are logged into the system and for whom the command shell is running. The global profile settings are very flexible, but we are interested in the default execution of all bash files (*.sh) from the folder /etc/profile.d. We will create a simple bash script in this folder, the role of which is to launch a python script, and this python script will perform data retrieval via the ssh connection, form an informational string, and send it to the server administrator's telegram channel.

 

Let's get started.

 

1. If you still do not have your own telegram bot, create one, as well as a channel where messages will be sent. To do this, use items 1-2 from the Instructions. As the administrator of the telegram channel, you can also add other participants for joint monitoring of SSH connections to the servers.

 

2. In the folder /usr/bin/, create a file for the python script. To do this, execute the command

 

vim /usr/bin/ssh_notification.py

 

and place the script code

 

# ---------- settings ---------
# dont send message to telegram if IP includes in  whitelist IP, for example, admin IP.
# send notification for all IPs: wlip = []
wlip = ['123.123.45.67','98.76.54.32']
# users to track. For all users to track: userstrack = []
userstrack = ['root','admin']
#-----------------------------
import os
import datetime
import requests
import socket
def SendMsgToTelegramChanel_z(msg):
    token="TOKEN"
    chat_id = 'CHAT_ID'
    params = {'chat_id': chat_id,'text': msg}
    response = requests.get('https://api.telegram.org/bot'+token+'/sendMessage', params=params)

localip = socket.gethostbyname(socket.gethostname())
ip = os.popen("echo $SSH_CLIENT | awk -F' ' '{print $1}'").read().strip()
login = os.popen("whoami").read().strip()
dtime =  datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")

if (ip not in wlip or not wlip) and (login in userstrack or not userstrack):
    SendMsgToTelegramChanel_z('SSH connect to ' + localip + '\nUser: ' + login + '\nFrom: ' + ip + '\n' + dtime)
 

 

At the top of the script, there are 2 optional settings:

 

 -  The variable wlip contains a whitelist of IPs, from which no notification will be sent when connecting to the server. This can be one or  several IPs of the server administrator. If you want to send a message about logging into the server regardless of the IP, set the variable value to [] (just clear everything inside the square brackets)

 

wlip = []

 

 -  In the variable userstrack, you can specify one or more logins that need to be tracked. To send notifications regardless of the username, clear everything inside the brackets:

 

userstrack = []

 

-  Also replace TOKEN and CHAT_ID with the corresponding values obtained when creating the telegram bot and channel.

 

3. In the folder /etc/profile.d/, create a simple bash script that will run the previously created python script. To do this, execute the command

 

vim /etc/profile.d/ssh_notification.sh 

 

and place the script code:

 

#!/bin/bash
python3 /usr/bin/ssh_notification.py

 

Monitoring SSH connections to the server with notifications sent to telegram is set up. 

 

As a result, you will be able to receive notifications like this: