Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to run some process that requires an opened ssh tunnel.

How do you run some command AFTER the ssh tunnel is successfully opened? Timers are not good enough as network speed and remote machine load might heavily affect the time needed to open up the connection...

--UPDATE-- I want to open the tunnel and run the command on the local machine

share|improve this question
Does using ssh itself not work? ssh root@host 'ls -a /' Would run ls -a / after connecting. – jscott Oct 4 '11 at 14:55
I want to run the command on the local machine, not the remote – xvga Oct 5 '11 at 10:42
up vote 0 down vote accepted

You can use LocalCommand ssh option, but there are some limitations. From man ssh_config:


Specifies a command to execute on the local machine after successfully connecting
to the server.  The command string extends to the end of the line, and is
executed with the user's shell.  The following escape character substitutions
will be performed:
  ‘%d’ (local user's home directory),
  ‘%h’ (remote host name), ‘%l’ (local host name),
  ‘%n’ (host name as provided on the command line),
  ‘%p’ (remote port),
  ‘%r’ (remote user name) or ‘%u’ (local user name).

The command is run synchronously and does not have access to the session of
the ssh(1) that spawned it. It should not be used for interactive commands.

This directive is ignored unless PermitLocalCommand has been enabled.

Here is quick example:

ssh -v -o PermitLocalCommand=yes -o 'LocalCommand=/bin/date >/tmp/test' localhost

Later, you probably need to put those options into proper Host section in $HOME/.ssh/config file.

share|improve this answer

Have you considered modifying you .bashrc file? That will run every time you log on. If this is something which needs to happen every time anyone logs in, you can modify the global /etc/bashrc too.

share|improve this answer

ssh -fN will cause the SSH client to background itself once the connection is established, so you should be able to just wait for that and then execute the command.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.