Python Network Programming Applications
Python Network Programming Applications
Page 1 of 185
2 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Note: This document is intended for students enrolled in all three courses and is
distributed for personal use only. The distribution of this material to people not
enrolled in the Python Network Programming course series is strictly prohibited
and is subject to copyright infringement. The author of this document is entitled to
invoke legal and technological measures to prevent and penalize copyright infringement.
More information here: https://en.wikipedia.org/wiki/Copyright_infringement
All the code, scripts and applications are explained, turned into working applications and
tested inside the course. For detailed explanations and testing, please see the course
sections referenced by each application below. Pay attention to comments in the code!
Page 2 of 185
3 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 3 of 185
4 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
except IOError:
print "Input parameter error! Please check username, password and
file name."
Page 4 of 185
5 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
username = selected_user_file.readlines()[0].split(',')[0]
password = selected_user_file.readlines()[0].split(',')[1]
session.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
connection = session.invoke_shell()
Page 5 of 185
6 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check the
username/password file or the device configuration!"
print "* Closing program...\n"
Page 6 of 185
7 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#!/usr/bin/env python
#SNMP function
def snmp_get(ip):
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.10.1.3')
#print
cmdGen.nextCmd(cmdgen.CommunityData(comm),cmdgen.UdpTransportTarget((ip,
161)),'1.3.6.1.2.1.14.10.1.3')
#print varBindNbrTable
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.10.1.1')
#print varBindNbrIpTable
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.4.1.9.2.1.3')
#print varBindHostTable
Page 7 of 185
8 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.1.1')
#print varBindHostIdTable
Page 8 of 185
9 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 9 of 185
10 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
import random
import sys
def subnet_calc():
try:
print "\n"
#Checking octets
a = ip_address.split('.')
else:
print "\nThe IP address is INVALID! Please retry!\n"
continue
#Checking octets
b = subnet_mask.split('.')
else:
print "\nThe subnet mask is INVALID! Please retry!\n"
continue
Page 10 of 185
11 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#print bin(int(mask_octets_decimal[octet_index]))
binary_octet =
bin(int(mask_octets_decimal[octet_index])).split("b")[1]
#print binary_octet
if len(binary_octet) == 8:
mask_octets_padded.append(binary_octet)
#print mask_octets_padded
decimal_mask = "".join(mask_octets_padded)
#print decimal_mask #Example: for 255.255.255.0 =>
11111111111111111111111100000000
#print no_of_zeros
#print no_of_ones
#print no_of_hosts
#print wildcard_octets
wildcard_mask = ".".join(wildcard_octets)
#print wildcard_mask
binary_octet =
bin(int(ip_octets_decimal[octet_index])).split("b")[1]
if len(binary_octet) < 8:
binary_octet_padded = binary_octet.zfill(8)
Page 11 of 185
12 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
ip_octets_padded.append(binary_octet_padded)
else:
ip_octets_padded.append(binary_octet)
#print ip_octets_padded
binary_ip = "".join(ip_octets_padded)
#Obtain the network address and broadcast address from the binary
strings obtained above
net_ip_octets = []
for octet in range(0, len(network_address_binary), 8):
net_ip_octet = network_address_binary[octet:octet+8]
net_ip_octets.append(net_ip_octet)
#print net_ip_octets
net_ip_address = []
for each_octet in net_ip_octets:
net_ip_address.append(str(int(each_octet, 2)))
#print net_ip_address
network_address = ".".join(net_ip_address)
#print network_address
bst_ip_octets = []
for octet in range(0, len(broadcast_address_binary), 8):
bst_ip_octet = broadcast_address_binary[octet:octet+8]
bst_ip_octets.append(bst_ip_octet)
#print bst_ip_octets
bst_ip_address = []
for each_octet in bst_ip_octets:
bst_ip_address.append(str(int(each_octet, 2)))
#print bst_ip_address
broadcast_address = ".".join(bst_ip_address)
#print broadcast_address
Page 12 of 185
13 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if generate == "y":
generated_ip = []
generated_ip.append(str(random.randint(int(oct_net), int(oct_bst))))
else:
print "Ok, bye!\n"
break
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
Page 13 of 185
14 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 14 of 185
15 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 15 of 185
16 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
import paramiko
import threading
import os.path
import subprocess
import time
import sys
import re
while True:
#Prompting user for input
print "\n# # # # # # # # # # # # # # # # # # # # # # # # # # #
#\n"
ip_file = raw_input("# Enter IP file name and extension: ")
print "\n# # # # # # # # # # # # # # # # # # # # # # # # # # # #"
except IOError:
print "\n* File %s does not exist! Please check and try
again!\n" % ip_file
#Checking octets
for ip in ip_list:
a = ip.split('.')
Page 16 of 185
17 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
break
else:
print '\n* There was an INVALID IP address! Please check
and try again!\n'
check = False
continue
#Checking IP reachability
print "\n* Checking IP reachability. Please wait...\n"
check2 = False
while True:
for ip in ip_list:
ping_reply = subprocess.call(['ping', '-c', '2', '-w', '2', '-
q', '-n', ip])
if ping_reply == 0:
check2 = True
continue
elif ping_reply == 2:
print "\n* No response from device %s." % ip
check2 = False
break
else:
print "\n* Ping to the following device has FAILED:", ip
check2 = False
break
Page 17 of 185
18 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
while True:
print "# # # # # # # # # # # # # # # # # # # # # # # # # # # #\n"
user_file = raw_input("# Enter user/pass file name and extension:
")
print "\n# # # # # # # # # # # # # # # # # # # # # # # # # # # #"
else:
print "\n* File %s does not exist! Please check and try
again!\n" % user_file
continue
while True:
print "\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # #
#\n"
cmd_file = raw_input("# Enter command file name and extension: ")
print "\n# # # # # # # # # # # # # # # # # # # # # # # # # # # #"
else:
print "\n* File %s does not exist! Please check and try
again!\n" % cmd_file
continue
except KeyboardInterrupt:
print "\n\n* Program aborted by user. Exiting...\n"
sys.exit()
except KeyboardInterrupt:
print "\n\n* Program aborted by user. Exiting...\n"
Page 18 of 185
19 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
sys.exit()
except KeyboardInterrupt:
print "\n\n* Program aborted by user. Exiting...\n"
sys.exit()
Page 19 of 185
20 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
time.sleep(1)
else:
print "\nDONE for device %s" % ip
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check the
username/password file or the device configuration!"
print "* Closing program...\n"
#Creating threads
def create_threads():
threads = []
for ip in ip_list:
th = threading.Thread(target = open_ssh_conn, args = (ip,))
#args is a tuple with a single element
th.start()
threads.append(th)
for th in threads:
th.join()
Page 20 of 185
21 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#End of program
Page 21 of 185
22 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#!/usr/bin/env python
import telnetlib
import threading
import os.path
import subprocess
import time
import sys
while True:
#Prompting user for input
ip_file = raw_input("Enter IP file name and extension: ")
except IOError:
print "\nFile %s does not exist! Please check and try
again!\n" % ip_file
#Checking octets
for ip in ip_list:
a = ip.split('.')
else:
Page 22 of 185
23 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Checking IP reachability
print "\nChecking IP reachability...\n"
check2 = False
while True:
for ip in ip_list:
ping_reply = subprocess.call(['ping', '-c', '3', '-w', '3', '-
q', '-n', ip])
if ping_reply == 0:
check2 = True
continue
elif ping_reply == 2:
print "\nNo response from device %s." % ip
check2 = False
break
else:
print "\nPing to the following device has FAILED:", ip
check2 = False
break
while True:
cmd_file = raw_input("Enter command file name and extension: ")
Page 23 of 185
24 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if os.path.isfile(cmd_file) == True:
print "\nSending command(s) to device(s)...\n"
break
else:
print "\nFile %s does not exist! Please check and try
again!\n" % cmd_file
continue
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
Page 24 of 185
25 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
connection.write(username + "\n")
except IOError:
print "Input parameter error! Please check username, password and
file name."
#Creating threads
def create_threads():
threads = []
for ip in ip_list:
th = threading.Thread(target = open_telnet_conn, args = (ip,))
#args is a tuple with a single element
th.start()
threads.append(th)
Page 25 of 185
26 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
for th in threads:
th.join()
#End of program
Page 26 of 185
27 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 27 of 185
28 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
DHCP DISCOVER:
'Ether(src=\'08:00:27:f9:51:87\', dst=\'ff:ff:ff:ff:ff:ff\',
type=2048)/IP(frag=0L, src=\'0.0.0.0\', proto=17, tos=16,
dst=\'255.255.255.255\', chksum=14742, len=328, options=[], version=4L,
flags=0L, ihl=5L, ttl=128, id=0)/UDP(dport=67, sport=68, len=308,
chksum=47898)/BOOTP(hlen=6,
sname=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\', xid=398202904, ciaddr=\'0.0.0.0\',
hops=0, giaddr=\'0.0.0.0\',
chaddr="\\x08\\x00\'\\xf9Q\\x87\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00", yiaddr=\'0.0.0.0\', secs=0, flags=0L, htype=1,
file=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\',
siaddr=\'0.0.0.0\', options=\'c\\x82Sc\', op=1)/DHCP(options=[(\'message-
type\', 1), (\'hostname\', \'kali-teo\'), (\'param_req_list\',
\'\\x01\\x1c\\x02\\x03\\x0f\\x06w\\x0c,/\\x1ay*\'), \'end\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\'])'
DHCP OFFER:
'Ether(src=\'c0:04:1a:5c:00:01\', dst=\'08:00:27:f9:51:87\',
type=2048)/IP(frag=0L, src=\'192.168.2.111\', proto=17, tos=0,
dst=\'192.168.2.1\', chksum=13540, len=328, options=[], version=4L,
flags=0L, ihl=5L, ttl=255, id=0)/UDP(dport=68, sport=67, len=308,
chksum=19350)/BOOTP(hlen=6,
sname=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\', xid=398202904, ciaddr=\'0.0.0.0\',
hops=0, giaddr=\'0.0.0.0\',
chaddr="\\x08\\x00\'\\xf9Q\\x87\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00", yiaddr=\'192.168.2.1\', secs=0, flags=0L, htype=1,
file=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
Page 28 of 185
29 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\',
siaddr=\'0.0.0.0\', options=\'c\\x82Sc\', op=2)/DHCP(options=[(\'message-
type\', 2), (\'server_id\', \'192.168.2.111\'), (\'lease_time\', 86400),
(\'renewal_time\', 43200), (\'rebinding_time\', 75600), (\'subnet_mask\',
\'255.255.255.0\'), \'end\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\'])'
DHCP REQUEST:
'Ether(src=\'08:00:27:f9:51:87\', dst=\'ff:ff:ff:ff:ff:ff\',
type=2048)/IP(frag=0L, src=\'0.0.0.0\', proto=17, tos=16,
dst=\'255.255.255.255\', chksum=14742, len=328, options=[], version=4L,
flags=0L, ihl=5L, ttl=128, id=0)/UDP(dport=67, sport=68, len=308,
chksum=61228)/BOOTP(hlen=6,
sname=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
Page 29 of 185
30 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\', xid=398202904, ciaddr=\'0.0.0.0\',
hops=0, giaddr=\'0.0.0.0\',
chaddr="\\x08\\x00\'\\xf9Q\\x87\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00", yiaddr=\'0.0.0.0\', secs=0, flags=0L, htype=1,
file=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\',
siaddr=\'0.0.0.0\', options=\'c\\x82Sc\', op=1)/DHCP(options=[(\'message-
type\', 3), (\'server_id\', \'192.168.2.111\'), (\'requested_addr\',
\'192.168.2.1\'), (\'hostname\', \'kali-teo\'), (\'param_req_list\',
\'\\x01\\x1c\\x02\\x03\\x0f\\x06w\\x0c,/\\x1ay*\'), \'end\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\'])'
DHCP ACK:
'Ether(src=\'c0:04:1a:5c:00:01\', dst=\'08:00:27:f9:51:87\',
type=2048)/IP(frag=0L, src=\'192.168.2.111\', proto=17, tos=0,
dst=\'192.168.2.1\', chksum=13539, len=328, options=[], version=4L,
flags=0L, ihl=5L, ttl=255, id=1)/UDP(dport=68, sport=67, len=308,
chksum=18582)/BOOTP(hlen=6,
sname=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\', xid=398202904, ciaddr=\'0.0.0.0\',
hops=0, giaddr=\'0.0.0.0\',
chaddr="\\x08\\x00\'\\xf9Q\\x87\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00", yiaddr=\'192.168.2.1\', secs=0, flags=0L, htype=1,
file=\'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0
0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x
00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\
\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\',
siaddr=\'0.0.0.0\', options=\'c\\x82Sc\', op=2)/DHCP(options=[(\'message-
type\', 5), (\'server_id\', \'192.168.2.111\'), (\'lease_time\', 86400),
(\'renewal_time\', 43200), (\'rebinding_time\', 75600), (\'subnet_mask\',
\'255.255.255.0\'), \'end\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\', \'pad\',
\'pad\', \'pad\', \'pad\', \'pad\', \'pad\'])'
'''
Page 30 of 185
31 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
import subprocess
import logging
import random
import sys
#This will suppress all messages that have a lower level of seriousness
than error messages, while running or loading Scapy
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
try:
from scapy.all import *
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#To see a list of what commands Scapy has available, run the lsc()
function.
#Run the ls() command to see ALL the supported protocols.
#Run the ls(protocol) command to see the fields and default values for any
protocol.
#See packet layers with the .summary() function.
#See packet contents with the .show() function.
#Dig into a specific packet layer using a list index:
pkts[3][2].summary()...
#...the first index chooses the packet out of the pkts list, the second
index chooses the layer for that specific packet.
#Using the .command() packet method will return a string of the command
necessary to recreate that sniffed packet.
Page 31 of 185
32 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Scapy normally makes sure that replies come from the same IP address the
stimulus was sent to.
#But our DHCP packet is sent to the IP broadcast address (255.255.255.255)
and any answer packet will have the IP address of the replying DHCP server
as its source IP address (e.g. 192.168.2.101).
#Because these IP addresses don't match, we have to disable Scapy's check
with conf.checkIPaddr = False before sending the stimulus.
#Source:
https://bitbucket.org/pbi/test/wiki/doc/IdentifyingRogueDHCPServers
conf.checkIPaddr = False
#print answd
#print unanswd
#print answd.summary()
#print unanswd.summary()
#print answd[0][1][BOOTP].yiaddr
#The IP offered by the DHCP server to the client is extracted from the
received answer
offered_ip = answd[0][1][BOOTP].yiaddr
#print offered_ip
Page 32 of 185
33 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#print answr
#print unanswr
#print answr[0][1][IP].src
#print answr[0][1][BOOTP].yiaddr
#The IP offered by the DHCP server to the client is extracted from the
received answer
offered_ip_ack = answr[0][1][BOOTP].yiaddr
client_mac.append(hw)
Page 33 of 185
34 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if user_option_sim == "s":
print "\nObtained leases will be exported to
'DHCP_Leases.txt'!"
try:
#Calling the function for the required number of times
(pkt_no)
for iterate in range(0, int(pkt_no)):
all_leased_ips = generate_dhcp_seq()[0]
#print all_leased_ips
except IndexError:
print "No DHCP Server detected or connection is broken."
print "Check your network settings and try again.\n"
sys.exit()
#print all_leased_ips
#print server_id
#print client_mac
dhcp_leases.close()
Page 34 of 185
35 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
continue
if user_option_release == "s":
print "\n"
#print all_leased_ips
#print server_id
#print client_mac
try:
#Check if required IP is in the list and run the
release function for it
if user_option_address in all_leased_ips:
index =
all_leased_ips.index(user_option_address)
generate_dhcp_release(user_option_address,
client_mac[index], server_id[index])
else:
print "IP Address not in list.\n"
continue
#print all_leased_ips
#print server_id
#print client_mac
try:
#Check if required IP is in the list and run the
release function for it
for user_option_address in all_leased_ips:
Page 35 of 185
36 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
index =
all_leased_ips.index(user_option_address)
generate_dhcp_release(user_option_address,
client_mac[index], server_id[index])
continue
else:
break
else:
print "Exiting... See ya...\n\n"
sys.exit()
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
#End of program
Page 36 of 185
37 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 37 of 185
38 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Make sure to have SSHv2 enabled and RSA 1024 bit key generated on every
device!
#Initialize colorama
init()
Page 38 of 185
39 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
else:
print Fore.RED + Style.BRIGHT + "\nIncorrect number of arguments
(files) passed into the script."
print Fore.RED + "Please try again.\n"
sys.exit()
while True:
#Changing exception message
try:
#Open user selected file for reading (IP addresses file)
selected_ip_file = open(ip_file, 'r')
except IOError:
print Fore.RED + "\n* File %s does not exist! Please check and
try again!\n" % ip_file
sys.exit()
#Checking octets
for ip in ip_list:
a = ip.split('.')
else:
print '\n* There was an INVALID IP address! Please check
and try again!\n'
check = False
continue
Page 39 of 185
40 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Checking IP reachability
print "* Checking IP reachability... Please wait...\n"
check2 = False
while True:
for ip in ip_list:
ping_reply = subprocess.call(['ping', '-c', '3', '-w', '3', '-
q', '-n', ip], stdout = subprocess.PIPE)
if ping_reply == 0:
check2 = True
continue
elif ping_reply == 2:
print Fore.RED + "\n* No response from device %s." % ip
check2 = False
break
else:
print Fore.RED + "\n* Ping to the following device has
FAILED:", ip
check2 = False
break
while True:
#Changing output messages
if os.path.isfile(user_file) == True:
print "\n* SSHv2 connection file has been validated. Checking
MySQL connection file...\n"
break
Page 40 of 185
41 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
else:
print Fore.RED + "\n* File %s does not exist! Please check and
try again!\n" % user_file
sys.exit()
while True:
#Changing output messages
if os.path.isfile(sql_file) == True:
print "\n* MySQL connection file has been validated...\n"
print "\n* Any MySQL errors will be logged to: " + Fore.YELLOW
+ "SQL_Error_Log.txt\n" + Fore.BLUE
print "\n* Reading network data and writing to MySQL...\n"
break
else:
print Fore.RED + "\n* File %s does not exist! Please check and
try again!\n" % sql_file
sys.exit()
except KeyboardInterrupt:
print Fore.RED + "\n\n* Program aborted by user. Exiting...\n"
sys.exit()
except KeyboardInterrupt:
print Fore.RED + "\n\n* Program aborted by user. Exiting...\n"
sys.exit()
except KeyboardInterrupt:
print Fore.RED + "\n\n* Program aborted by user. Exiting...\n"
sys.exit()
check_sql = True
def sql_connection(command, values):
Page 41 of 185
42 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
global check_sql
sql_host = selected_sql_file.readlines()[0].split(',')[0]
sql_username = selected_sql_file.readlines()[0].split(',')[1]
sql_password = selected_sql_file.readlines()[0].split(',')[2]
sql_database =
selected_sql_file.readlines()[0].split(',')[3].rstrip("\n")
cursor = sql_conn.cursor()
cursor.execute("USE NetMon")
cursor.execute(command, values)
#Commit changes
sql_conn.commit()
except mdb.Error, e:
sql_log_file = open("SQL_Error_Log.txt", "a")
Page 42 of 185
43 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
selected_sql_file.close()
top3_cpu = {}
top3_io_mem = {}
top3_proc_mem = {}
top3_upint = {}
Page 43 of 185
44 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
else:
print Fore.GREEN + "* All parameters were extracted from
device %s" % ip,
Page 44 of 185
45 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
hostname = dev_hostname.group(1)
#print hostname
serial_no = ""
if len(re.findall(r"(.+), SN: (.+?)\r\n", output)) == 0:
serial_no = "unknown"
else:
serial_no = re.findall(r"(.+), SN: (.+?)\r\n",
output)[0][1].strip()
#print serial_no
for j in uptime_value_list:
if 'year' in j:
y_sec = int(j.split(' ')[0]) * 31449600
elif 'week' in j:
w_sec = int(j.split(' ')[0]) * 604800
elif 'day' in j:
d_sec = int(j.split(' ')[0]) * 86400
Page 45 of 185
46 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
elif 'hour' in j:
h_sec = int(j.split(' ')[0]) * 3600
elif 'minute' in j:
m_sec = int(j.split(' ')[0]) * 60
cpu_model = ""
if re.search(r".isco (.+?) \((.+)\) processor(.+)\n", output) ==
None:
cpu_model = "unknown"
else:
cpu_model = re.search(r".isco (.+?) \((.+)\) processor(.+)\n",
output).group(2)
#print cpu_model
cpu_speed = ""
if re.search(r"(.+?)at (.+?)MHz(.+)\n", output) == None:
cpu_speed = "unknown"
else:
cpu_speed = re.search(r"(.+?)at (.+?)MHz(.+)\n",
output).group(2)
#print cpu_speed
serial_int = ""
if re.findall(r"Serial([0-9]*)/([0-9]*) (.+)\n", output) == None:
serial_int = "no serial"
else:
serial_int = len(re.findall(r"Serial([0-9]*)/([0-9]*) (.+)\n",
output))
#print serial_int
internal_pro = ','.join(is_internal)
external_pro = ','.join(is_external)
#print internal_pro
#print external_pro
Page 46 of 185
47 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Append used proc memory values for each device to the mem_values
list
proc_mem_values.append(float(proc_mem_percent))
Page 47 of 185
48 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Append used I/O memory values for each device to the mem_values
list
io_mem_values.append(float(io_mem_percent))
dev_total_int = re.findall(r"([A-Za-z]*)Ethernet([0-
9]*)(.+)YES(.+)\n", output)
total_int = len(dev_total_int)
#print total_int
dev_total_up_int = re.findall(r"(.+)Ethernet([0-9]*)/([0-
9]*)[\s]*(.+)up[\s]*up", output)
total_up_int = len(dev_total_up_int)
#print total_up_int
except paramiko.AuthenticationException:
print Fore.RED + "* Invalid SSH username or password. \n* Please
check the username/password file or the device configuration!\n"
check_sql = False
#Creating threads
def create_threads():
threads = []
Page 48 of 185
49 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
for ip in ip_list:
th = threading.Thread(target = open_ssh_conn, args = (ip,))
#args is a tuple with a single element
th.start()
threads.append(th)
for th in threads:
th.join()
poll_timestamp = datetime.datetime.now()
#print poll_timestamp
###Testing code###
#print cpu_values
#print proc_mem_values
#print io_mem_values
#print upint_values
#print top3_cpu
#print top3_proc_mem
#print top3_io_mem
#print top3_upint
###
Page 49 of 185
50 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
except ZeroDivisionError:
print "* There was an error while computing a network parameter.
No record has been added to MySQL. Please retry."
cpu_average()
except ZeroDivisionError:
print "* There was an error while computing a network parameter.
No record has been added to MySQL. Please retry."
mem_proc_average()
except ZeroDivisionError:
print "* There was an error while computing a network parameter.
No record has been added to MySQL. Please retry."
mem_io_average()
Page 50 of 185
51 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
sql_connection("INSERT INTO
UPEthInterfaces(NetworkUPEthIntfPercent,Top3UPEthIntf,PollTimestamp)
VALUES(%s, %s, %s)", (upint, top3_list, poll_timestamp))
except ZeroDivisionError:
print "* There was an error while computing a network parameter.
No record has been added to MySQL. Please retry."
upint_total()
#print check_sql
if check_sql == True:
print "\n* All parameters were successfully exported to MySQL."
else:
print Fore.RED + "\n* There was a problem exporting data to MySQL.\n*
Check the files, database and SQL_Error_Log.txt.\n"
#De-initialize colorama
deinit()
#End of program
Page 51 of 185
52 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 52 of 185
53 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
'''
Make the following configuration on each router in the network:
configure terminal
snmp-server community public RO
'''
#Necessary Python packages (they are already installed on the Debian VM)
#https://pypi.python.org/pypi/setuptools
#https://pypi.python.org/pypi/networkx
#https://pypi.python.org/pypi/matplotlib
#https://pypi.python.org/pypi/pysnmp
#https://pypi.python.org/pypi/colorama
import pprint
import subprocess
import binascii
import sys
try:
import matplotlib.pyplot as matp
except ImportError:
print Fore.RED + Style.BRIGHT + "\n* Module matplotlib needs to be
installed on your system."
print "* Download it from: https://pypi.python.org/pypi/matplotlib\n"
+ Fore.WHITE + Style.BRIGHT
sys.exit()
try:
import networkx as nx
except ImportError:
print Fore.RED + Style.BRIGHT + "\n* Module networkx needs to be
installed on your system."
print "* Download it from: https://pypi.python.org/pypi/networkx"
print "* You should also install decorator:
https://pypi.python.org/pypi/decorator\n" + Fore.WHITE + Style.BRIGHT
sys.exit()
try:
#Module for output coloring
from colorama import init, deinit, Fore, Style
except ImportError:
Page 53 of 185
54 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
try:
#Module for SNMP
from pysnmp.entity.rfc3413.oneliner import cmdgen
except ImportError:
print Fore.RED + Style.BRIGHT + "\n* Module pysnmp needs to be
installed on your system."
print "* Download it from: https://pypi.python.org/pypi/pysnmp\n" +
Fore.WHITE + Style.BRIGHT
sys.exit()
#Initialize colorama
init()
except KeyboardInterrupt:
print Fore.RED + Style.BRIGHT + "\n\n* Program aborted by user.
Exiting...\n"
sys.exit()
Page 54 of 185
55 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
else:
print '\n* There was an INVALID IP address! Please check and
try again!\n'
sys.exit()
#Checking IP reachability
print Fore.GREEN + Style.BRIGHT + "\n* Valid IP address. Checking IP
reachability...\n"
while True:
ping_reply = subprocess.call(['ping', '-c', '3', '-w', '3', '-q',
'-n', ip], stdout = subprocess.PIPE)
if ping_reply == 0:
print Fore.GREEN + Style.BRIGHT + "* Device is reachable.
Performing SNMP extraction...\n"
print Fore.GREEN + Style.BRIGHT + "* This may take a few
moments...\n"
break
elif ping_reply == 2:
print Fore.RED + Style.BRIGHT + "\n* No response from device
%s." % ip
sys.exit()
else:
print Fore.RED + Style.BRIGHT + "\n* Ping to the following
device has FAILED:", ip
print "\n"
sys.exit()
except KeyboardInterrupt:
print Fore.RED + Style.BRIGHT + "\n\n* Program aborted by user.
Exiting...\n"
sys.exit()
ospf = []
#SNMP function
def snmp_get(ip):
nbridlist = []
nbriplist = []
ospf_devices = {}
Page 55 of 185
56 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.10.1.3')
#print
cmdGen.nextCmd(cmdgen.CommunityData(comm),cmdgen.UdpTransportTarget((ip,
161)),'1.3.6.1.2.1.14.10.1.3')
#print varBindNbrTable
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.10.1.1')
#print varBindNbrIpTable
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.4.1.9.2.1.3')
#print varBindHostTable
cmdgen.UdpTransportTarget((ip, 161)),
'1.3.6.1.2.1.14.1.1')
#print varBindHostIdTable
Page 56 of 185
57 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#print ip
nbr_r_id = '.'.join(str(i) for i in ip)
#print nbr_r_id
nbridlist.append(nbr_r_id)
#print('%s = %s' % (oid, nbr_r_id))
ospf.append(ospf_devices)
return ospf
def find_unqueried_neighbors():
Page 57 of 185
58 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#print "HID"
#print all_host_ids
#print "\n"
if each_nid == "0.0.0.0":
pass
else:
all_nbr_ids.append(each_nid)
#print "NBR"
#print all_nbr_ids
#print list(set(all_nbr_ids))
#print "\n"
for p in all_nbr_ids:
if p not in all_host_ids:
all_outsiders.append(p)
#print "OUT"
#print all_outsiders
#print "\n"
if q == s:
new_ip = ospf[r]["NbrRtrIp"][index]
snmp_get(new_ip)
else:
pass
Page 58 of 185
59 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if (len(list(set(find_unqueried_neighbors()[0]))) ==
len(list(set(find_unqueried_neighbors()[1])))):
break
final_devices_list = find_unqueried_neighbors()[2]
#pprint.pprint(final_devices_list)
#pprint.pprint(neighborship_dict)
while True:
try:
#User defined actions
print Fore.BLUE + Style.BRIGHT + "* Please choose an action:\n\n1
- Display OSPF devices on the screen\n2 - Export OSPF devices to CSV
file\n3 - Generate OSPF network topology\ne - Exit"
user_choice = raw_input("\n* Enter your choice: ")
print "\n"
#Defining actions
if user_choice == "1":
continue
Page 59 of 185
60 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
csv_file.close()
continue
continue
else:
print Fore.RED + Style.BRIGHT + "* Invalid option. Please
retry.\n"
continue
except KeyboardInterrupt:
print Fore.RED + Style.BRIGHT + "\n\n* Program aborted by user.
Exiting...\n"
sys.exit()
#De-initialize colorama
Page 60 of 185
61 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
deinit()
#End of program
Page 61 of 185
62 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
This application is a basic network sniffer, which captures some predefined protocols and
saves info about each network packet in an external file.
As with the other applications in this course, the full code is available for download.
Based on what you have learned so far in the course, its your job now to study,
understand and test the code against a network device, as youve seen me doing with the
previous applications.
Feel free to alter the code in any way you want, add new protocols to be captured, more
data to be exported in the external file and so on. New functionality of any kind is welcome.
Just make sure to adapt your code to the contents of the packet in Scapy.
Also, please read the first 33 lines in the code carefully, as they are a good introduction
to the code that follows.
As youve probably guessed, I used Scapy to build this sniffer, because this tool allows
packet handling, decoding and analysis in a very intuitive way.
Also, pay special attention to the recommendations and settings that I made before
starting to build the user menu and so on. I am referring to these lines and the ones above
them:
net_iface = raw_input("* Enter the interface on which to run the sniffer (like 'eth1'):
")
subprocess.call(["ifconfig", net_iface, "promisc"], stdout=None, stderr=None,
shell=False)
Further more, please read the comments before every code block, as they are good
guidelines to what functionality is covered by that piece of code.
As you can see at line 72, the program asks the user what network interface is the capture
process going to be executed on. A good example is entering eth1.
net_iface = raw_input("* Enter the interface on which to run the sniffer (like 'eth1'):
")
Then, at line 80, the user is asked to enter the number of packets he wishes to be captured
by the sniffer:
Page 62 of 185
63 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
At line 92, the program requires the number of seconds to run the capture:
time_to_sniff = raw_input("* Enter the number of seconds to run the capture: ")
At line 103, the program asks the user for the protocol to filter the packets by:
Lines 115 and 116 are dedicated to choosing the file name and creating the file, by
opening it for writing (w):
At line 124, you can find the function that takes care of the parameter extraction from
each packet and logging the packet info to the file: def packet_log(pkt)
The program implements a counter for each packet, then records the source MAC
address and destination MAC address to the file, on a single row.
Finally, the sniffing process is initialized by the sniff() function in Scapy, at line 138,
passing the values collected from the user as arguments to this function.
Now, to test the program, first you should have direct connectivity from the Debian VM to
the router in GNS3 (R1 - 192.168.2.101 was my test device):
Lets choose ICMP packets for capturing purposes and after the capture is started, I am
going to ping the VM (192.168.2.100) from R1.
Please see the following way to use the program menu as an example:
* Enter the interface on which to run the sniffer (like 'eth1'): eth1
Page 63 of 185
64 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
At this point, the program listens for all the ICMP packets it receives in the next 10
seconds on eth1 (ping from R1 now!). The results will be exported to the udemy.txt file.
Page 64 of 185
65 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#In Scapy, we will use the sniff() function to capture network packets.
#To see a list of what commands Scapy has available, run the lsc()
function.
#Run the ls() command to see ALL the supported protocols.
#Run the ls(protocol) command to see the fields and default values for any
protocol.
#See packet layers with the .summary() function.
#See packet contents with the .show() function.
#Dig into a specific packet layer using a list index:
pkts[3][2].summary()...
Page 65 of 185
66 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#...the first index chooses the packet out of the pkts list, the second
index chooses the layer for that specific packet.
#Using the .command() packet method will return a string of the command
necessary to recreate that sniffed packet.
#To see the list of optional arguments for the sniff() function:
'''
>>> print sniff.__doc__
Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] +
L2ListenSocket args) -> list of packets
import logging
import subprocess
#This will suppress all messages that have a lower level of seriousness
than error messages, while running or loading Scapy
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
try:
from scapy.all import *
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
Page 66 of 185
67 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Asking the user for some parameters: interface on which to sniff, the
number of packets to sniff, the time interval to sniff, the protocol
#Making the necessary configurations
#Asking the user for the number of packets to sniff (the "count"
parameter)
pkt_to_sniff = raw_input("Enter the number of packets to capture (0 is
infinity): ")
#Asking the user for the time interval to sniff (the "timeout" parameter)
time_to_sniff = raw_input("* Enter the number of seconds to run the
capture: ")
Page 67 of 185
68 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Asking the user for any protocol filter he might want to apply to the
sniffing process
#For this example I chose three protocols: ARP, BOOTP, ICMP
#You can customize this to add your own desired protocols
proto_sniff = raw_input("* Enter the protocol to filter by
(arp|bootp|icmp|0 is all): ")
#Filtering the packets based on the protocol. Using the lower() method
to ignore the case when searching for the protocol in the packet.
if proto_sniff.lower() in pkt[0][1].summary().lower():
packet_no = packet_no + 1
#Writing the data for each packet to the external file
print >>sniffer_log, "Packet " + str(packet_no) + ": " + "SMAC: "
+ pkt[0].src + " DMAC: " + pkt[0].dst
#print pkt.show()
Page 68 of 185
69 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
print "* Please check the %s file to see the captured packets.\n" %
file_name
#End of program. Feel free to modify it, test it, add new protocols to
sniff and improve de code whenever you feel the need to.
Page 69 of 185
70 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
This application connects to a router in the network via Telnet, extracts the output
of show running-config and show startup-config, filters the irrelevant lines and
finally compares the configurations. Now, I know this can be accomplished using
the show archive config differencescommand in Cisco CLI, but I wanted you to know
how can this task be accomplished using Python.
As with the other applications in this course, the full code is available for download.
Based on what you have learned so far in the course, its your job now to study,
understand and test the code against a network device, as youve seen me doing with the
previous applications.
Feel free to alter the code in any way you want. New functionality of any kind is welcome,
enhancements as well. Just make sure to adapt your code to the command output format.
Also, please read the first 13 lines in the code carefully, as they are a good introduction
to the code that follows. As you can see, the first thing you should do is configure Telnet
access on the router and the username and password:
At line 27, I have defined the ip_validity() function, which takes care of checking whether
the IP address of the router, which the user enters at the prompt, is valid or not. You have
already seen this kind of validity check in action in the previous applications, so there is
nothing new here. The same comment is valid for the file_validity() function (line 46).
Both functions are defined at this point and will be called later in the code.
At line 61, the telnet() function is defined, which takes a single parameter:command. The
value of this parameter will be passed to theconnection.write() method at line 96.
Starting with line 108, I defined the user menu, which will accept 3 options, except e -
Exit program:
1 - Compare running-config with startup-config
2 - Compare running-config with local file
3 - Compare startup-config with local file
I had treated only the first option, comparing the running-config with the startup-config -
Page 70 of 185
71 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
lines 115-196, leaving you with the job of coding and testing the other two options, having
my code from option 1 as a guideline.
Now, lets look at option 1 for a bit. First, I called the ip_validity() function to get this out
of the way. Next, a very important step, I called the telnet()function for each of the two
commands I am interested in, and saved the returned output to a separate
variable: output_run for the running-config and output_start for the startup-config.
Then, I have created (opened for writing) two files, each of them storing the output of the
corresponding command. The file names are intuitively chosen. Dont forget to close the
files after writing the contents of those variables, to save the information.
Next, I opened the files for reading and used the readlines() method on each file object
to store the lines in each file as elements of a list. Of course, then I closed the files.
Then, using a for loop, I have filtered the lines in each file which were of no interest to
our goal. We are only interested in the lines starting with the one defining the IOS
version: version 12.4 for example. That is actually the first relevant line in each file.
Now, after cleaning the files, we are left with only the pure router configurations. Its time
to create a new file (file_diff.txt), in which all the config differences are going to be stored.
Actually, we are going to compare the two lists obtained with the readlines() method.
Finally, using list comprehensions, we are going to find the lines in the running-config
which are not present in the startup-config and vice versa. In case there are multiple
differences, we use a for loop to iterate over the lists and then print those differences
directly into the file_diff.txt file., one per line As stated in the code, the rule is:
A "+" sign means the line is present in the RUNNING-CONFIG but not in the
STARTUP-CONFIG
A "-" sign means the line is present in the STARTUP-CONFIG but not in the
RUNNING-CONFIG
Now, lets make a quick test. If you have just started the router and made no config yet,
then the startup-config and running-config are the same. No surprise here. But, to make
the test more relevant, lets configure a few things before starting the comparison, without
saving the changes to the startup-config. So, lets go to router R1:
Now, these three configurations are the differences between the startup-config and the
running-config. We should see them after running our program, saved in
the file_diff.txt file. Lets test this:
Page 71 of 185
72 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Now lets check the results. We should see all three commands with a +sign, right?
root@debian:/home/debian/workingdir#
...and success! As expected, the three commands are marked as differences, in the file.
Page 72 of 185
73 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Page 73 of 185
74 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
import telnetlib
import os.path
import subprocess
import time
import sys
def ip_validity():
global ip_address
#Checking IP validity
while True:
ip_address = raw_input("Enter an IP address: ")
#Checking octets
a = ip_address.split('.')
else:
print "\nThe IP address is INVALID! Please retry!\n"
continue
def file_validity():
while True:
Page 74 of 185
75 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
else:
print "\nFile %s does not exist! Please check and try
again!\n" % cfg_file
continue
def telnet(command):
#Connecting to router via Telnet
#Define telnet parameters
username = 'teopy'
password = 'python'
Page 75 of 185
76 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
router_output = connection.read_very_eager()
#print router_output
return router_output
if user_option == "1":
###Checking IP validity first###
ip_validity()
#print output_run
#print output_start
list_run = file_run.readlines()
Page 76 of 185
77 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#print list_run
list_start = file_start.readlines()
#print list_start
#print list_run
#print list_start
Page 77 of 185
78 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
file_diff.close()
else:
print "Exiting... See ya...\n\n"
sys.exit()
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
#End of program
Page 78 of 185
79 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
import socket
srv_ip = socket.gethostbyname(socket.gethostname())
srv_port = 11111
srv.bind((srv_ip, srv_port))
srv.listen(2)
client, ip = srv.accept()
client.close()
import socket
ip = socket.gethostbyname(socket.gethostname())
port = 11111
cli.connect((ip, port))
server_reply = cli.recv(65535)
print server_reply
cli.close()
Page 79 of 185
80 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
To allow remote access to your Cisco IOS device, you must enter the configuration below.
Please note that some versions of Cisco IOS do not support SSH, so you should make
sure you have a SSH-compatible IOS version. According to cisco.com: "The Cisco IOS
image used must be a k9(crypto) image in order to support SSH. For example c3750e-
universalk9-tar.122-35.SE5.tar is a k9 (crypto) image."
Here is the configuration you have to make in order to allow remote access. Please enter
Global Configuration mode (#configure terminal) before pasting this configuration.
IP Configuration:
enable
configure terminal
interface Fa0/0
Page 80 of 185
81 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
no shutdown
SSHv2 Configuration:
line vty 0 4
privilege level 15
login local
exit
ip domain-name mihai
hostname Cisco-R1
!When asked How many bits in the modulus [512]: enter 1024
1024
ip ssh version 2
Page 81 of 185
82 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
ip ssh time-out 60
ip ssh authentication-retries 3
SNMP Configuration:
show ip ssh
show snmp
Saving Configuration:
NOTE! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
Page 82 of 185
83 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Using a while loop to allow the user to return and choose another cXdY
combination.
while True:
#Asking the user about the output he wants to obtain.
print '\nNOTE! The format is always cXdY, where X is the command
number and Y is the device number in the lists you enter.\nIf X = a this
means that command Y will be executed on ALL devices.\nIf Y = a this means
that all commands will be executed on device X.\nIf both X = a and Y = a
then all the commands will be executed on all devices.'
Page 83 of 185
84 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Now if the user types 'cada' for example, meaning execute all
commands on all devices.
elif user_option_1[1] == 'a' and user_option_1[3] == 'a':
all_outputs_list = []
for device in devices_list:
for command in commands_list:
all_outputs_list.append('Device: ' + device + ' -
Command #' + str(commands_list.index(command) + 1) + ':\n\n' +
cmd.results[device][command])
final_result = '\r\n'.join(all_outputs_list)
Page 84 of 185
85 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if back == 'y':
continue
else:
break
if back == 'y':
continue
else:
break
#End Of Program
Page 85 of 185
86 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Running all commands from all the given files on all given devices.
cmd = CommandRunner(devices = devices_list, files = cmd_files_list)
#Raise exception in case one file does not exist. IP addresses are already
verified by Trigger.
except IOError, reason:
print '\nError! Reason: ' + str(reason) + '.\n'
print 'Please check the file(s) and paths. Redirecting back to
prompt...\n'
#End Of Program
Page 86 of 185
87 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
To allow remote access to your Juniper JunOS device, you must enter the configuration
below.
Note! Since JunOS requires a higher level of security when setting the remote access
password ('error: require change of case, digits or punctuation'), I configured
username: mihai1 and password: python1 and also added them in the .tacacsrc file
(~/.tacacsrc) on the Ubuntu 15.10 VM.
IP Configuration:
cli
edit
SSHv2 Configuration:
configure
Page 87 of 185
88 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
set system login user mihai1 class super-user authentication plain-text-password [Enter]
SNMP Configuration:
commit
Checking Configuration:
show snmp
Saving Configuration:
commit
Page 88 of 185
89 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#save [email protected]:/tftpboot/juniper_cfg
Note: Before trying to save the configuration to the TFTP server on the Ubuntu VM, I had
to install openssh on the VM and allow SSH access from the Juniper SRX100, using the
following commands in the Linux shell:
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
Page 89 of 185
90 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Using a while loop to allow the user to return and choose another cXdY
combination.
while True:
#Asking the user about the output he wants to obtain.
print '\nNOTE! The format is always cXdY, where X is the command
number and Y is the device number in the lists you enter.\nIf X = a this
means that command Y will be executed on ALL devices.\nIf Y = a this means
that all commands will be executed on device X.\nIf both X = a and Y = a
then all the commands will be executed on all devices.'
#Now if the user types 'cada' for example, meaning execute all
commands on all devices.
elif user_option_1[1] == 'a' and user_option_1[3] == 'a':
all_outputs_list = []
for device in devices_list:
for command in commands_list:
Page 90 of 185
91 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if back == 'y':
continue
else:
break
if back == 'y':
continue
else:
break
#End Of Program
Page 91 of 185
92 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Running all commands from all the given files on all given devices.
cmd = CommandRunner(devices = devices_list, files = cmd_files_list,
force_cli = True, timeout = None)
#Raise exception in case one file does not exist. IP addresses are already
verified by Trigger.
except IOError, reason:
print '\nError! Reason: ' + str(reason) + '.\n'
print 'Please check the file(s) and paths. Redirecting back to
prompt...\n'
#End Of Program
Page 92 of 185
93 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
To allow remote access to your Arista EOS device, you must enter the configuration
below.
Please enter Global Configuration mode (#configure terminal) before making this
configuration.
Note! I used this configuration on Arista vEOS VM, Software Version 4.13.14M.
IP Configuration:
enable
configure
interface Management 1
no shutdown
SSHv2 Configuration:
management ssh
idle-timeout 0
Page 93 of 185
94 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
server-port 22
no fips restrictions
no shutdown
log-level info
management telnet
no shutdown
idle-timeout 0
SNMP Configuration:
Checking Configuration:
show snmp
Saving Configuration:
Page 94 of 185
95 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
#Using a while loop to allow the user to return and choose another cXdY
combination.
while True:
#Asking the user about the output he wants to obtain.
print '\nNOTE! The format is always cXdY, where X is the command
number and Y is the device number in the lists you enter.\nIf X = a this
means that command Y will be executed on ALL devices.\nIf Y = a this means
that all commands will be executed on device X.\nIf both X = a and Y = a
then all the commands will be executed on all devices.'
Page 95 of 185
96 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Now if the user types 'cada' for example, meaning execute all
commands on all devices.
elif user_option_1[1] == 'a' and user_option_1[3] == 'a':
all_outputs_list = []
for device in devices_list:
for command in commands_list:
all_outputs_list.append('Device: ' + device + ' -
Command #' + str(commands_list.index(command) + 1) + ':\n\n' +
cmd.results[device][command])
final_result = '\r\n'.join(all_outputs_list)
Page 96 of 185
97 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
if back == 'y':
continue
else:
break
if back == 'y':
continue
else:
break
#End Of Program
Page 97 of 185
98 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
#Running all commands from all the given files on all given devices.
cmd = CommandRunner(devices = devices_list, files = cmd_files_list)
#Raise exception in case one file does not exist. IP addresses are already
verified by Trigger.
except IOError, reason:
print '\nError! Reason: ' + str(reason) + '.\n'
print 'Please check the file(s) and paths. Redirecting back to
prompt...\n'
#End Of Program
Page 98 of 185
99 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
To allow remote access to your HP ProCurve device, you must enter the configuration
below.
Please enter Global Configuration mode (#configure terminal) before making this
configuration.
IP Configuration:
enable
configure
vlan 1
SSHv2 Configuration:
ip ssh version 2
Page 99 of 185
100 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
SNMP Configuration:
Checking Configuration:
show ip
show ip ssh
show snmp-server
Saving Configuration:
write memory
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
#User menu
print '\nPlease choose an action:\n\n1 - Read command output from a single
device\n2 - Read command output from multiple devices\n'
print '\n'
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
if user_choice == '1':
print session_output
if user_choice == '1':
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'hp_procurve', ip
= ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'hp_procurve', ip
= ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
#End of Program
#User menu
print '\nMake sure you have an username and password and SSHv2 enabled on
the device(s)'
print '\n'
session_output = session.send_config_set(commands.split(','))
print '\n'
for ip in ip.split(','):
session_output = session.send_config_set(commands.split(','))
print '\n'
session_output = session.send_config_from_file(commands_file)
print '\n'
for ip in ip.split(','):
session_output = session.send_config_from_file(commands_file)
else:
print "\nInvalid input. Exiting...\n"
sys.exit()
#End of Program
To allow remote access to your Avaya ERS device, you must enter the configuration
below.
Telnet access is enabled by default. In this section, we will use Telnet instead of SSH to
access the switch.
Please enter Global Configuration mode (#configure terminal) before making this
configuration.
Note! I used this configuration on an Avaya ERS 3526T-PWR+ switch, Software Version
5.3.1.
IP Configuration:
enable
configure terminal
Telnet/SSHv2 Configuration:
ssh [OPTIONAL]
SNMP Configuration:
snmp-server enable
Checking Configuration:
show ip
show ssh
show snmp-server
Saving Configuration:
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
Below you can find the full documentation and code for the AvayaERSConnect module.
The AvayaERSConnect Python module is built using Python 2.7.3, on top of the telnetlib
library and it works with any version of Python >= 2.7.x. Other versions below 2.7.x were
not tested.
https://docs.python.org/2/library/telnetlib.html
AvayaERSConnects main purpose is to connect to any Avaya ERS Device via Telnet
and perform various administration operations easily, without the need to write any
Python code at all.
- IP connectivity from the host / virtual machine to the Avaya ERS device(s)
Default Avaya credentials for read and write via Telnet are: username: RW ,
password: securepasswd
ReadConfig()
The ReadConfig() function in AvayaERSConnect is responsible for connecting to an
Avaya device via Telnet, sending a show command that the user specifies as an
argument and capturing and storing the output of that command. This command should
be invoked in the Python interpreter, after importing the AvayaERSConfig module.
The format:
Note: Please follow the exact order of arguments (as shown above) when calling the
function!
Example:
- The first argument is the IP address of the device you want to read from, in
between double quotes.
- The second argument is the Telnet username for logging into the device.
This will be RW if you leave it at default. cli password telnet local should be
configured on the device, prior to running the ReadConfig() function.
- The third argument is the Telnet password for logging into the device. This
will be securepasswd if you leave it at default. cli password telnet local
should be configured on the device, prior to running the ReadConfig() function.
- The fourth argument is the show command you want to send to the device.
- The to_screen argument can be set to either True or False. When set to
True, the command output is printed on the screen, in the Python interpreter.
- If both to_file and to_screen are set to True, the output will be both stored
in an external file and printed to the screen. If both are set to False, nothing
happens.
- If you set to_file = True, then the output of the show command is stored
inside a file in the current directory, which is going to be automatically named
following this format: Hostname_Command.txt. This is useful when querying
multiple devices, one by one.
Example:
SendConfig()
The SendConfig() function in AvayaERSConnect is responsible for connecting to an
Avaya device via Telnet, sending configuration commands stored in an external text file,
each specified one per line. In the function call, you can also specify whether you want
the configuration you just made to be saved to the devices NVRAM. This command
should be invoked in the Python interpreter, after importing the AvayaERSConfig module.
The format:
Note: Please follow the exact order of arguments (as shown above) when calling the
function!
Example:
SwitchOne(config)#show vlan
Total VLANs: 1
SwitchOne(config)#show vlan
Total VLANs: 4
- The first argument is the IP address of the device you want to write
commands to, in between double quotes.
- The third argument is the Telnet username for logging into the device. This
will be RW if you leave it at default. cli password telnet local should be
configured on the device, prior to running the SendConfig() function.
- The fourth argument is the Telnet password for logging into the device. This
will be securepasswd if you leave it at default. cli password telnet local
should be configured on the device, prior to running the SendConfig() function.
SendConfigToMultiDev()
This function uses threading for initiating multiple concurrent sessions to multiple Avaya
ERS IP addresses, specified inside an external, dedicated file.
The format:
Note: Please follow the exact order of arguments (as shown above) when calling the
function!
Example:
Lets consider three Avaya ERS 35xx switches [IPs: 10.105.62.23, 10.105.62.24,
10.105.62.25]:
2.3#show vlan
Total VLANs: 1
2.4#show vlan
Total VLANs: 1
2.5#show vlan
Total VLANs: 1
Lets create the files we need: one holding the IP addresses and one holding the
commands.
10.105.62.23
10.105.62.24
10.105.62.25
Checking IP reachability...
Lets verify the configuration on the three switches - vlans 77, 88, 99 should have been
configured.
2.3#show vlan
Total VLANs: 4
2.4#show vlan
Total VLANs: 4
2.5#show vlan
Total VLANs: 4
- The first argument is the Telnet username for logging into the device. This
will be RW if you leave it at default. cli password telnet local should be
configured on the device, prior to running the SendConfigToMultiDev() function.
- The second argument is the Telnet password for logging into the device.
This will be securepasswd if you leave it at default. cli password telnet local
should be configured on the device, prior to running the SendConfigToMultiDev()
Page 120 of 185
121 Python Network Programming Course Applications Guide by Mihai Ctlin Teodosiu
function.
Note: Other functions in the AvayaERSConnect.py file take care of checking IP format
validity, IP reachability and commands file path corectness. These functions are not to be
used directly in the Python interpreter.
#!/usr/bin/env python
###AVAYA TELNETTING###
while True:
#Prompting user for input
ip_file = raw_input("Enter IP file name and extension: ")
except IOError:
print "\nFile %s does not exist! Please check and try
again!\n" % ip_file
#Checking octets
for ip in ip_list:
a = ip.split('.')
else:
print '\n* There was an INVALID IP address! Please check
and try again!\n'
check = False
continue
#Checking IP reachability
print "\nChecking IP reachability...\n"
check2 = False
while True:
for ip in ip_list:
ping_reply = subprocess.call(['ping', '-c', '3', '-w', '3', '-
q', '-n', ip], stdout = subprocess.PIPE)
if ping_reply == 0:
check2 = True
continue
elif ping_reply == 2:
print "\nNo response from device %s." % ip
check2 = False
break
else:
print "\nPing to the following device has FAILED:", ip
check2 = False
break
def CommandFileExists():
global cmd_file
while True:
cmd_file = raw_input("Enter command file name and extension: ")
else:
print "\nFile %s does not exist! Please check and try
again!\n" % cmd_file
continue
###DEBUG CODE
#print ip
#print username
#print password
###DEBUG CODE
#print to_file
#print to_screen
#print router_output
#Getting device hostname from output, for naming the file to which
to save the output
hostname_regex = re.search(r"(.+?)#show ", router_output)
hostname = hostname_regex.group(1)
###DEBUG CODE
#print hostname_regex
#print hostname
except IOError:
print "\nInput parameter error! Please check destination IP,
username and password.\n"
sys.exit()
except AttributeError:
print "\nInput parameter error! Please check destination IP,
username and password.\n"
sys.exit()
except KeyboardInterrupt:
print "\nProgram aborted by user. Exiting...\n"
sys.exit()
###DEBUG CODE
#print ip
#print username
#print password
else:
pass
connection.write("configure terminal\n")
time.sleep(1)
else:
print "\nFile %s does not exist! Please check filename or path
and try again.\n" % cmd_file
sys.exit()
###DEBUG CODE
#Test for reading command output
#router_output = connection.read_very_eager()
#print router_output
if save_config == True:
#Saving the config to NVRAM
connection.write("\n")
connection.write("copy config nvram\n")
time.sleep(5)
print "\nConfiguration was saved to NVRAM.\n"
except IOError:
print "\nInput parameter error! Please check destination IP,
username and password.\n"
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
#Creating threads
def SendConfigToMultiDev(username, password, save_config = True):
IpIsValidReach()
CommandFileExists()
threads = []
for ip in ip_list:
th = threading.Thread(target = SendConfig, args = (ip, cmd_file,
username, password, save_config)) #'args' is a tuple
th.start()
threads.append(th)
for th in threads:
th.join()
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
except KeyboardInterrupt:
print "\n\nProgram aborted by user. Exiting...\n"
sys.exit()
#End of program
#User menu
print '\nPlease choose an action:\n\n1 - Read command output from a
device\n2 - Send config commands from a file to a device\n3 - Send config
commands from a file to multiple devices\n'
if save == 'y':
to_file = True
if screen == 'y':
to_screen = True
print '\n'
if save == 'y':
save_config = True
print '\n'
if save == 'y':
save_config = True
print '\n'
#End Of Program
To allow remote access to your Cisco IOS XE device, you must enter the configuration
below.
Please note that some versions of Cisco IOS XE do not support SSH, so you should
make sure you have a SSH-compatible IOS XE version. According to cisco.com: "The
Cisco IOS image used must be a k9(crypto) image in order to support SSH. For example
c3750e-universalk9-tar.122-35.SE5.tar is a k9 (crypto) image."
Here is the configuration you have to make in order to allow remote access. Please enter
Global Configuration mode (#configure terminal) before pasting this configuration.
IP Configuration:
enable
configure terminal
interface GigabitEthernet 1
no shutdown
SSHv2 Configuration:
hostname IOS-XE
line vty 0 4
privilege level 15
login local
exit
ip domain-name mihai
ip ssh version 2
ip ssh time-out 60
ip ssh authentication-retries 3
!When asked How many bits in the modulus [512]: enter 1024
1024
SNMP Configuration:
Checking Configuration:
show ip ssh
show snmp
Saving Configuration:
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
#User menu
print '\nPlease choose an action:\n\n1 - Read command output from a single
device\n2 - Read command output from multiple devices\n'
print '\n'
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
if user_choice == '1':
print session_output
if user_choice == '1':
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'cisco_xe', ip =
ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'cisco_xe', ip =
ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
#End of Program
#User menu
print '\nMake sure you have an username and password and SSHv2 enabled on
the device(s)'
print '\n'
session_output = session.send_config_set(commands.split(','))
print '\n'
for ip in ip.split(','):
session_output = session.send_config_set(commands.split(','))
print '\n'
session_output = session.send_config_from_file(commands_file)
print '\n'
for ip in ip.split(','):
session_output = session.send_config_from_file(commands_file)
else:
print "\nInvalid input. Exiting...\n"
sys.exit()
#End of Program
To allow remote access to your Cisco IOS XR device, you must enter the configuration
below.
Please note that some versions of Cisco IOS XR do not support SSH, so you should
make sure you have a SSH-compatible IOS XR version. According to cisco.com: "The
Cisco IOS image used must be a k9(crypto) image in order to support SSH. For example
c3750e-universalk9-tar.122-35.SE5.tar is a k9 (crypto) image."
Please note that when using the Cisco IOS XR VM (Cisco IOS XRv), you set
the username and password after the first boot, at an interactive prompt. That prompt is
where you should enter your remote login credentials, the ones to use when connecting
via SSHv2 (username: mihai , password: python - as used throughout this course, or
your own credentials).
Here is the configuration you have to make in order to allow remote access. Please enter
Global Configuration mode (#configure terminal) before pasting this configuration.
IP Configuration:
enable
configure terminal
no shutdown
SSHv2 Configuration:
hostname IOS-XR
line console
exit
ssh server v2
1024
SNMP Configuration:
Checking Configuration:
show ip ssh
show snmp
Saving Configuration:
RP/0/0/CPU0:IOS-XR(config)#commit
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
#User menu
print '\nPlease choose an action:\n\n1 - Read command output from a single
device\n2 - Read command output from multiple devices\n'
print '\n'
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
if user_choice == '1':
print session_output
if user_choice == '1':
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'cisco_xr', ip =
ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
for ip in dev_list:
#Running the code for each device specified by the user
session = ConnectHandler(device_type = 'cisco_xr', ip =
ip, username = username, password = password)
time.sleep(1)
session_output = session.send_command(command)
time.sleep(1)
#End of Program
#User menu
print '\nMake sure you have an username and password and SSHv2 enabled on
the device(s)'
print '\n'
session_output = session.send_config_set(commands.split(','))
print '\n'
for ip in ip.split(','):
session_output = session.send_config_set(commands.split(','))
print '\n'
session_output = session.send_config_from_file(commands_file)
print '\n'
for ip in ip.split(','):
session_output = session.send_config_from_file(commands_file)
else:
print "\nInvalid input. Exiting...\n"
sys.exit()
#End of Program
To allow remote access to your Netscreen device, you must enter the configuration below.
IP Configuration:
SSHv2 Configuration:
SNMP Configuration:
Checking Configuration:
get interface
get ssh
get snmp
Saving Configuration:
save
Note! Depending on the hardware and software you are using in your network, some
commands, command options or command outputs may be slightly different.
#Using a while loop to allow the user to return and choose another cXdY
combination.
while True:
#Asking the user about the output he wants to obtain.
print '\nNOTE! The format is always cXdY, where X is the command
number and Y is the device number in the lists you enter.\nIf X = a this
means that command Y will be executed on ALL devices.\nIf Y = a this means
that all commands will be executed on device X.\nIf both X = a and Y = a
then all the commands will be executed on all devices.'
#Now if the user types 'cada' for example, meaning execute all
commands on all devices.
elif user_option_1[1] == 'a' and user_option_1[3] == 'a':
all_outputs_list = []
for device in devices_list:
for command in commands_list:
if back == 'y':
continue
else:
break
if back == 'y':
continue
else:
break
#End Of Program
#Running all commands from all the given files on all given devices.
cmd = CommandRunner(devices = devices_list, files = cmd_files_list)
#Raise exception in case one file does not exist. IP addresses are already
verified by Trigger.
except IOError, reason:
print '\nError! Reason: ' + str(reason) + '.\n'
print 'Please check the file(s) and paths. Redirecting back to
prompt...\n'
#End Of Program
while True:
#User input
print '\nChoose the SNMP operation you want to perform on %s:\n\n1 -
SNMP GET\n2 - SNMP SET\n3 - SNMP WALK\ne - Exit program' % oid
if user_choice == '1':
#Performing SNMP GET
snmp_get = session.get(oid)
continue
continue
snmp_walk = session.walk(oid)
continue
break
else:
print '\nInvalid input. Exiting...\n'
break
#End Of Program
#Iterating over the files and capturing the interfaces and their ip
addresses.
for cfg_file in cfg_files:
parse = CiscoConfParse("/tftpboot/" + cfg_file)
obj = parse.find_objects_w_parents(r'interface ', r'ip address')
print '\n\n' + cfg_file + '\n'
for interface in obj:
print interface.geneology_text[0] + ': ' +
interface.geneology_text[1]
#End Of Program
#Defining the function for extracting the running config and building the
diff_file, report and master_report files.
def diff_function(device_type, vendor, username, password, command):
#Opening the old config file, the new config file for reading and a
new file to write the differences.
#Opening the new file, reading each line and creating a list where
each element is a line in the file.
with open(str(diff_file_date), 'r') as diff_file:
#Creating the list of lines.
diff_list = diff_file.readlines()
#print diff_list
except IndexError:
pass
if len(report_file.readlines()) < 1:
#Adding device as first line in report.
master_report.write('\n\n*** Device: ' + each_device + '
***\n')
master_report.write('\n' + 'No Configuration Changes
Recorded On ' + datetime.datetime.now().isoformat() + '\n\n\n')
else:
#Appending the content to the master report file.
report_file.seek(0)
master_report.write('\n\n*** Device: ' + each_device + '
***\n\n')
master_report.write(report_file.read())
else:
print '\nThis device type is not supported, sorry!\n'
#Checking whether any changes were recorded and building the email body.
with open('cfgfiles/master_report_' + datetime.date.today().isoformat() +
'.txt', 'r') as master_report:
master_report.seek(0)
body = '\n' + master_report.read() + '\n****************\n\nReport
Generated: ' + datetime.datetime.now().isoformat() + '\n\nEnd Of Report\n'
msg.attach(MIMEText(body, 'plain'))
#End Of Program
Note! Assuming you have Python and Scapy already installed on your Linux system, you
can easily perform the following attacks and operations on a specified target, using the
code provided below.
Disclaimer
The information inside this document is provided for educational purposes only and it is
not intended to be put into practice unless you have authorized access to the systems
you are trying sniff, scan, ping or perform any other action presented in this course on.
Any actions and/or activities related to the material contained within this document is
solely your responsibility. All the activities inside this document should be performed only
on authorized isolated, test/lab environments.
Do not use the information and scripts inside this document in a real, production network!
The misuse of the information in this document can result in criminal charges brought
against the persons in question.
The author will not be held responsible in the event any criminal charges be brought
against any individuals misusing the information in this document to break the law.
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#To see the list of optional arguments for the sniff() function:
'''
>>> print sniff.__doc__
Sniff packets
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
#ans.show()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
ans.summary(lambda(s, r) : r.sprintf("%IP.src% --> ICMP:%ICMP.type% -->
TCP:%TCP.flags%"))
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
#ans.summary()
ans.summary(lambda(s, r) : r.sprintf("%IP.src%"))
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
'''
An attacker uses a SYN scan to determine the status of ports on the remote
target.
RFC 793 defines the required behavior of any TCP/IP device in that an
incoming connection request begins with a SYN packet, which in turn must
be followed by a SYN/ACK packet from the receiving service.
When a SYN is sent to an open port and unfiltered port, a SYN/ACK will be
generated.
Source: https://capec.mitre.org/data/definitions/287.html
'''
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
'''
An attacker uses TCP ACK segments to gather information about firewall or
ACL configuration.
When RSTs are received in response, the ports are marked as unfiltered, as
the ACK packets solicited the expected behavior from a port.
Source: https://capec.mitre.org/data/definitions/305.html
'''
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
'''
An attacker uses a TCP FIN scan to determine if ports are closed on the
target machine. This scan type is accomplished by sending TCP segments
with the FIN bit set in the packet header. The RFC 793 expected behavior
is that any TCP segment with an out-of-state Flag sent to an open port is
discarded, whereas segments with out-of-state flags sent to closed ports
should be handled with a RST in response.
Many operating systems, however, do not implement RFC 793 exactly and for
this reason FIN scans do not work as expected against these devices. Some
Source: https://capec.mitre.org/data/definitions/302.html
'''
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
'''
An attacker uses a TCP XMAS scan to determine if ports are closed on the
target machine. This scan type is accomplished by sending TCP segments
with the all flags sent in the packet header, generating packets that are
illegal based on RFC 793. The RFC 793 expected behavior is that any TCP
segment with an out-of-state Flag sent to an open port is discarded,
whereas segments with out-of-state flags sent to closed ports should be
handled with a RST in response.
Many operating systems, however, do not implement RFC 793 exactly and for
this reason FIN scans do not work as expected against these devices. Some
operating systems, like Microsoft Windows, send a RST packet in response
to any out-of-sync (or malformed) TCP segments received by a listening
socket (rather than dropping the packet via RFC 793), thus preventing an
attacker from distinguishing between open and closed ports.
Source: https://capec.mitre.org/data/definitions/303.html
'''
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
'''
An attacker uses a TCP NULL scan to determine if ports are closed on the
target machine. This scan type is accomplished by sending TCP segments
with no flags in the packet header, generating packets that are illegal
based on RFC 793. The RFC 793 expected behavior is that any TCP segment
with an out-of-state Flag sent to an open port is discarded, whereas
segments with out-of-state flags sent to closed ports should be handled
with a RST in response. This behavior should allow an attacker to scan for
closed ports by sending certain types of rule-breaking packets (out of
sync or disallowed by the TCB) and detect closed ports via RST packets.
Many operating systems, however, do not implement RFC 793 exactly and for
this reason NULL scans do not work as expected against these devices. Some
operating systems, like Microsoft Windows, send a RST packet in response
to any out-of-sync (or malformed) TCP segments received by a listening
socket (rather than dropping the packet via RFC 793), thus preventing an
attacker from distinguishing between open and closed ports.
Source: https://capec.mitre.org/data/definitions/304.html
'''
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
try:
from scapy.all import *
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
ans.summary(lambda(s,r): r.sprintf("%IP.src% is UP!"))
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
ans.summary(lambda(s,r): r.sprintf("%IP.src% is UP!"))
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#The results
ans.summary(lambda(s,r): r.sprintf("%IP.src% is UP!"))
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
def arp_monitor(packet):
if ARP in packet and packet[ARP].op == 1: #ARP Request (who-has
...?)
return "ARP Request: Device " + packet[ARP].psrc + " asking
about: " + packet[ARP].pdst
elif ARP in packet and packet[ARP].op == 2: #ARP Reply (is-at ...)
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#Scapy normally makes sure that replies come from the same IP address the
stimulus was sent to.
#But our DHCP packet is sent to the IP broadcast address (255.255.255.255)
and any answer packet will have the IP address of the replying DHCP server
as its source IP address (e.g. 192.168.1.111).
#Because these IP addresses don't match, we have to disable Scapy's check
with conf.checkIPaddr = False before sending the stimulus.
conf.checkIPaddr = False
#The IP offered by the DHCP server to the client is extracted from the
received answer (OFFER)
offered_ip = ans[0][1][BOOTP].yiaddr
except IndexError:
print "\nDone. No more addresses to steal! :)\n"
http://www.cisco.com/c/en/us/td/docs/ios-xml/ios/ipaddr_dhcp/configuration/12-4t/dhcp-
12-4t-book/config-dhcp-server.html
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#Scapy normally makes sure that replies come from the same IP address the
stimulus was sent to.
#But our DHCP packet is sent to the IP broadcast address (255.255.255.255)
and any answer packet will have the IP address of the replying DHCP server
as its source IP address (e.g. 192.168.1.111).
#Because these IP addresses don't match, we have to disable Scapy's check
with conf.checkIPaddr = False before sending the stimulus.
conf.checkIPaddr = False
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#Sending the Discover packet and accepting multiple answers for the same
Discover packet
ans, unans = srp(dhcp_discover, multi = True, iface = "enp0s3", timeout =
5, verbose = 0)
#!/usr/bin/env python
#This will suppress all messages that have a lower level of seriousness
than error messages.
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
except ImportError:
print "Scapy package for Python is not installed on your system."
print "Get it from https://pypi.python.org/pypi/scapy and try again."
sys.exit()
#Defining the destination names/IPs and ports and the exiting interface
targets = ['172.16.1.2', '172.16.1.3', '172.16.1.150', '172.16.1.100']
ports = [50743, 111, 135, 22]
interface = "enp0s3"
return open_ports
if len(open_ports) > 0:
pkt = sr1(IP(dst = target) / TCP(dport =
open_ports[0], flags = "S"), timeout = 2, iface = interface, verbose = 0)
ttl = str(pkt[IP].ttl)
window = str(pkt[TCP].window)
#print ttl, window
I really hope you found this course application guide useful for your networking needs
and, again, thank you for purchasing my Python Network Programming course series!
To stay updated with the latest news and courses in the networking and network
programming world, you have several options:
Follow me on Twitter:
https://twitter.com/MihaiCTeodosiu
and/or:
https://www.linkedin.com/groups/8313392
and/or:
https://www.youtube.com/c/MihaiCatalinTeodosiu
and/or:
http://trendelearning.com/wp/homepage/subscribe/
Have no fear, Im not going to spam you with junk e-mails. If I have great content to share
or a huge special offer for my courses, I will send it your way. Otherwise, you wont hear
from me just for the sake of it.
Best regards!