[英]Pexect in Windows Batch File > Cygwin > Python > SSH
I have a Linux box that runs Cisco IOS and need to SSH into it sometimes to reboot it.我有一个运行 Cisco IOS 的 Linux 盒子,有时需要将 SSH 插入其中以重新启动它。 I've written a batch file that calls on Cygwin.
我编写了一个调用 Cygwin 的批处理文件。 Cygwin then calls on Python+PythonScript.
Cygwin 然后调用 Python+PythonScript。
Batch File:批处理文件:
cd c:\cygwin64\bin
bash --login -i -c "python3 /home/Owner/uccxtesting.py"
Python Script Python 脚本
import pexpect
import time
import sys
server_ip = "10.0.81.104"
server_user = "administrator"
server_pass = "secretpassword"
sshuccx1 = pexpect.spawn('ssh %s@%s' % (server_user, server_ip))
sshuccx1.logfile_read = sys.stdout.buffer
sshuccx1.timeout = 180
sshuccx1.expect('.*password:')
sshuccx1.sendline(server_pass)
sshuccx1.expect('.admin:')
sshuccx1.sendline('utils system restart')
sshuccx1.expect('Enter (yes/no)?')
sshuccx1.sendline('yes')
time.sleep(30)
When I run this, it stops at Enter yes/no
.当我运行它时,它会在
Enter yes/no
处停止。 This is what I'm getting:这就是我得到的:
I've seen plenty of examples of pexpect with expect, but there is some white space out beside the question mark.我已经看到很多 pexpect 和 expect 的例子,但是问号旁边有一些空白。 I just don't know how to tell python to expect it.
我只是不知道如何告诉 python 期待它。
There may be a bug:可能有一个错误:
utils system restart prompts for force restart ( https://bst.cisco.com/bugsearch/bug/CSCvw22828 ) utils 系统重启提示强制重启( https://bst.cisco.com/bugsearch/bug/CSCvw22828 )
Replace time.sleep(30)
with the following code to answer a possible force restart
prompt.将
time.sleep(30)
替换为以下代码以回答可能的force restart
提示。 If it works, you can get rid of the try...except
and print
commands that I added for debugging:如果它有效,您可以摆脱我为调试添加的
try...except
和print
命令:
try:
index = -1
while index != 0:
sshuccx1.expect_exact(['succeeded', 'force', ], timeout=300)
if index == 2:
print('Forcing restart...')
sshuccx1.sendline('yes')
print('Operation succeeded')
print(str(child.before))
except pexpect.ExceptionPexpect:
e_type, e_value, _ = sys.exc_info()
print('Error: ' + pexpect.ExceptionPexpect(e_type).get_trace())
print(e_type, e_value)
Also, change sshuccx1.expect('Enter (yes/no)?')
to sshuccx1.expect_exact('Enter (yes/no)?')
.另外,将
sshuccx1.expect('Enter (yes/no)?')
更改为sshuccx1.expect_exact('Enter (yes/no)?')
。 The expect
method tries to match a regex pattern, and it may get caught on the parentheses (see https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect_exact ) expect
方法尝试匹配正则表达式模式,它可能会被括号捕获(参见https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect_exact )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.