好的,我正在尝试编写一个脚本来保存我的网络设备上的配置。我在某个地方出错了,我不知道在哪里。它不会发送最终确认“y”字符,但我认为这是由于我所说的预期。
当前代码:
tabstop=2
我也试过这行产生了同样的结果:
import pexpect
import sys
import os
import time
import getpass
hostname = "switch1"
username = raw_input('Enter Your username: ')
password = getpass.getpass('Password:')
fout = file('mylog.txt','w')
child = pexpect.spawn('ssh %s@%s' % (username, hostname))
child.logfile_read = fout
child.expect('myusername@%s\'s password:' % hostname)
child.sendline(password)
child.expect('>')
child.sendline('enable')
child.expect('Password:')
child.sendline(password)
child.expect('#')
child.sendline('wr mem')
child.expect("Are you sure you want to save? (y/n) ")
child.sendline('y')
child.expect('#')
child.sendline('logout')
以下是我的开关上的样子:
child.expect("\r\n\r\nThis operation may take a few minutes.\r\nManagement interfaces will not be available during this time.\r\n\r\nAre you sure you want to save? (y/n) ")
这是我运行脚本时遇到的错误:
(switch1) #write mem
This operation may take a few minutes.
Management interfaces will not be available during this time.
Are you sure you want to save? (y/n) y
Config file 'startup-config' created successfully .
Configuration Saved!
(switch1) #
我再次认为它与期望有关“你确定要保存”但是我不确定。我可以确认登录到交换机和其他命令工作,因为我有其他脚本,这只是我无法弄清楚的。任何帮助表示赞赏。
答案 0 :(得分:1)
检查日志:
searcher: searcher_re:
0: re.compile("Are you sure you want to save? (y/n) ")
将"Are you sure you want to save? (y/n) "
编译为正则表达式会将?, (, / and )
作为特殊字符进行编译,因此请尝试将它们视为这样:
"Are you sure you want to save\? \(y\/n\) "
与文字"Are you sure you want to save? (y/n) "
匹配this
因此请将此行更改为:
child.expect("Are you sure you want to save\? \(y\/n\) ")
答案 1 :(得分:0)
Pexpect还支持部分匹配。所以你也可以使用,
child.expect('Are you sure you want to save?')