24

I want to execute a Python script on several (15+) remote machine using SSH. After invoking the script/command I need to disconnect ssh session and keep the processes running in background for as long as they are required to.

I have used Paramiko and PySSH in past so have no problems using them again. Only thing I need to know is how to disconnect a ssh session in python (since normally local script would wait for each remote machine to complete processing before moving on).

4 Answers 4

35

This might work, or something similar:

ssh [email protected] nohup python scriptname.py &

Basically, have a look at the nohup command.

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

1 Comment

Hi! I am trying this solution but my python is not executed... How can I debug what is wrong? Thanks :)
4

On Linux machines, you can run the script with 'at'.

echo "python scriptname.py" ¦ at now

2 Comments

:). I personally found 'at' to be more versatile for me, but 'nohup' is good enough in many situations.
I've also tried this solution but my python is not executed... How can I debug what is wrong? Thanks :)
1

If you are going to perform repetitive tasks on many hosts, like for example deploying software and running setup scripts, you should consider using something like Fabric

Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

It provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution.

Typical use involves creating a Python module containing one or more functions, then executing them via the fab command-line tool.

Comments

1

You can even use tmux in this scenario.

As per the tmux documentation:

tmux is a terminal multiplexer. It lets you switch easily between several programs in one terminal, detach them (they keep running in the background) and reattach them to a different terminal. And do a lot more

From a tmux session, you can run a script, quit the terminal, log in again and check back as it keeps the session until the server restart.

How to configure tmux on a cloud server

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.