Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I listen for and report server (SSH) connections via a Python script?

I am a bit new to Python, but an experienced programmer. I am writing a Python 2.7 script which should be started by a Linux server at boot. The purpose is to send, via various mediums, notification(s) when a user connects to the server.

My problem has to do with the actual listening. How can I make the module see when a user connects (via SSH, or whatever) to the server? Some quick pseudocode:

# When a connection is made
    # Send an email
    # Send a text message
    # Send notification to server output
    # Etc...

I'd like to include some details in the notification, like username, IP, connection time, last connection, a cute custom connection message, whatever. Any protips on how to do those things best is appreciated as well, but I'm sure I can figure this out elsewhere.

Thanks in advance for any guidance!

like image 381
David Gay Avatar asked Mar 30 '12 01:03

David Gay


1 Answers

If your sshd is using syslog, you could configure syslog to send the auth facility to a named pipe, then write a Python script to read the FIFO. Here's an example that uses bash.

Or, like sblom said, you could tail /var/log/auth.log in a Python script. Either way, you should get lines like this:

Mar 29 19:58:13 mybox sshd[13914]: Accepted password for jtg from 192.168.0.20 port 51538 ssh2
like image 56
jtg Avatar answered Oct 22 '22 16:10

jtg