Category Archives: 9. Software Defined Network

Iperf with Python

WIP:Iperf with Python

## ACR – IPERF Project
import base64, time, sys
import paramiko, getpass, telnetlib

## List of server
lperfrip = [‘192.168.46.1′,’192.168.48.1’]
lperfloc = [‘Japan’,’Philippines’]

titles = [‘Remote IP’, ‘Location’]
data = [titles] + list(zip(lperfrip, lperfloc))

for i, d in enumerate(data):
line = ‘|’.join(str(x).ljust(14) for x in d)
print(line)
if i == 0:
print(‘-‘ * len(line))

## Select server
mtcp = “TCP”
testlat = []
ipsvr = input(“\nEnter Iperf Server IP: “)
ipclnt = input(“\nEnter Iperf Client IP: “)
suser = input(“Login acct: “)
spass = input(“password: “)
perfport = input(“Select port[5000-10]: “)
testbw = int(input(“CIR: “))
testop = input(“Select[TCP/UDP]: “)
if testop in mtcp:
ttestlat = int(input(“Latency: “))
testlat.append(ttestlat)
## Calculate BDP
mtk = (testbw * 1000)
print(“Kbps: “, mtk)
bdp = int(mtk * ttestlat / 8)
print (“BDP: “,bdp)
for sshsvrip in ipsvr:
sshrip = sshsvrip.strip()
print(“Processing …..”,sshrip)
psvrcmd = (“iperf3 -s -p “,perfport,” -i 2 -B “, ipsvr)
stripscmd = [test1.strip() for test1 in psvrcmd]
strpcmd = ‘ ‘.join(stripscmd)
print (“# # COMMAND:”, strpcmd)

## Test SSH
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ipsvr, username=suser, password=spass)
stdin, stdout, stderr = client.exec_command(strpcmd)

## for line in stdout:
## print(‘\nResult: ‘ + line.strip(‘\n’))
## client.close()

## IPERF CLIENT
## print (“PROCESSING CLIENT SCRIPT”)
for sshclntip in ipsvr:
sshcrip = sshclntip.strip()
print(“Processing …..”,sshcrip)
## psvrcmd = (“iperf3 -s -p “,perfport,” -i 2 -B “, ipsvr)
## stripscmd = [test1.strip() for test1 in psvrcmd]
## strpcmd = ‘ ‘.join(stripscmd)
## print (“# # COMMAND:”, strpcmd)

## Test SSH
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ipclnt, username=suser, password=spass)
stdin, stdout, stderr = client.exec_command(“iperf3 -c 192.168.46.1 -t 5”)

for line in stdout:
print(‘\nResult: ‘ + line.strip(‘\n’))
client.close()

else:
print(“Exit”)
print(testlat)

## Test SSH
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ipsvr, username=suser, password=spass)
stdin, stdout, stderr = client.exec_command(‘pwd’)

for line in stdout:
print(‘\nResult: ‘ + line.strip(‘\n’))
client.close()

Python Telnet & SSH

import getpass
import sys
import telnetlib

HOST = "hostname"

user = raw_input("Enter your remote account: ")

password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")

tn.write(user + "\n")

if password:
tn.read_until("Password: ")
tn.write(password + "\n")

tn.write("ls\n")

tn.write("exit\n")

print tn.read_all()
ssh: link

import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password)
s.sendline ('uptime') # run a command
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.sendline ('ls -l')
s.prompt()
print s.before
s.sendline ('df')
s.prompt()
print s.before
s.logout()
except pxssh.ExceptionPxssh, e:
print "pxssh failed on login."
print str(e)

https://stackoverflow.com/questions/28295501/ssh-and-telnet-to-localhost-using-python

Python: Show ip bgp & regex

Simple way to pullout the Network, Peer AS and origin AS using regex.

Here’s the pattern:

#SEARCH NETWORK ENTRY
npat = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',teststr)

## Search Peer AS
ppat = re.findall("(?<=3491)\\s+(?:\\d{1,6})",teststr)
##print ("\n Peer AS: \n",ppat)

## Search Origin AS
opat = re.findall("(?:\\d{1,6})\\s+(?=i)",teststr)
##print ("\n Origin AS: \n",opat)

A. Prefix entry validation on RADB(Internet Routing Registry) and to Level3 filtergen system.


