python - python 中的 ssh 连接句柄 pexpect

标签 python linux ssh cisco pexpect

我试图自动化一个系统,我们有一个 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/

相关文章:

linux - 生成一个值来反射(reflect)图像的平均亮度

c++ - ./配置错误: The test for linking against libxcb and support libraries failed

linux - 使用 X11/Xlib 接收焦点小部件更改事件

python - Paramiko TypeError:from_buffer()无法返回str或unicode或bytearray对象内的原始字符串的地址

python - 加载 NLTK 感知器标记器时出现 IOError

python - 比较列表中的多个唯一字符串

python - 使用python os.rmdir时,得到PermissionError : [WinError 5] Access is denied

linux - 如何通过 ssh 将 echo 的输出重定向到一个文件

ssh - SSH到中间主机

java - Python Blowfish 加密