Who SSH to my server?

I manage quite a few number of servers, Most of them at Digital Ocean.
I needed a way to monitor the ssh logins to my servers.
even that port 22 is blocked by the firewall to specific IPs, and you need a private key to login, It’s good to have a notification when a user is logging into your server.

So I decided to write a small python script that will monitor every second the logged in users on the server.
The script send me notifications using slack, on every new connection or disconnection from the server.

To get the current logged users we need to use psutil package

import psutil

Next, we will need to get the users looged at the moment

users = psutil.users()

Next is to cycle through the users and send notification upon status change

        l_in = list(set(users) - set(logged_users))
        for user in l_in:
               print('''{} Logged in to {} from {} at {}'''.format(user.name,
                                                                                        datetime.utcfromtimestamp(int(user.started)).strftime('%Y-%m-%d %H:%M:%S')))
        l_out = list(set(logged_users) - set(users))
        for user in l_out:
            print('''{} Logged in to {} from {} at {}'''.format(user.name,
                                                                                        '%Y-%m-%d %H:%M:%S')))

After that, we need to updated the logged_users object with the current users and sleep for a second.

logged_users = users

Then only thing that is left is to change the print to a slack notification call, and you are good to go