【发布时间】: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”,但由于我返回stdin、stdout 和@,这需要很长时间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