How to ssh to a remote host and immediately execute the command

If I already installed the public key on the remote host. Thus, there is no problem with entering a password.

I want to log in to the remote computer and immediately execute screen -r . Is there any way to achieve this?

For instance:

 ssh example.com ; screen -r 

But this is not true, since screen -r will not be sent to the remote host.

+6
source share
8 answers

When you run a command on a remote host, by default ssh does not allocate a pseudo-terminal. If you are running an interactive program such as a screen on a remote host, you must have a pseudo-terminal. The -t option does this. Try:

 ssh -t example.com "screen -r" 
+8
source

Remove the semicolon from your example:

 ssh example.com "screen -r" 

However, you will not get a lot of bandwidth for this particular command, since a connected terminal is required to successfully complete this.


* EDIT 1 *

To run multiple commands, simply join them together, separating them with a comma:

 ssh example.com "screen -r; ls -al; ps -elfc" 

* EDIT 2 *

Still not quite sure what you are trying to accomplish (was screen -r just an example, or are you really trying to just combine a bunch of commands together?). In any case, I am correcting my answer to cover more possibilities:

To combine arbitrary commands together:

 ssh example.com "ps -elfc; ls" 

To run some random commands after starting the screen:

 ssh -t example.com "screen -r; ls" 

To specifically launch the screen and send commands to it:

 ssh -t example.com "screen -r -X ls" 
+6
source

You can also cancel the command on the remote host:

 echo "command" | ssh user@host 
+2
source

http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1

ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec] [-D [bind_address:] port] [-e escape_char] [-F configfile] [-i identity_file] [-L [bind_address:] port: host: hostport] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-R [bind_address:] port: host: hostport] [-S ctl_path] [-w tunnel: tunnel] [user @] hostname [command]

Command is the last parameter .; tells the local shell that ssh and screen are two different commands, not one command and the other is an argument.

Not sure if this will work or not, since the screen is an odd program to do this, but ssh blah.com 'screen -r' is the correct syntax.

+1
source

It will work

 ssh root@something 'ls -l' 
+1
source

Try using single quotes:

 ssh example.com 'screen -r' 
+1
source

Just enter the command you want to run after the host name:

 ssh example.com screen -r 
+1
source

try this one ...

 ssh -XY -t user@remote _IP 'ssh -XY -t user@remoteToRemote _IP' 

you can continue the screen -r command or any other command on the remoteToRemote_IP machine.

0
source

Source: https://habr.com/ru/post/911379/


All Articles