1

I need to run an infinite bash loop for background monitoring task on a remote server. I am using python Paramiko for this work and run the following command:

 s = paramiko.SSHClient()
 s.load_system_host_keys()
 s.connect(hostname, port, username, password)
 cmd = 'bash -c "while :; do cat /some/file >>/tmp/sca.mon; sleep 1 ; done" &'
 (stdin, stdout, stderr) = s.exec_command(cmd)

However, this does not work for what ever reason. It just stuck at exec_command line. How can I force the paramiko to leave the remote server when it submit the background bash command and start execute next like ? Note: I have tried nohup bash -c as well but it does not work as long as I use & to push the command running in the background on the remote server.

ARH
  • 1,355
  • 3
  • 18
  • 32
  • Seems to me that all information you need is here: http://unix.stackexchange.com/questions/30400/execute-remote-commands-completely-detaching-from-the-ssh-connection – KostasT Feb 14 '15 at 22:21
  • @KostasT I am having hard time to find my missing part of the puzzle in that page. Would you please elaborate more ? – ARH Feb 14 '15 at 22:54

2 Answers2

1

Seems to be working. I only don't specify shell. Also I am using while true because I am not familiar with "while :" in bash.

s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, username, password)
cmd = 'while true; do date >> ~/file.txt; sleep 1; done &'
(stdin, stdout, stderr) = s.exec_command(cmd)
s.close()
KostasT
  • 217
  • 1
  • 3
  • I have to use `bash` so It would let me kill the background job in the future with `killall bash` command. Otherwise, I need to some how get PID of this `while` loop and use `kill PID` in the future. I don't know how to get the PID at this point. any idea ? – ARH Feb 14 '15 at 23:47
  • So you should try to construct command by info from previous comment. About PID - http://stackoverflow.com/questions/7858191/difference-between-bash-pid-and – KostasT Feb 14 '15 at 23:52
  • 1
    That sounds reasonable. I can run `echo $!` to get the PID of last background job. More details: http://unix.stackexchange.com/questions/30370/how-to-get-the-pid-of-the-last-executed-command-in-shell-script – ARH Feb 14 '15 at 23:54
  • Are you sure this solution works ? I have tried it multiple times and it does not worked for me ! It just stuck at `exec_command` – ARH Feb 15 '15 at 05:26
0

Here is how I solved this problem (finally):

s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, username, password)
cmd = "echo 'while true; do date >> ~/file.txt; sleep 1; done &' >run.sh"
(stdin, stdout, stderr) = s.exec_command(cmd)
cmd = "bash run.sh </dev/null >>/dev/null 2>&1"
(stdin, stdout, stderr) = s.exec_command(cmd)
s.close()
ARH
  • 1,355
  • 3
  • 18
  • 32