3

I want to run a command automatically after I connect to another machine via ssh, without the ssh session being closed automatically.

After searching the internet I found some solutions but none of them work the way I need.

ssh bla@bla "ls"

This runs the ls command on the remote machine, shows me the output and closes the connection.

I also tried editing the ssh config file with

Host bla
        HostName bla
        User bla
        IdentityFile ~/.ssh/key
        RemoteCommand ls
        RequestTTY force 

Same issue, this connects via ssh, runs the ls command, shows me the output and then exits. Not even the RequestTTY option helped.

ssh bla@bla "ls ; bash"

This doesn't disconnect after running ls, but I don't get a full terminal interface, just some bare bones command line that doesn't show the me@machine:~$ thing.

What I actually want:

Either some bash alias, or .ssh/config entry that will allow me to type in a simple command which will connect to the remote machine and then run a command there and leave the terminal open. Basically as if I did this by hand:

type

ssh blah@blah

and then after it connects I would type

ls

2 Answers 2

4
ssh bla@bla "ls ; bash"

This doesn't disconnect after running ls, but I don't get a full terminal interface, just some bare bones command line that doesn't show the me@machine:~$ thing.

If you specify a command (e.g. ls ; bash above) the SSH server will not provide a pseudo-terminal. You have observed exactly this.

On the other hand sole ssh bla@bla allocates a pseudo-terminal by default. So this is what you want. Force pseudo-terminal allocation, use -t or RequestTTY.

Not even the RequestTTY option helped.

It won't help you if the remote command is ls only. You need ls; bash or similar.

It seems when you requested a tty, you did not request bash. And when you requested bash after ls, you did not request a tty. You need both:

ssh -t bla@bla "ls; bash"

Note ls will also use the pseudo-terminal. Please read the "broader picture" section of this answer of mine to learn the difference (especially where it reads "there's a quirk").

-1

To get rid of me@machine you need to set the PS1 environment variable. Try:

ssh bla@bla "PS1=\"\"; ls; bash"
1
  • I was docked on this. But it does meet the requirements of the question. It allows the user to type in a simple command (ssh bla@bla "PS1=\"\"; ls; bash" ) which connects to the remote machine and then runs a command there (ls) and leaves the terminal open (bash). It is a bare bones command that doesn't show the me@machine:~$ thing.
    – Emmett
    May 23, 2021 at 20:55

You must log in to answer this question.

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