ssh config auto execute remote command

I connect to server through ssh under vpn. To make project changes I always do the same procedure after accessing server – log as project_user, because with my identity I get sh shell and I don’t have write access to project files.

In my ~/.ssh/config file I tried to use LocalCommand parameter to automate the procedure:

LocalCommand sudo -iu project_user bash

and then

LocalCommand /bin/sh -c sudo -iu project_user bash

But none of this makes any change – after connecting I’m still in sh shell and I need to run above commands again and again.

Any ideas?

Update: sorry, but this LocalCommand parameter is meant for local and not remote command. Is there any ssh_config parameter that would let me execute remote command after connecting to server?
Or at least change the shell to bash so that I can execute my command through bash initialization scripts?

Asked By: vlad


If you can log in to the remote system you can change your default shell there:

chsh -s /bin/bash
Answered By: roaima

As the name indicates, LocalCommand runs a command on the local (client) machine, not on the remote (server) machine. The command that runs on the server is the argument(s) that you pass to ssh after the options and the host name.

By default, a terminal is not created when you pass a command, so pass the -t option to create one. Instead of ssh yourserver, run

ssh -t yourserver exec sudo -iu project_user

The OpenSSH server permits you to associate a command with an ssh key. When a particular ssh key is used to connect to a server, the server will ignore the command requested by the client and run the command associated with the key instead. If you are using ssh keys for these sessions, you could use this feature to launch your sudo command.

You set this up through your account’s “authorized_keys” file on the server. The sshd(8) man page describes the authorized_keys file format. Briefly, authorized_keys is a series of lines that each start with something like this:

ssh-rsa AAAAB3NzaC1yc2...

You can add a command directive to the front of a line:

command="sudo -iu project_user bash" ssh-rsa AAAAB3NzaC1yc2...

When the corresponding key is used to authenticate, the SSH server will ignore the command requested by the SSH client, and run the specified command instead. The ssh session will close when the sudo process (and the shell running within it) exits.

I recommend that you set up two keys for ssh’ing into this server: one key that performs this sudo operation, and one that doesn’t. You will probably need to be able to get into the server without performing the sudo operation from time to time. The key that runs sudo also won’t work for running scp or sftp, at least not without setting up something more sophisticated on the server.

Answered By: Kenster
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.