Run a remote command using ssh config file

33

10

I'd like to be able to setup a command to run on ssh login to a server, without needing to type it. Basically I'm looking for the ssh config file equivalent of:

ssh host command

so that all I need to type is:

ssh host

and the command gets run.

PeterJCLaw

Posted 2010-03-25T18:11:45.813

Reputation: 1 882

Answers

16

It is also possible to insert a command in your authorized keys file. (~/.ssh/authorized_keys). This allows you to execute a custom command for each key in the file. I use this to forward shell connections through my firewall. The result is that I can ssh to one host and it automatically connects the session to a host inside the network. The authorized_keys entry looks like this:

command="ssh -Tq <hostname> \"$SSH_ORIGINAL_COMMAND\"",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty ssh-rsa AAAA... the rest of the key ...

More specifically the redirect is for my gitolite instance. This allows simple outside access without directly exposing the gitolite host to any external access. Check the man page for more info. ( http://linux.die.net/man/8/sshd )

dav

Posted 2010-03-25T18:11:45.813

Reputation: 161

3If you put the command in your authorized_keys file it'll break things such as rsync and scp - you'll get something like this: open terminal failed: not a terminal. Also, be aware that if the command fails you'll not be able to login. I've discovered this the hard way. – John Hunt – 2015-09-18T11:32:34.237

1This is awesome, didn't know you could do this. +1 – Brian Wigginton – 2013-09-24T19:48:56.593

11

If you are running OpenSSH, it looks like ~/.ssh/rc is executed upon login.

coneslayer

Posted 2010-03-25T18:11:45.813

Reputation: 7 494

3Is /.ssh/rc located on the client or server machine? Looks like from the docs the server, right? – heavyd – 2010-03-25T18:45:37.090

1Yes, that would be on the server machine. – coneslayer – 2010-03-25T18:52:38.837

1Unfortunately the rc file appears to fail to run things like screen, getting an error "Must be connected to a terminal" – davidparks21 – 2017-05-01T22:26:56.447

10

You could set up a bash alias.

In your .bashrc file, put:

alias ssl='ssh some_host run_command'

Then you wouldn't even have to type the hostname.

Or, if you wanted to do this with multiple hosts(and multiple aliases wouldn't work), then use a small script:

kevin@box:~$ cat ssl.sh
#!/bin/sh
ssh $1 some_command
kevin@box:~$

Kevin M

Posted 2010-03-25T18:11:45.813

Reputation: 2 396

5

You cold solve this in your .ssh/config file, for the host where you want to execute a command, add

  RequestTTY yes
  RemoteCommand <some command>

where <some command> is your command. This also works with screen or tmux.

Florian Lautenschlager

Posted 2010-03-25T18:11:45.813

Reputation: 51

IMHO this is the expected answer. – David Ammouial – 2020-01-24T16:49:04.927