Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to ssh into a remote host and execute a command immediately

Tags:

linux

If i've already put public key to remote host. So there is no password input problem.

I want to login a remote machine and execute screen -r immediately. Is there a way to achieve this ?

For example:

ssh example.com ;  screen -r 

But this is wrong since screen -r won't send to remote host.

like image 319
hey mike Avatar asked Mar 22 '12 05:03

hey mike


2 Answers

When you run a command on a remote host, by default ssh will not allocate a pseudoterminal. If you run an interactive program like screen on a remote host, you must have a pseudoterminal. The -t option makes this happen. Try:

ssh -t example.com "screen -r"
like image 106
amcnabb Avatar answered Oct 25 '22 00:10

amcnabb


Remove the semicolon from your example:

ssh example.com "screen -r"

Your not going to get much bandwidth for that particular command though, as it needs an attached terminal in order to execute successfully.


* EDIT 1 *

To run multiple commands, just string them together separated by semi-colon:

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

* EDIT 2 *

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

To chain random commands together:

ssh example.com "ps -elfc; ls"

To run some random commands after running screen:

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

To specifically run screen and send commands to it:

ssh -t example.com "screen -r -X ls"
like image 33
Perception Avatar answered Oct 25 '22 00:10

Perception