我想ssh
远程机器并使用pexpect
运行ls-l
。我是一名学习 python 语言的系统工程师,没有编码方面的知识。有人可以帮助我吗?提前致谢。
我的代码:
import pexpect
child = pexpect.spawn('/usr/bin/ssh root@192.168.32.1')
child.expect('password:', timeout=120)
child.sendline('pass123')
child.expect ('prompt# ')
#child.maxread=100000
child.sendline ('uname -a')
child.expect ('prompt# ')
print child.before, child.after
下面是运行上面代码时的错误输出。
usr/bin/python /root/PycharmProjects/IS_LAB/pexpect-test.py
Traceback (most recent call last):
File "/root/PycharmProjects/IS_LAB/pexpect-test.py", line 36, in <module>
child.expect ('prompt# ')
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1451, in expect
timeout, searchwindowsize)
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1466, in expect_list
timeout, searchwindowsize)
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1568, in expect_loop
raise TIMEOUT(str(err) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0x9b4110>
version: 3.3
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'root@192.168.32.1']
searcher: <pexpect.searcher_re object at 0x9b4450>
buffer (last 100 chars): 'cape.canonical.com/\r\n\r\nLast login: Tue Jun 16 10:26:18 2015 from 192.168.32.1\r\r\nroot@ubuntu14:~# '
before (last 100 chars): 'cape.canonical.com/\r\n\r\nLast login: Tue Jun 16 10:26:18 2015 from 192.168.32.1\r\r\nroot@ubuntu14:~# '
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 13015
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
Process finished with exit code 1
最佳答案
以下是您的代码发生的情况,它可以帮助您理解为什么您的脚本无法正常工作:
import pexpect
child = pexpect.spawn('/usr/bin/ssh root@192.168.32.1')
# This line means, "wait until you see a string that matches password:"
# in the response
child.expect('password:', timeout=120)
child.sendline('pass123') # Send the characters pass123 and "enter"
# Wait till you see a string matching prompt#
child.expect ('prompt# ')
在这一行,您的脚本正在搜索字符串 prompt#
,但服务器返回的是 root@ubuntu14:~#
。由于这与您为脚本提供的要检查的内容不匹配,因此它引发了一个异常,这基本上意味着 “我等待 TIMEOUT 期间的字符串与您的模式匹配,但我没有找到它。 "
要解决此问题,您可以输入要搜索的脚本的确切提示字符串,如下所示:
child.sendline('pass123') # Send the characters pass123 and "enter"
# Wait till you see a string matching ~#
child.expect('~#')
child.sendline ('uname -a')
child.expect ('~#')
print child.before, child.after
或者简单地暂停你的脚本几秒钟:
import time
child.sendline('pass123') # Send the characters pass123 and "enter"
time.sleep(10)
child.sendline('uname -a')
time.sleep(10)
print child.before, child.after
关于python - ssh 远程机器并使用 pexpect 运行 'ls-l',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859455/