简体   繁体   中英

Executing remote python script in background over SSH

I have a python file "run.py" like below on my remote server.

import subprocess
subprocess.Popen(["nohup", "python", "/home/admin/Packet/application.py", "&"])

I want to run that file from my local computer using SSH. I'm trying like the below. However, my local terminal got stuck there. It seems it isn't being run in the background.

ssh -n -f -i /Users/aws/aws.pem admin@hello_world.com 'python /home/admin/run.py'

After running that command, my terminal got stuck.

The following is an example I'm using, you can try something like this, customizing the ssh_options.

import subprocess
ssh_options = '-o ConnectTimeout=10 -o PasswordAuthentication=no -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no'
server_name = 'remote_server.domain'
cmd = 'ssh ' + ssh_options + ' ' + server_name + ' "/usr/bin/nohup /usr/bin/python /home/admin/run.py 2>&1 &"'  
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Later you can redirect the output to a flat file, changing :

2>&1 &

for:

>> /path/lo/log_file.txt 2>&1 &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM