Martinos
Martinos

Reputation: 2236

Running ssh command and keeping connection

Is there a way to execute a command before accessing a remote terminal

When I enter this command:

bash $> ssh [email protected] 'ls'

The ls command is executed on the remote computer but ssh quits and I cannot continue in my remote session.

Is there a way of keeping the connection? The reason that I am asking this is that I want to create a setup for ssh session without having to modify the remote .bashrc file.

Upvotes: 1

Views: 303

Answers (2)

damienfrancois
damienfrancois

Reputation: 59300

You can try using process subsitution on the init file of bash. In the example below, I define a function myfunc:

myfunc () {
   echo "Running myfunc"
}

which I transform to a properly-escaped one-liner echoed in the <(...) construct for process subsitution for the --init-file argument of bash:

$ ssh -t localhost 'bash --init-file <( echo "myfunc() { echo \"Running myfunc\" ; }" )  '
Password:
bash-3.2$ myfunc
Running myfunc
bash-3.2$ exit

Note that once connected, my .bashrc is not sourced but myfunc is defined and properly usable in an interactive session.

It might prove a little difficult for more complex bash functions, but it works.

Upvotes: 1

David M. Syzdek
David M. Syzdek

Reputation: 15788

I would force the allocation of a pseudo tty and then run bash after the ls command:

syzdek@host1$ ssh -t host2.example.com 'ls -l /dev/null;   bash'
-rwxrwxrwx    1 root     other          27 Apr  1  2005 /dev/null
bash-4.1$ 

Upvotes: 2

Related Questions