plink ssh 命令作为来自 txt 文件的变量使用 python

plink ssh command as a variable from txt file using python

我有一个关于使用 plink 并将命令作为来自外部文件的变量发送的问题。

test.txt里面有:

id -a user.name1\n; id -a user.name2\n; id -a user.name3\n;exit\n

此代码无效:

import subprocess
sshoutput = open("c:/sshoutput.txt", "w")
sshoutputerror = open("c:/sshoutputerror.txt", "w")
sshinput = open("C:/test.txt", "r").read()
ssh = subprocess.Popen("plink user.name@server -pw password",shell=True, stdin=subprocess.PIPE, stdout=sshoutput, stderr=sshoutputerror)
ssh.communicate(sshinput)

但是如果我将最后一行 sshinput 更改为 "id -a user.name1\n; id -a user.name2\n; id -a user.name3\n;exit\n"

ssh.communicate("id -a user.name1\n; id -a user.name2\n; id -a user.name3\n;exit\n")

这确实有效,但我想使用来自外部文件的命令。

感谢您的帮助。

尝试在 test.txt 文件中包含引号内的行。

像这样:

 "id -a user.name1\n; id -a user.name2\n; id -a user.name3\n;exit\n"

并使用 readline() 代替 read() :

import subprocess
sshoutput = open("c:/sshoutput.txt", "w")
sshoutputerror = open("c:/sshoutputerror.txt", "w")
sshinput = open("C:/test.txt", "r").readline()
ssh = subprocess.Popen("plink user.name@server -pw password",shell=True, stdin=subprocess.PIPE, stdout=sshoutput, stderr=sshoutputerror)
ssh.communicate(sshinput)