I am looking for a way to execute a local command when logging into a remote machine via SSH. (I want to stay logged in after the command has finished.) In other words, I want to specify the command on my command line. It should be executed on the remote machine and then I should get the shell, as if I had logged in normally.
For instance, let’s say, I want to mount /home on the remote machine before I get the shell. I would do something like this (which does not work well)
ssh mymachine.example.com 'mount /home ; /bin/bash'
In effect, I am looking for a way how to condense the following two commands into one:
ssh mymachine.example.com 'mount /home' ssh mymachine.example.com
Does anybody have any idea how to do it?
IMPORTANT: I don’t want to store the command-to-be-executed on the remote machine. It must be stored locally (perhaps it contains my password to de-crypt the encrypted home.)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You are likely looking for the -t option for ssh which forces pseudo-terminal allocation – without that you are just directly connecting your terminal to standard input/output/error of the remotely running programs. Hence your command should look like this:
ssh -t mymachine.example.com 'mount /home ; /bin/bash'
Method 2
I recommend an alternate approach: use a master connection. First start a master connection that performs the mounting and then sleeps forever, then use slave connections that require no authentication and so are very fast.
ssh -M mymachine.example.com 'mount -o password=swordfish …; exec sleep 999999999' ssh mymachine.example.com ls
Method 3
You could use the ssh’s rc files.
File ~/.ssh/rc is executed before de user’s home becomes avalaible, so you can put all your stuff there.
The caveat is that these files reside on the server.
man sshd could be of help.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0