# ACR - IRR FILTERING VERIFICATION v1
import re, base64, os, sys, subprocess, csv
##def main():

####OPEN BGP TXT
fname = r"bgp.txt"
file = open(fname,'r')
teststr = file.read()
##print ("SHOW IP BGP\n",teststr)

#SEARCH NETWORK ENTRY
npat = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',teststr)
#print ("List: \n",npat)

## Search Peer AS
ppat = re.findall("(?<=3491)\\s+(?:\\d{1,6})",teststr)
##print ("\n Peer AS: \n",ppat)

## Search Origin AS
opat = re.findall("(?:\\d{1,6})\\s+(?=i)",teststr)
##print ("\n Origin AS: \n",opat)

# FINAL LIST FILTERGEN / WHOIS / PEERAS / ROUTESET
flist = []
rlist = []
palist = []
rslist = []
oalist = []
rdboa = []

#### !! 1. Loop AS-SET RS-SET !!
## Check Peer AS, Origin AS and Network From PCCW AS-SET/RS-SET

for x in ppat:
pas = x.strip()
print ("Processing PAS..... ", pas)
# Finding PEER AS in AS-SET
gpas = os.popen("grep " +pas+ " /mnt/hgfs/IRR/RADB/asxxxx-customers-*").readlines()
## gpas = "grep " +pas+ " /mnt/hgfs/IRR/RADB/as3491-customers-*"

strpgpas = [test2.strip() for test2 in gpas]
sgpas = ''.join(strpgpas)
print ("From AS-SET: ", sgpas)

repas = re.findall("(?<=members:\s{4})AS\\d{1,6}",sgpas)
srepas = ''.join(repas)
fpas = re.sub('AS',"",srepas)
print ("Match from Grep PAS: ",fpas)
## print ("\n Match from GPAS: ",fpas)
if pas in fpas:
## palist.append(fpas)
palist.append("PAS Found")
else:
palist.append("PAS Not found")

#### !! 2. Loop Origin AS !!
for y in opat:
oas = y.strip()
print ("Processing OAS..... ", oas)
## Finding Origin AS in AS-set
goas = os.popen("grep " +oas+ " /mnt/hgfs/IRR/RADB/as3491-customers-*").readlines()
strpoas = [test4.strip() for test4 in goas]
soas = ''.join(strpoas)
## print ("From AS-SET: ", soas)
roas = re.sub("AS", "", soas)
sroas = ''.join(roas)
print ("From AS-SET: ",sroas)

if oas in str(sroas):
## oalist.append(oas)
oalist.append("OAS Found")
else:
oalist.append("OAS Not found")

#### !! 3. Loop Filtergen ad Whois !!
for ips in npat:
ipnet = ips.strip()
print ("Processing Net..... ", ipnet)

## Finding on RS-SET
rsgrep = os.popen("grep " +ipnet+ " /mnt/hgfs/IRR/RADB/rs-as3491").readlines()
stripnet = [test3.strip() for test3 in rsgrep]
strnet = ''.join(stripnet)
rspat = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',strnet)
print ("From RS-SET: ",rspat)

if ipnet in rspat:
rslist.append("PFX Found")
print ("RS-SET result: ", rslist)
else:
rslist.append("PFX Not Found")
print ("RS-SET result: ",rslist)

## Finding network on Level3 Filtergen TXT
fgen = os.popen("grep " +ipnet+ " /mnt/hgfs/IRR/fgen.txt").readlines()
f2 = [test.strip() for test in fgen]
sf2 = str(f2)
print ("From Filtergen txt: ",sf2)
f2pat = re.findall(r'(?:[\d\.\/]+)',sf2)
## print ("\nMatch from Fgen output: ",f2pat)
if ipnet in f2pat:
flist.append("PFX Found")
print ("Filtergen result: ", flist)
else:
flist.append("PFX Not Found")
print ("Filtergen result: ",flist)

## Look for an Entry in RADB
f = os.popen('whois -h whois.radb.net ' + ipnet).readlines()
print ("\nPRINT F: ",f)
fs = [test1.strip() for test1 in f]
who = ''.join(fs)
print ("From RADB: ", who)
radb = re.findall('^route:.+\s(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+', who)
radbs = ''.join(radb)
radbpat = re.sub('route:.+\s', "", radbs)
## print ("\nMatch from Radb :",radbpat)
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',str(radbpat)):
rlist.append(radbpat)
print ("RADB result: ", rlist,"\n")
else:
rlist.append("No Entry")
print ("RADB result: ",rlist,"\n")

