Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

linux - Running process of remote SSH server in the background using Python Paramiko

I am finding hard to run a process on a remote SSH server at background using Paramiko. I used :

stdin, stdout, stderr = ssh.exec_command('executefile.py &') 

and found that no process of executefile.py was found running.

Then I tried using other way as including a backward slash:

stdin, stdout, stderr = ssh.exec_command('executefile.py &') 

This method worked. There was an instance running on machine but no surprise, it was not running at background. I could come to know as it is not running at background as when code stuck at second line after this code. It was

all_inf = stdout.readlines()

Now code was not going beyond above line unless the process of the script was killed.

I am learning Paramiko, any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've tried all the methods described here and here without success, and finally realized that you need to use channels instead of using the SSHClient directly for calling exec_command (this does not work in background):

client = paramiko.SSHClient()
client.connect(ip_address, username='root', pkey=paramiko_key, timeout=5)
client.exec_command('python script.py > /dev/null 2>&1 &')

You should create and use a channel, this works in background:

client = paramiko.SSHClient()
client.connect(ip_address, username='root', pkey=paramiko_key, timeout=5)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command('python script.py > /dev/null 2>&1 &')

So nohup, dtach, screen, etc, are actually not necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...