【问题标题】:Python Paramiko "exec_command" does not execute - DjangoPython Paramiko“exec_command”不执行 - Django
【发布时间】:2022-01-25 14:48:32
【问题描述】:

我的 Django 应用程序中的 Python Paramiko 库遇到问题

这是我编写的用于创建 SFTP 连接的函数:

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

这只是返回给我 ssh、用户名和 sftp_client 的变量

然后我使用此代码在远程服务器上执行命令 -

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())

现在,这段代码可以正常工作,并在远程服务器上执行脚本“temp.sh”,但由于我返回stdinstdout 和@,这需要很长时间987654325@ 并在控制台上打印出来

但是,由于我不希望从那里删除 readlines() 调用,使我的代码看起来像这样 -

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

但由于某种原因,删除 readlines() 调用后,此代码在远程服务器上只是不执行

因此,让我觉得如果没有 readlines() 提前调用 exec_command 就无法工作

我不知道为什么会这样..

任何帮助都将不胜感激!! 谢谢!!

供您参考 - 这是readlines() 调用后的 Django 代码 -

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")

【问题讨论】:

    标签: python django ssh paramiko


    【解决方案1】:

    SSHClient.exec_command 仅开始执行命令。如果您不等待它完成并立即终止会话,它会与它一起终止的命令。

    如果您想在断开连接后仍保持命令运行,则需要将其从会话中分离。

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

    这基本上不是 Python/Paramiko 问题,另见 Getting ssh to execute a command in the background on target machine

    首先,在尝试在 Python 中实现它之前,让它在 ssh/plink/whatever-client 中工作。比如:

    ssh user@example.com "cd path; nohup sh script.sh /dev/null 2>&1 &"
    

    【讨论】: