I see two ways to interpret your question.
Log monitoring
Perhaps you're really looking for a log monitoring script like Fail2ban (which is a free software python project, so you can see how their code works).
SSH server logs vary in their location based on how they are installed. They most commonly live in /var/log/auth.log
, /var/log/secure
, /var/log/sshd.log
, or a similar name in an alternate log area like /usr/local/var/log/
(see also How to check sshd log?). Here's a sample log:
Aug 14 12:34:56 jodari-desktop sshd[12345]: Accepted pubkey for jodari from 127.0.0.1 port 54321 ssh2: RSA SHA256:3xyQ+PG0Z3CIiShclJ2iNya5TOdKDgE/HrOXr11IdOo
If you "want to get notified about that and retrieve their public keys, IP address, etc." then you need only monitor that line. (It is possible you need to increase the LogLevel in /etc/ssh/sshd_config
or wherever that file lives.)
If you're looking to retrieve the user's actual public keys (rather than just their fingerprints), your script would merely need to traverse their $HOME/.ssh/authorized_keys
file (that's the default location; it can be changed with the AuthorizedKeysFile
directive in your sshd_config
). You'll need to match the fingerprint to the public key. It's free if there's only one valid line in the file, but you'd otherwise need to generate each public key's fingerprint and match it to the fingerprint you extracted from the logs. Just search for the fingerprint in the output of the following command:
ssh-keygen -lf "$HOME/.ssh/authorized_keys"
Running commands via SSH
If you're actually looking to run things as they'd be experienced in an SSH session, you can use passwordless ssh keys to run commands.
Generate ssh keys for internal use only and you'll have automated passwordless access via ssh on localhost. This will keep everything controlled by OpenSSH, so to monitor connections, just look for localhost as authenticated by the dedicated internal keys in the standard SSH logs.
I can't speak to the python way of doing this, but you can do all of these in python as system calls.
To create the key:
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"
ssh keygen -t rsa -b 4096 -P "" -C "python script PASSWORDLESS access" \
-f "$HOME/.ssh/python-localhost.id_rsa"
To install it locally:
cat "$HOME/.ssh/python-localhost.id_rsa.pub" >> "$HOME/.ssh/authorized_keys"
To then use it:
ssh -i "$HOME/.ssh/python-localhost.id_rsa" localhost your_command_goes_here