Mihir
Mihir

Reputation: 660

Python Paramiko "exec_command" does not execute - Django

I am facing an issue with the Python Paramiko library in my Django Application

This is a function I have written to create an SFTP connection:

def createSFTPConnection(request,temp_pwd):
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    user = User.objects.get(username=request.user)
    ssh.connect(hostname=temp_host,username=user.username,password=temp_pwd,port=22)
    sftp_client=ssh.open_sftp()

    return ssh,user,sftp_client

This just returns me the variable for ssh, the username, and sftp_client

Then I execute a command on the remote server using this code -

ssh,user,sftp_client=createSFTPConnection(request,temp_pwd)  # passes the password on that server for the user for creating the connection

cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" # executing a shell script by passing it 2 variables

stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call
print("stderr: ", stderr.readlines())
print("pwd: ", stdout.readlines())

Now, this code works fine and executes the script "temp.sh" on the remote server, but it takes a lot of time as I am returning stdin, stdout and stderr and printing them on the console

But, since I don't want that I removed the readlines() calls from there making my code look like this -

cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" 
stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call

But for some reason, this code just doesn't execute on the remote server after removing the readlines() calls

Thus, making me think that exec_command does not work without a readlines() call ahead of it

And I don't know why this is happening..

Any help would be highly appreciable!! Thanks!!

For your info - This is the Django code after the readlines() calls -

usr_msg="Your file has been uploaded successfully!! This is your variable: "+var1
messages.success(request, usr_msg)
ssh.close()
sftp_client.close()
return redirect("/execute/all")

Upvotes: 0

Views: 2247

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202534

The SSHClient.exec_command only starts an execution of the command. If you do not wait for it to complete and immediately kill the session, the command is killed along with it.

If you want to keep the command running even after you disconnect, you need to detach it from the session.

See Running process of remote SSH server in the background using Python Paramiko.

It's basically not a Python/Paramiko question, see also Getting ssh to execute a command in the background on target machine.

First, make it working in ssh/plink/whatever-client before trying to implement it in Python. Something like:

ssh [email protected] "cd path; nohup sh script.sh /dev/null 2>&1 &"

Upvotes: 1

Related Questions