Saturday, October 23, 2021

[SOLVED] Running a remote command through SSH but in the background

Issue

My use case is as follows. I have to list files on a remote machine and I am using SSH to accomplish this

The command looks like this

/usr/bin/ssh -2 remote_user@remote_host ls -l remote_dir

This works fine and I get the ls output

But it errors out when I run it with nohup or in the background. The process just quits. For instance the below command just fails to give any output

nohup /usr/bin/ssh -2 remote_user@remote_host ls -l remote_dir &

When run in the debug mode I see this error. It considers all the connections as closed

debug2: channel 0: read<=0 rfd 4 len -1^M
debug2: channel 0: read failed^M
debug2: channel 0: close_read^M
debug2: channel 0: input open -> drain^M
debug2: channel 0: ibuf empty^M
debug2: channel 0: send eof^M
debug2: channel 0: input drain -> closed^M
debug2: tcpwinsz: 87380 for connection: 3^M
debug2: tcpwinsz: 87380 for connection: 3^M
debug2: channel 0: rcvd eof^M
debug2: channel 0: output open -> drain^M
debug2: channel 0: obuf empty^M
debug2: channel 0: close_write^M
debug2: channel 0: output drain -> closed^M
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0^M
debug2: channel 0: rcvd close^M
debug3: channel 0: will not send data after close^M
debug2: tcpwinsz: 87380 for connection: 3^M
debug2: channel 0: almost dead^M
debug2: channel 0: gc: notify user^M
debug2: channel 0: gc: user detached^M
debug2: channel 0: send close^M

How can I run the remote file listing in the background and I don't want to redirect the standard out and standard error?

Can someone explain what is happening here?


Solution

Figured out that the SSH command has to be passed a -t argument.

The man page for SSH says this

     -t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine,
             which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even if
             ssh has no local tty.

On running SSH command with -t -t I was able to run it with nohup

nohup /usr/bin/ssh -2 -t -t remote_user@remote_host ls -l remote_dir &

You have to specify the -t twice to force the tty allocation



Answered By - rgk