Mundisoft Mundisoft - 1 year ago 85
Linux Question

Attach to a GNU screen and then execute commands

I have seen some similar questions asked but the solutions don't seem to work in my case.

I am trying to SSH into a specific screen instance on a Node machine and then execute some commands

My current process is this:

On the remote machine I create a screen instance:

screen -dmS "my_screen"

From my local machine I do something like:

ssh <user>@<remote> -a -x -t screen -x -r my_screen -X stuff 'ruby my_script.rb'

but the output is just:

Connection at (ip) closed.

and the ruby script is not run.

If I separate the commands then the script runs correctly eg:

ssh <user>@<remote> -a -x -t screen -x -r my_screen

it connects to the screen, and then I manually enter:

ruby my_script.rb

Then the script executes in the screen as intended.

What is the correct way to send commands to a screen?

Answer Source

In your second example, you are executing the command by typing it into the console. If that is the behavior you want to emulate, you can use the stuff command to have screen paste your text into the console to execute it.

ssh <user>@<remote> -a -x -t screen -x -r my_screen -X stuff \"ruby my_script.rb^M\"

(Note the ^M was generated using CTRL-V, CTRL-M).

This won't display anything to your open terminal, but when you reconnect to the screen, you should see the output of your command (assuming the screen was at a console window at the time you sent the command, which is the risk with this approach).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download