-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelnet_showIPintbrief.py
executable file
·87 lines (74 loc) · 2.36 KB
/
telnet_showIPintbrief.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3.6
'''
Write a script that connects to a Cisco IOS device using telnet,
and executes the 'show ip int brief' command.
'''
from __future__ import print_function, unicode_literals
import telnetlib
import time
import socket
import sys
import getpass
class MyTelnetlib(object):
"""
My Telnet library
"""
def __init__(self):
self.telnet_port = 23
self.telnet_timeout = 6
def send_command(self, remote_conn, cmd):
'''
Send a command down the telnet channel
Return the response
'''
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_very_eager()
def login(self, remote_conn, username, password):
'''
Login to network device
'''
output = remote_conn.read_until("sername:", self.telnet_timeout)
remote_conn.write(username + '\n')
output += remote_conn.read_until("ssword:", self.telnet_timeout)
remote_conn.write(password + '\n')
return output
def disable_paging(self, remote_conn, paging_cmd='terminal length 0'):
'''
Disable the paging of output (i.e. --More--)
'''
return self.send_command(remote_conn, paging_cmd)
def telnet_connect(self, ip_addr):
'''
Establish telnet connection
'''
try:
return telnetlib.Telnet(ip_addr, self.telnet_port, self.telnet_timeout)
except socket.timeout:
sys.exit("Connection timed-out")
def main(self):
'''
Write a script that connects to the lab pynet-rtr1, logins, and executes the
'show ip int brief' command.
'''
try:
ip_addr = raw_input("IP address: ")
except NameError:
ip_addr = input("IP address: ")
ip_addr = ip_addr.strip()
username = input("Username: ")
password = getpass.getpass()
remote_conn = self.telnet_connect(ip_addr)
output = self.login(remote_conn, username, password)
time.sleep(1)
remote_conn.read_very_eager()
self.disable_paging(remote_conn)
output = self.send_command(remote_conn, 'show ip int brief')
print ("\n\n")
print (output)
print ("\n\n")
remote_conn.close()
if __name__ == "__main__":
EXECUTE = MyTelnetlib()
EXECUTE.main()