Paramiko SSH第一次工作,但第二次不工作,除非等待

时间:2018-10-30 18:43:48

标签: python unix ssh expect paramiko

我在python上使用paramiko ssh。第一次运行正常,如以下日志所示:

.... more logs above...    
Authentication (password) successful!
[chan 0] Max packet in: 32768 bytes
[chan 0] Max packet out: 32768 bytes
Secsh channel 0 opened.
[chan 0] Sesch channel 0 request ok
[chan 1] Max packet in: 32768 bytes
[chan 1] Max packet out: 32768 bytes
Secsh channel 1 opened.
[chan 0] EOF sent (0)
[chan 1] Sesch channel 1 request ok
Ignoring message for dead channel 0
Ignoring message for dead channel 0
Ignoring message for dead channel 0
... starts running expect script and works fine...
[chan 1] EOF received (1)
[chan 1] EOF sent (1)
[chan 2] Max packet in: 32768 bytes
[chan 2] Max packet out: 32768 bytes
Secsh channel 2 opened.
[chan 2] Sesch channel 2 request ok
EOF in transport thread

我在完成此脚本后立即再次运行,它不适用于以下日志:

... more logs above...
Authentication (password) successful!
[chan 0] Max packet in: 32768 bytes
[chan 0] Max packet out: 32768 bytes
Secsh channel 0 opened.
[chan 0] Sesch channel 0 request ok
[chan 1] Max packet in: 32768 bytes
[chan 1] Max packet out: 32768 bytes
Secsh channel 1 opened.
[chan 0] EOF sent (0)
[chan 1] Sesch channel 1 request ok
[chan 1] EOF received (1)
[chan 2] Max packet in: 32768 bytes
[chan 1] EOF sent (1)
[chan 2] Max packet out: 32768 bytes
Secsh channel 2 opened.
Ignoring message for dead channel 0
Ignoring message for dead channel 0
[chan 2] Sesch channel 2 request ok
EOF in transport thread
... does not run rest and ends here...

这是我的代码示例(不完全是):

import paramiko
import logging

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
ssh.connect(host, username=usr, password=pwd)

prompt="{\\\\$ $}"
expect_script='set timeout -1\n' \
              'spawn sudo -i -u {0}\n' \
              'expect -exact \\"\\\\[sudo\\\\] password for {1}: \\"\n' \
              'send -- \\"{2}\\\\r\\"\n' \
              'set prompt_re {3}\n' \
              'expect -re \\$prompt_re\n' \
              'send \\"shell_script.sh\\\\r\\"\n' \
              'expect -re \\$prompt_re\n' \
              '\n' \
              .format(another_user,usr,pwd,prompt)
ssh.exec_command('echo "{}" > test.exp'.format(expect_script))
stdin, stdout, stderr = ssh.exec_command('expect test.exp')
for line in stdout:
    logging.debug(line.strip('\n'))
ssh.close()

我认为这与会话最后未正确关闭有关。我需要多次运行此python脚本,并且似乎只有在每次运行此命令之间等待约5分钟时,它才起作用。我在代码中添加了期望脚本,以防它可能是导致问题的原因。可能是因为期望脚本仍在运行,并且我尝试启动另一个会话?每次运行此命令时,主机和用户都是相同的。

0 个答案:

没有答案