14

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.

3
  • 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
    Commented Feb 3, 2012 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
    Commented Feb 3, 2012 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
    Commented Feb 3, 2012 at 11:13

2 Answers 2

20

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

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

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .