SSH Startup Commands
This is about running SSH with a specific set of commands before turning the interactive session over to you.
Why would you want to do this? Because that way you can automatically open up one or more sessions on a remote computer for a specific purpose. It can be a huge time-saver if this is something you have to do frequently. It can be an even bigger time-saver if you don’t have to do it frequently and can’t remember what to do on the remote computer (though see also profile-menu for another solution to this).
See also:
Running specific commands in an SSH session
You can tell SSH to run a command on a remote host like so:
$ ssh example.com 'run this command'
But that just runs the command and closes the session. So how do we run a command and keep a living shell session open to work in?
Export an environment variable before running the login shell
Check this out:
ssh -t deimos 'export DEV=foo ; ksh -l'
Note that my remote server in this case is running OpenBSD and ksh
is
OpenBSD’s default korn shell and -l
makes it work as a login shell.
The principle holds for Bash and presumably just about any shell. Check the manual for the precise details.
And on the remote server side, I’ve got the following in my .profile
(Bash’s equivalent is .bash_profile
, but it also reads a .profile
if there is one.)
function do_foo { cd /tmp/foo echo "Foo!" } function do_thing1 { ... } function do_thing2 { ... } function do_thing3 { ... } if [[ -n $DEV ]] then echo "Doing $DEV things..." # Run associated function do_$DEV else echo "Just a normal day." fi
If I simply connect with a normal session, I see this:
$ ssh deimos Just a normal day. deimos$
But if I run the one that sets the DEV
variable:
ssh -t deimos 'export DEV=foo ; ksh -l' Doing foo things... Foo! deimos/tmp/foo$
Nice!
Why this method?
Why am I setting DEV
and checking that? Isn’t there some better way to
run a command via SSH?
So, if you dig far enough, you find that both SSH and the popular shells expect to either run interactively OR run a command and exit. They really don’t have a concept of running a command and then turning the session over to you for interactive use.
In fact, a common use of the Tcl-derived control and test application expect
is to run some commands in an interactive shell and then turn control over to
you. Expect is a wonderful tool, but it’s arcane enough to be a real pain to
learn just for one automation every couple years!
After many false avenues, I’ve found that the most dependable way to get some per-session logic into a shell or SSH session is to set a value in an environment variable and export it so the shell can read it.
People have come up with a billion work-arounds, but I’ve found them all to be incredibly fragile or simply not work for me. (Quite frankly, I think some of the "solutions" were based on misunderstandings of the desired outcome.)
Back to unix.