regoa = re.findall("(?<=origin:\s{5})([a-zA-Z]{2}\\d{1,6})", who)
strrdboa = ''.join(regoa)
frdboa = re.sub("AS", "", strrdboa)
print ("\n\n RADBOS: ",regoa)
print ("FRDBOA", frdboa)

if re.findall("(?<=origin:\s{5})([a-zA-Z]{2}\\d{1,6})", str(who)):
rdboa.append(frdboa)
else:
rdboa.append("No Entry")
## print ("RADB result: ",rlist,"\n")

print (npat, "\n", rslist, "\n", ppat, "\n", palist, "\n", opat, "\n", oalist, "\n", flist, "\n", rlist, "\n", rdboa)

## OUTPUT TABLE
titles = ['NETWORK', 'RS-SET', 'PEER-AS', 'AS-SET', 'ORIGIN AS', 'AS-SET', 'FILTERGEN', 'RADB', 'AS']
data = [titles] + list(zip(npat, rslist, ppat, palist, opat, oalist, flist, rlist, rdboa))

for i, d in enumerate(data):
line = '|'.join(str(x).ljust(14) for x in d)
print(line)
if i == 0:
print('-' * len(line))

##print ("\n",flist,"\n",rlist)

## EXPORT AS CSV
with open('irr.csv', 'w') as updatecsv:
write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
write.writerows([titles] + list(zip(npat, rslist, ppat, palist, opat, oalist, flist, rlist, rdboa)))
updatecsv.close()
print ("\n irr.csv file has been updated")

## Debug output
### WIP
#main()

Working on Python for Ipv4/v6 lookup

READ ME
This script use for searching available address to be allocated on our PE routers. No module need to install.

#ACR – Assigning V4/V6 verification
# v1

import ipaddress, getpass
import os, telnetlib, time

#Ask the ipaddress in CIDR format
ip = input(“Enter the IP/CIDR: “)
#ip = “x.x.x.x/30”
ape = input(“Enter the assinged PE router(hostname): “)
#print (ape)

#Enter Cred
user = input(“Enter your remote acct: “)
password=getpass.getpass(“Enter Your Password Here: “)

#Change Directory
os.chdir(“/rs/configs”)
print(“pwd=%s” % os.getcwd())

for i in ipaddress.IPv4Network(ip):
ilist = [str(i)]
slist = ilist[0].strip()
print (“\nFinding: “, slist)
# ia = ip[ilist].strip()
# print (ia)
cmd = “grep ” +(slist)+ ” *”
print (cmd)
os.system(cmd)

for dev in [ape]:
print (“\nNow accessing… “, dev)
HOST = dev.strip()
## print (HOST)
tn = telnetlib.Telnet(HOST, timeout = 5)
tn.read_until(b”username new-ACS : “)
tn.write(user.encode(“ascii”) + b”\n”)

if password:
tn.read_until(b”password: “)
tn.write(password.encode(“ascii”) + b”\n”)

