-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex4_pexpect.py
70 lines (55 loc) · 1.41 KB
/
ex4_pexpect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
'''
Use pexpect to get sh ip int br from pynet-rtr2
This code does not run
'''
import pexpect
from getpass import getpass
import time
def login(ssh_conn):
'''
Handle sending password
'''
password = getpass()
ssh_conn.expect('ssword:')
ssh_conn.sendline(password)
ssh_conn.expect('#')
def find_prompt(ssh_conn):
'''
Find the current prompt
Pexpect is non-greedy which is problematic
'''
ssh_conn.send('\n')
time.sleep(1)
ssh_conn.expect('#')
prompt = ssh_conn.before + ssh_conn.after
return prompt.strip()
def disable_paging(ssh_conn, pattern='#', cmd='terminal length 0'):
'''
Disable the paging of output i.e. --More--
'''
ssh_conn.sendline(cmd)
ssh_conn.expect(pattern)
def main():
# pynet-rtr2
ip_addr = '184.105.247.70'
username = 'pyclass'
port = 22
ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
ssh_conn.timeout = 3
login(ssh_conn)
prompt = find_prompt(ssh_conn)
disable_paging(ssh_conn, prompt)
ssh_conn.sendline('config t')
ssh_conn.expect('#')
ssh_conn.sendline('logging buffer 9000')
ssh_conn.expect('#')
ssh_conn.sendline('end')
ssh_conn.expect(prompt)
ssh_conn.sendline('show run | inc logging buffer')
ssh_conn.expect(prompt)
print
print ssh_conn.before
print
if __name__ == '__main__':
main()