Ssh – Run Python program when user logs in using SSH

pythonshellssh

I want to have a command line program that I made in Python automatically run when a certain user logs in on my server using SSH. But the user must not be able to escape the program or run any other commands.

The program allows the user to view certain server information and send messages to the admin. Can you think of anyway I can do this with the OpenSSH server in Ubuntu?

Thanks, Dave.

Best Answer

The safest approach is to define your command as the user's shell (instead of /bin/bash or similar). It will be difficult to circumvent unless there is a bug in your code.

The second safest approach is to use ForceCommand in your sshd configuration or command= in your authorized_keys.

Do not just put the command in .bash_profile or similar, it is a common mistake and very easy to circumvent.

Note that even when you restrict the user to this single command, they will still be able to open tunnels through the SSH session. You might want to prevent also that for untrusted users.