Linux – Ssh, run a command on login, and then Stay Logged In

automationcommand-line-interfacelinuxssh

I tried this with expect, but it didn't work: it closed the connection at the end.

Can we run a script via ssh which will log into remote machines, run a command, and not disconnect?

So ssh in a machine, cd to such and such a directory, and then run a command, and stay logged in.

-Jonathan

(expect I used)

#!/usr/bin/expect -f
set password [lrange $argv 0 0]
spawn ssh root@marlboro "cd /tmp; ls -altr | tail"
expect "?assword:*"
send -- "$password\r"
send -- "\r"
interact

Best Answer

Add a ; /bin/bash to the end of your command line on the remote side? That is:

spawn ssh -t root@marlboro "cd /tmp; ls -altr | tail; /bin/bash -i"

Even better, change root's .bashrc to be something like this:

PROMPT_COMMAND="cd /tmp && ls -altr | tail ; unset PROMPT_COMMAND"

:)