3

I am reading some output of remote server using SSH bash(command). I need to do it constantly, so I spawn subprocess. It works fine, unless server server become unavailable for brief period. How do I restart SSH command (whole subprocess) if it fails?

I have following piece of code:

(...)

process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
while True:
    line = process.stdout.readline()
    if lines == "" and process.poll() is not None:
        break
(...)

I would think that process.poll() is not None should do the trick but it seems to hang on

1000     21431  0.0  0.0      0     0 pts/0    Z+   Oct22   0:00 [ssh] <defunct>

And does not break out of while True:

4
  • Just put the entire block into another while True as well? Commented Oct 26, 2020 at 9:05
  • the problem is that the ssh process inside goes to [ssh] <defunct> state and process.stdout.readline() waits forever. I would like to break out of readline() when ssh disconnects... Commented Oct 28, 2020 at 9:03
  • might be helpful: stackoverflow.com/questions/760978/… Commented Oct 28, 2020 at 9:43
  • I had bug in my code afterall... silly typo. Commented Oct 28, 2020 at 11:52

1 Answer 1

4

I had silly typo error in my code preventing if lines == "" and process.poll() is not None: from executing properly. Another thing to look at is ssh_config, It is wise to set values to disconnect @60 seconds/1 attempt. And avoid process.communicate() as it is blocking the whole thread.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.