Python 使用 Popen 难以通过管道传输 ssh

2024-06-13 15:43:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本,它使用plink将ssh连接到linux框中,执行一个命令,然后将该命令的输出写入一个字符串并返回到python脚本。你知道吗

我也不想打印命令,我正在运行的终端。你知道吗

我有下面的代码来执行命令并打印到终端,但它不会返回到python脚本,也不知道如何将命令的输出存储到字符串中。你知道吗

while(True):
network_name = raw_input('\nEnter test network: ')
network_name_check = raw_input('\nYou want to test on the %s network. Is this correct? (Y/N): ' %(network_name))
if inputYNChecker(network_name_check):
    print "\nVerifying Network exists as Group_Name on Control VM..."
    sshCommand = "plink root@Control -pw PASSWORD"
    lsCommand = "ls -1 --color=never -d */ | grep " + network_name +"\n"
    sshProcess = Popen(sshCommand,shell=False,stdin=PIPE)
    sshProcess.stdin.write("cd /mnt/PCAPS/GroupSetup\n")
    #sshProcess.communicate("cd /mnt/PCAPS/GroupSetup\n")
    sshProcess.stdin.write(lsCommand)
    sshProcess.stdin.write("exit\n")
    sshProcess.stdin.close()
    break
print "Back to python script"

我想我真的不明白管道是怎么工作的,因为当我有stdin=PIPEstdout=PIPE时,终端中除了“Using username“root”之外什么都不显示,然后它就挂断了。你知道吗

我怎样才能:

a)不显示我发送给ssh会话的命令

b)将命令的输出(即文件夹名)存储到字符串中

c)返回到我原来的python程序


Tags: 字符串nametest命令脚本终端inputraw