I would like to be able to automatically run a command on a remote host each time I log into that host, but within the current interactive SSH session.

Something like

ssh user@remotehost [run do.sh]

where do.sh does a couple of housekeeping tasks and then reattaches to a screen session (currently I run do.sh manually after logging into the host).

I don't want to add it to .bashrc because I login to this host from other machines and I don't want do.sh to run when I do login from there so I need it to be optional.

  • 1
    why you don't simply run ssh user@remotehost /path/to/do.sh ? If it works, you can even alias it in .ssh/config or your personnal .bashrc
    – Coren
    Feb 3 '12 at 9:50
  • So you want to run "do.sh" when you log in to remotehost from somewhere, but not when you log in to remotehost from somehwere else? Which hosts do you connect from should trigger "do.sh", and which others shouldn't?
    – Mat
    Feb 3 '12 at 10:09
  • Yes, I want to run it sometimes, but not all the time, the reason for this is that I have a keyboard shortcut from a launcher on my Mac that gives me what I want most of the time. I hit a shortcut and I want to ssh into the box and then reattach to a screen session, but I don't want to do that if I use a regular terminal like "ssh user@host". The solution mentioned below by Patkos does exactly what I need.
    – Jim Farkas
    Feb 3 '12 at 11:13

You could try something like this:

ssh server -t "do.sh; bash --login"

as suggested here: https://serverfault.com/questions/167416/change-directory-automatically-on-ssh-login

Or you could try using the 'LocalCommand' option in sshd_conf (or ~/.ssh/config) as described in the official man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1

  • 1
    Thanks so much!! ssh server -t "/home/user/do.sh; bash --login" worked for me. köszönöm szépen!
    – Jim Farkas
    Feb 3 '12 at 11:07
  • 1
    Szivesen (You are welcome) Feb 3 '12 at 11:57
  • @PatkosCsaba Please avoid other languages than English here. This applies also to comments. Nov 30 '16 at 8:29

One part of the puzzle: assuming OpenSSH, the ssh client will set the following environment variable:

SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number.

So you can use this information to find out where your connection comes from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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