sshd

how to add commands in .ssh/authorized_keys


I read on man sshd one can add post-login processing when a user logs in using a particular key:

environment="FOO=BAR" ssh-rsa AAA... keytag

But when I try to ssh into the system, the target host does not register the line and instead asks for a password. What is the right way of adding this? I would like to do something like

command="echo|mail -s ${USER},${HOSTNAME} a.monitored.email@example.com" ssh-rsa AAA... keytag

I am using Suse SLE 11 SP2.

Thanks Dinesh


Solution

  • First, according to the documentation command = "command":

    Specifies that the command is executed whenever this key is used for authentication. The command supplied by the user (if any) is ignored. The command is run on a pty if the client requests a pty; otherwise it is run without a tty. If an 8-bit clean channel is required, one must not request a pty or should specify no-pty. A quote may be included in the command by quoting it with a backslash. This option might be useful to restrict certain public keys to perform just a specific operation. An example might be a key that permits remote backups but nothing else. Note that the client may specify TCP and/or X11 forwarding unless they are explicitly prohibited. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Note that this option applies to shell, command or subsystem execution. Also note that this command may be superseded by either a sshd_config(5) ForceCommand directive or a command embedded in a certificate.

    Using this option, it is possible to enforce execution of a given command when this key is used for authentication and no other. This is not what you're looking for.

    To run a command after login, you can add in the file ~/bashrc something like this:

    if [[ -n $SSH_CONNECTION ]] ; then
        echo|mail -s ${USER},${HOSTNAME} a.monitored.email@example.com"
    fi
    

    Second, you need to verify the permissions of the authorized_keys file and the folder / parent folders in which it is located.

    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
    

    For more information see: https://www.complang.tuwien.ac.at/doc/openssh-server/faq.html#3.14