command = “show ip route “+(ip)
# print (command)
tn.read_until(b”#”)
tn.write(((command)+ “\n”).encode(‘ascii’))
time.sleep(1)
tn.write(b”exit”+b”\n”)
# print (“P Start”)
## readoutput = tn.read_until(b”#”).decode(‘ascii’)
readoutput = tn.read_all().decode(‘ascii’)
print (10 * “-“, “FROM PE”, 10 * “-“,”\n”,readoutput)
## print (tn.read_all().decode(‘ascii’))

#### #### #### ##
## NEW SESSION ###
#### #### #### ##
tn = telnetlib.Telnet(“x.x.x.x”, timeout = 5)
tn.read_until(b”username new-ACS : “)
tn.write(user.encode(“ascii”) + b”\n”)
if password:
tn.read_until(b”password: “)
tn.write(password.encode(“ascii”) + b”\n”)
command = “show ip route “+(ip)
# print (command)
tn.read_until(b”#”)
tn.write(((command)+ “\n”).encode(‘ascii’))
time.sleep(1)
tn.write(b”exit”+b”\n”)
# print (“P Start”)
readoutput = tn.read_all().decode(‘ascii’)
# print (“P Start”)
print (10 * “-“, “FROM US REGION”, 10 * “-“,”\n”,readoutput)

tn.close()

# Work in progress – Haven’t add the ipv6.

https://stackoverflow.com/questions/1942160/python-3-create-a-list-of-possible-ip-addresses-from-a-cidr-notation

Change Hostname based on list

# Requirements you need to get the IP address of all network devices

import csv
import telnetlib
import getpass
import sys
import time

##from prettytable import PrettyTable
def main():

#open csv file, then put to variable csvfile.
with open(input(“Input the CSV filename: “)) as csvfile:
## with open(input(“Input the CSV filename: “)) as csvfile:
riphostCSV = csv.reader(csvfile, delimiter=’,’)

#Put the data as list from excel.
ipaddress = []
nhostname = []

#Action – Put the data from excel to variable[list]
for col in riphostCSV:
ipadr = col[0]
nhost = col[1]

ipaddress.append(ipadr)
nhostname.append(nhost)
print (nhostname)
# Loging Session
user = input(“Enter your username: “)
password=getpass.getpass(“Enter Your Password Here: “)

# Accessing the device
for i in range(0,len(ipaddress)):
print (“Now accessing the device: “,ipaddress[i])
dev = ipaddress[i].strip()
tn = telnetlib.Telnet(dev)
print(“Host: “,dev)
tn.read_until(b”Username:”)
tn.write(user.encode(“ascii”) + b”\n”)

print (“Hostname :”, nhostname[i])
if password:
tn.read_until(b”Password: “)
tn.write(password.encode(“ascii”) + b”\n”)
tn.write(b”conf t\r\n”)
time.sleep(2)
tn.write((“hostname ” + nhostname[i] + “\n”).encode(‘ascii’))
time.sleep(2)
tn.write(b”exit \n”)
tn.write(b”wr mem \n”)
tn.close()
##
## break
main()

Inventory Script

import pexpect, getpass, time, re, sys

help(re.search)

function search in module re:

search(pattern, string, flags=0)
Scan through string looking for a match to the pattern, returning
a Match object, or None if no match was found.

#OPEN List of Devices
f = open(“ipadd.txt”)

#OPEN COMMANDS AND PUT INTO LIST
commandFile = open(‘commands.txt’,’r’)
commands = [i for i in commandFile]

# ENTER CRED
user = input(“Enter your remote account: “)
password = getpass.getpass()

# LOOP
for line in f:
print (“\nNow accessing the device.. ” + line)
HOST = line.strip()
child = pexpect.spawn (‘telnet ‘+HOST)
child.expect (‘Username: ‘)
child.sendline (user)
child.expect (‘Password: ‘)
child.sendline (password)
for command in commands:
child.expect (‘#’)
child.sendline(command)
child.expect (‘#’)
## print(“LIST OF COMMAND: “,commands)
## print(“EXECUTED COMMAND: “,command)
time.sleep(1)
show = str(child.before)
## print(show)

# SEARCH
regexoutput2 = re.search(‘\d\d\.\d{3}\.\d{3}\.\d’,show)
regexoutput3 = re.search(‘hostname [a-z]\w*\.[a-z]\w*’,show)
regexoutput4 = re.search(‘C\d{4}’,show)
regexoutput = re.search(‘.*Version (.*?\)).*’,show)
regexoutput5 = re.search(‘ID\s\w*’,show)
regexoutput6 = re.search(‘License’,show)

if regexoutput2:
print (“MGMT IP:”, str(regexoutput2.group(0)))
if regexoutput3:
print (“Hostname:”,re.sub(“hostname “, “”, str(regexoutput3.group(0))))
if regexoutput4:
print (“Model:”, str(regexoutput4.group(0)))
if regexoutput:
print (“Version:”,re.sub(“Version “, “”,regexoutput.group(1)))
if regexoutput5:
print (“Serial #:”,re.sub(“ID “, “”,regexoutput5.group(0)))
if regexoutput6:
print (“License:”, str(regexoutput6.group(0)))
## else:
## print(“Licence: none”)