在pexpect中进行ssh操作时如何转义.expect中的字符

问题描述 投票:0回答:1

我正在学习 pexpect 并且对它很陌生,我正在尝试使用 python 的 pexpect 模块获取另一台机器的主机名。

当我调用 child.expect('root@.*:~\#') 时,它抛出一个名为 搜索者: searcher_re: 0: 重新编译(b'root@worker01:~#')

成功(ssh)登录后的预期字符串是 root@worker01:~#

代码如下

#!/usr/bin/python3
  
import pexpect

child = pexpect.spawn('ssh [email protected]')
child.expect('shobhit@.*password:')
child.sendline('y@9')
print('Logged In')
child.expect('root@.*:~\\#')
child.sendline('hostname')
print(child.before)
print('Got Hostname')
child.expect('root@.*:~\#')
print(child.before)
child.sendline('exit')
print('logged Out')

我尝试过转义#,但我找不到它是要转义的正则表达式模式。也尝试过在没有 \ 的情况下给予,但似乎没有任何效果

python regex pexpect
1个回答
0
投票

https://pythex.org/ 有一个计算器和一个备忘单。

#
不需要转义。

我怀疑它不匹配

root
,因为您正在以
shobhit
身份登录。尝试更通用的正则表达式以确保您收到提示:

....
print('Logged In')
child.expect('@')
child.sendline('hostname')
...
© www.soinside.com 2019 - 2024. All rights reserved.