- Mastering Python Networking
- Eric Chou
- 238字
- 2021-07-02 21:42:36
More Pexpect features
In this section, we will look at more Pexpect features that might come in handy when the situation arises.
If you have a slow link to your remote device, the default expect() method timeout is 30 seconds, which you can be increased via the timeout argument:
>>> child.expect('Username', timeout=5)
You can choose to pass the command back to the user using the interact() method. This is useful when you just want to automate certain parts of the initial task:
>>> child.sendline('show version | i V')
19
>>> child.expect('iosv-1#')
0
>>> child.before
b'show version | i VrnCisco IOS Software, IOSv Software (VIOS-ADVENTERPRISEK9-M), Version 15.6(2)T, RELEASE SOFTWARE (fc2)rnProcessor board ID 9MM4BI7B0DSWK40KV1IIRrn'
>>> child.interact()
iosv-1#show run | i hostname
hostname iosv-1
iosv-1#exit
Connection closed by foreign host.
>>>
You can get a lot of information about the child.spawn object by printing it out in a string format:
>>> str(child)
"<pexpect.pty_spawn.spawn object at 0x7fb01e29dba8>ncommand: /usr/bin/telnetnargs: ['/usr/bin/telnet', '172.16.1.20']nsearcher: Nonenbuffer (last 100 chars): b''nbefore (last 100 chars): b'NTERPRISEK9-M), Version 15.6(2)T, RELEASE SOFTWARE (fc2)\r\nProcessor board ID 9MM4BI7B0DSWK40KV1IIR\r\n'nafter: b'iosv-1#'nmatch: <_sre.SRE_Match object; span=(164, 171), match=b'iosv-1#'>nmatch_index: 0nexitstatus: 1nflag_eof: Falsenpid: 2807nchild_fd: 5nclosed: Falsentimeout: 30ndelimiter: <class 'pexpect.exceptions.EOF'>nlogfile: Nonenlogfile_read: Nonenlogfile_send: Nonenmaxread: 2000nignorecase: Falsensearchwindowsize: Nonendelaybeforesend: 0.05ndelayafterclose: 0.1ndelayafterterminate: 0.1"
>>>
The most useful debug tool for Pexpect is to log the output in a file:
>>> child = pexpect.spawn('telnet 172.16.1.20')
>>> child.logfile = open('debug', 'wb')
Use child.logfile = open('debug', 'w') for Python 2. Python 3 uses byte string by default. For more information on Pexpect features, check https://pexpect.readthedocs.io/en/stable/api/index.html.
推薦閱讀
- SPSS數(shù)據(jù)挖掘與案例分析應(yīng)用實(shí)踐
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第二版)
- Progressive Web Apps with React
- Mastering RabbitMQ
- GitLab Repository Management
- Learning Network Forensics
- JAVA程序設(shè)計(jì)實(shí)驗(yàn)教程
- Mastering openFrameworks:Creative Coding Demystified
- 詳解MATLAB圖形繪制技術(shù)
- Spring Boot+MVC實(shí)戰(zhàn)指南
- 寫給程序員的Python教程
- HTML+CSS+JavaScript網(wǎng)頁制作:從入門到精通(第4版)
- Learning Grunt
- Drupal 8 Development:Beginner's Guide(Second Edition)
- Java高手是怎樣煉成的:原理、方法與實(shí)踐