我试图自动化一个系统,我们有一个 linux box 但定制.. 要转到 shell,我们必须传递一些输入。如下所示:
tanuj$ ssh admin@10.10.10.10
Used by Tanuj
Password:
command line interface
app > en
app # config t
app (config) #
我在 python 中使用 pexpect 编写了一个脚本。我能够登录并执行命令
pexpect.sendline("ls -lrt")
pexpect.expect("#")
但是当我使用 pexpect.before()
时..什么也没得到..当命令输出很长时我也可以看到 pexpect.before
有里面也有命令。
知道如何解决这个问题......或者是否有任何其他 python 模块可以用来自动化 ssh session ,就像我在这里一样。
我也尝试过使用 paramiko 但它没有用,因为我们必须先执行一些命令才能到达正常的 shell 提示符。
最佳答案
我也遇到了类似的问题。我正要问这个问题。您正在使用 # 登录您的
pexpect.expect('#')
这个 # 符号注释它后面的所有内容。此外,我猜你应该创建一个子进程来生成一个进程,比如(我不知道我是否适合你的情况):
child=pexpect.spawn('ssh admin@10.10.10.10')
child.expect('prompt_expected_by_you') # put in the prompt you expect after sending SSH
child.sendline('your_password')
child.expect('Prompt_expected_by_you')
child.sendline('ls -ltr')
child.expect('Prompt_expected_by_you')
print child.before, # , will keep continue your newline print
print child.after
child.sendline('exit')
child.expect('Prompt_expected_by_you')
child.sendline('exit')
child.expect('Prompt_expected_by_you') # may not be required
child.close # close the child session
我已在 FTP 中成功使用这些命令,但无法在 SSH 中打印“LS -LTR”的结果。我想我必须启动一个 shell,但不确定。你这边有什么进展吗?
有人可以帮忙吗???
关于python - python 中的 ssh 连接句柄 pexpect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21757386/