def proxied(self): """ Connects to the proxy server via netmiko library, then logs into the router via \ standard SSH """ proxy_name = self.device["proxy"] device_proxy = configuration.proxy(proxy_name) nm_proxy = { "host": device_proxy["address"], "username": device_proxy["username"], "password": device_proxy["password"], "device_type": device_proxy["type"], "global_delay_factor": 0.5, } nm_connect_proxied = ConnectHandler(**nm_proxy) nm_ssh_command = device_proxy["ssh_command"].format( **self.nm_host) + "\n" # Debug logger.debug(f"Netmiko proxy {proxy_name}:\n{nm_proxy}") logger.debug(f"Proxy SSH command: {nm_ssh_command}") # End Debug nm_connect_proxied.write_channel(nm_ssh_command) time.sleep(1) proxy_output = nm_connect_proxied.read_channel() logger.debug(f"Proxy output:\n{proxy_output}") try: # Accept SSH key warnings if "Are you sure you want to continue connecting" in proxy_output: logger.debug(f"Received OpenSSH key warning") nm_connect_proxied.write_channel("yes" + "\n") nm_connect_proxied.write_channel(self.nm_host["password"] + "\n") # Send password on prompt elif "assword" in proxy_output: logger.debug(f"Received password prompt") nm_connect_proxied.write_channel(self.nm_host["password"] + "\n") proxy_output += nm_connect_proxied.read_channel() # Reclassify netmiko connection as configured device type logger.debug( f'Redispatching netmiko with device class {self.nm_host["device_type"]}' ) redispatch(nm_connect_proxied, self.nm_host["device_type"]) response = nm_connect_proxied.send_command(self.command) status = codes["success"] logger.debug(f"Netmiko proxied response:\n{response}") except ( NetMikoAuthenticationException, NetMikoTimeoutException, NetmikoAuthError, NetmikoTimeoutError, ) as netmiko_exception: response = config["messages"]["general"] status = codes["danger"] logger.error( f'{netmiko_exception}, {status},Proxy: {self.nm_host["proxy"]}' ) nm_connect_proxied.disconnect() return response, status
def routing(): ios_r1 = { 'device_type': 'cisco_ios', 'username': '******', 'password': '******', 'ip': '192.168.100.1', } ios_r2 = { 'device_type': 'cisco_ios', 'username': '******', 'password': '******', 'ip': '192.168.200.2', } ios_r4 = { 'device_type': 'cisco_ios', 'username': '******', 'password': '******', 'ip': '172.16.100.1', } net_connect1 = ConnectHandler(**ios_r1) output = net_connect1.send_config_set( ["router ospf 1", "network 0.0.0.0 255.255.255.255 area 0"]) #print(output) print('\n') print('********* Routing enabled on: ios_r1') net_connect1.write_channel("ssh -l lab 192.168.200.2\n") time.sleep(1) output2 = net_connect1.read_channel() if "word" in output2: net_connect1.write_channel(net_connect1.password + '\n') time.sleep(1) net_connect1.write_channel("conf t\n") net_connect1.write_channel("router ospf 1\n") net_connect1.write_channel("network 0.0.0.0 255.255.255.255 area 0\n") net_connect1.write_channel("end\n") #print('\n') print('********* Routing enabled on: ios_r2') time.sleep(4) net_connect1.write_channel("ssh -l lab 172.16.100.1\n") time.sleep(4) output3 = net_connect1.read_channel() if "word" in output3: net_connect1.write_channel(net_connect1.password + '\n') net_connect1.write_channel("conf t\n") net_connect1.write_channel("router ospf 1\n") net_connect1.write_channel("network 0.0.0.0 255.255.255.255 area 0\n") net_connect1.write_channel("end\n") #print('\n') print('********* Routing enabled on: ios_r4')
def on(jumpserver, ip_addr, rsa_pwd): # Connect to jump box net_connect = ConnectHandler(**jumpserver) # Connect to the target device ssh_command = "ssh " + ip_addr # for TACACS account # ssh_command = "ssh " + local_user + "@" + ip_addr # for local account net_connect.write_channel(ssh_command) print(net_connect.find_prompt()) sleep(10) net_connect.write_channel(rsa_pwd + "\n") net_connect.read_channel() redispatch(net_connect, device_type='cisco_ios') return net_connect
def topology(ip): mininet = { 'device_type': 'linux', 'username': '******', 'password': '******', 'ip': ip, } net_connect2 = ConnectHandler(**mininet) #updating the default route on the Mininet VM net_connect2.write_channel( "echo mininet | sudo -S ip route del 0.0.0.0/0\n") time.sleep(1) net_connect2.write_channel( "echo mininet | sudo -S ip route add 0.0.0.0/0 dev eth0\n") time.sleep(1) #spinning the default mininet topology net_connect2.write_channel("sudo mn\n") time.sleep(1) output2 = net_connect2.read_channel() print(output2) if "word" in output2: net_connect2.write_channel("mininet\n") time.sleep(1) #changing the OpenFlow version net_connect2.write_channel( "sh ovs-vsctl set bridge s1 protocols=OpenFlow13\n") time.sleep(1) print("OpenFlow version changed to OpenFlow1.3") #setting the controller net_connect2.write_channel( "sh ovs-vsctl set-controller s1 tcp:10.20.30.2:6653\n") time.sleep(10) print("Controller on OVS changed to Ryu (10.20.30.2:6653)") z = net_connect2.send_command("sh ovs-vsctl show") reg1 = r'(?m)(?<=\bis_connected: ).*$' find1 = re.findall(reg1, z) #checking the connection to the controller if len(find1) > 0 and find1[0] == "true": net_connect2.write_channel("pingall\n") flag = 1 return flag else: flag = 0 return flag
def verify_controller_con(ip): mininet={ 'device_type':'linux', 'username':'******', 'password':'******', 'ip':ip, } conn=ConnectHandler(**mininet) #adding route default through eth0 in order for mininet vm to be able to connect to controller #delete if route exists conn.write_channel("echo mininet | sudo -S ip route del 0.0.0.0/0\n") time.sleep(1) #add it back conn.write_channel("echo mininet | sudo -S ip route add 0.0.0.0/0 dev eth0\n") time.sleep(1) #starting up default mininet topology conn.write_channel("sudo mn\n") time.sleep(1) output = conn.read_channel() #print(output) if "word" in output: conn.write_channel("mininet\n") time.sleep(1) #set openflow version conn.write_channel("sh ovs-vsctl set bridge s1 protocols=OpenFlow13\n") time.sleep(2) print("\n") print("******** OpenFlow version changed to --> 1.3\n") #set controller ip address and port number conn.write_channel("sh ovs-vsctl set-controller s1 tcp:10.20.30.2:6653\n") time.sleep(5) print("******** Controller configured!") #check controller connectivity output = conn.send_command("sh ovs-vsctl show") #search for is_connected string reg = r'(?m)(?<=\bis_connected: ).*$' match = re.findall(reg,output) #check if is_connected is set to true which indicates controller connectivity if len(match)>0 and match[0]=="true": return True else: return False
def remote_command(conn_dict, commands=[]): ssh = SSH(**conn_dict) prompt = ssh.find_prompt() print(prompt, end=" ") output = "" for cmd in commands: # print(cmd) ssh.write_channel(str(cmd) + "\n") time.sleep(1) output = ssh.read_channel() print(output, end="") ssh.disconnect()
def ssh_function(): device = ConnectHandler(**yourbox) print(device.find_prompt()) device.write_channel("ssh -l admin 192.168.1.167 \n") time.sleep(1) output = device.read_channel() print(output) if "Password: "******"YourCiscoRouter2Password\n")) time.sleep(1) print(device.send_command("sh ip int bri")) device.disconnect()
def send_command(host, port, tbr, command): ''' Takes a command as an argument runs the command and returns the output of that command. ''' console = { 'device_type': 'generic_termserver_telnet', 'ip': host, 'port': port } net_connect = ConnectHandler(**console) net_connect.write_channel(command + '\r') time.sleep(tbr) output = net_connect.read_channel() return output
def talk_to_router(dev_dict,rname,q): net_connect = ConnectHandler(**dev_dict) net_connect.read_channel() net_connect.write_channel('show ip interface brief\r\n') sleep(2) output1 = net_connect.read_channel() net_connect.write_channel('show ip interface brief\r\n') net_connect.read_channel() net_connect.write_channel('show arp\r\n') output2 = net_connect.read_channel() q.put((rname,output1,output2))
def make_connection(a_device): global main_logger try: net_connect = ConnectHandler(global_delay_factor=5, **a_device) output = net_connect.read_channel() main_logger.info(output) except ValueError as Va: main_logger.info(Va) main_logger.info("Not able to enter Versa Director CLI. please Check") exit() # net_connect.enable() time.sleep(5) main_logger.debug("{}: {}".format(net_connect.device_type, net_connect.find_prompt())) # print str(net_connect) + " connection opened" main_logger.debug(str(net_connect) + " connection opened") return net_connect
def sudo_mn(ip): mininet = { 'device_type': 'linux', 'username': '******', 'password': '******', 'ip': ip, } #connect to mininet vm conn = ConnectHandler(**mininet) #starting up default mininet topology conn.write_channel("echo mininet | sudo -S mn\n") time.sleep(1) output = conn.read_channel() print(output)
def ovs_config(ip): mininet = { 'device_type': 'linux', 'username': '******', 'password': '******', 'ip': ip, } conn = ConnectHandler(**mininet) #adding route default through eth0 in order for mininet vm to be able to connect to controller #delete if route exists conn.write_channel("echo mininet | sudo -S ip route del 0.0.0.0/0\n") time.sleep(1) #add it back conn.write_channel( "echo mininet | sudo -S ip route add 0.0.0.0/0 dev eth0\n") time.sleep(1) #starting up default mininet topology conn.write_channel("sudo mn\n") time.sleep(1) output = conn.read_channel() print(output) if "word" in output: conn.write_channel("mininet\n") time.sleep(2) #set openflow version conn.write_channel("sh ovs-vsctl set bridge s1 protocols=OpenFlow13\n") time.sleep(2) print("\n") print("******** OpenFlow version --> 1.3\n") #set controller ip address and port number conn.write_channel("sh ovs-vsctl set-controller s1 tcp:10.20.30.2:6653\n") time.sleep(5) print("******** Controller configured!")
class Terminal: def __init__(self): self.device = { 'device_type': 'terminal_server', 'ip': '10.10.10.11', 'username': '******', 'password': '******' } self.console = { 'fusion': '1', 'border1': '2', 'border2': '3', 'edge1': '4', 'edge2': '5' } self.net_connect = ConnectHandler(**self.device) def send_command(self, command, wait=2): c = command self.net_connect.write_channel(c) print "command issued : " + c time.sleep(2) print 'hitting enter' self.net_connect.write_channel('\r') print "waiting for " + str(wait) + " seconds" time.sleep(wait) print "Read from console " + self.net_connect.read_channel() time.sleep(2) def run_guest_shell_script(self, script): self.send_command('conf t') self.send_command('iox', 150) self.send_command('end') self.send_command('guestshell enable', 20) self.send_command('guestshell run bash', 10) self.send_command(script, 5) self.send_command('exit') self.send_command('conf t') self.send_command('no iox') def reset_switch(self, switch): console = str(self.console[switch]) time.sleep(2) print self.net_connect.read_channel() time.sleep(2) print "choosing option " + console self.send_command(console) print "hitting enter again" self.send_command('\r') print "entering device console" print "entering username" self.send_command('admin') print "entering password" self.send_command('credentials') print "entering enable mode " self.send_command('enable') print "running reset script" self.run_guest_shell_script('python reset.py') print "switch reloaded" def init_switch(self, switch): script = 'python ' + switch + '.py' print "reading from console " + self.net_connect.read_channel() time.sleep(2) #Please answer 'yes' or 'no'.\r\nWould you like to enter the initial configuration dialog? [yes/no]: self.send_command('no') #u'no\r\n\r\nWould you like to terminate autoinstall? [yes]: ' self.send_command('yes', 5) self.send_command('\r') self.send_command('en') self.run_guest_shell_script(script)
from netmiko import ConnectHandler import configparser import time site = '6305' config = configparser.RawConfigParser() config.read('settings.ini') iosUser = config['ROUTER']['user'] iosPass = config['ROUTER']['pass'] iosHost = config['ROUTER'][site] device = { 'device_type': 'cisco_ios', 'host': iosHost, 'username': iosUser, 'password': iosPass, 'global_delay_factor': 10 } print("Starting Router connection test") net_connect = ConnectHandler(**device) net_connect.write_channel('show run\n') time.sleep(5) showRun = net_connect.read_channel() #print(showRun) for entry in showRun.split('\n'): print(entry) net_connect.disconnect() print("ALL DONE")
from netmiko import ConnectHandler from getpass import getpass password = getpass() device = { "host": 'cisco4.lasthop.io', "username": '******', "password": password, "secret": password, "device_type": 'cisco_ios', "session_log": "my_output.txt", } net_connect = ConnectHandler(**device) print(net_connect.find_prompt()) print(net_connect.config_mode()) print(net_connect.exit_config_mode()) net_connect.enable() net_connect.write_channel("disable\n") net_connect.read_channel() output = net_connect.find_prompt() print(output) net_connect.secret = getpass() net_connect.enable() print(net_connect.find_prompt())
def nxos_provision(host, port, tbr, commands, hostname): ''' Provision nxos device using telnet for eve-ng. host: IP address of the EVE-NG server port: Telnet port given to the device tbr: Time Between Requests is how long to sleep between commands. commands: List of strings that are commands for the device. ''' console = { 'device_type': 'generic_termserver_telnet', 'ip': host, 'port': port } net_connect = ConnectHandler(**console) loading_stage1 = True loading_stage2 = True loading_stage3 = True # We wait for the device to present us with the # option to skip POAP - Power On Auto Provisioning print("{} - Stage 0 - Waiting for device to boot".format(hostname)) while loading_stage1: output = net_connect.read_channel() if 'skip' in output: net_connect.write_channel('skip\r') loading_stage1 = False elif 'loader >' in output: net_connect.write_channel('boot nxos.9.2.2.bin\r') elif 'switch#' in output or 'config)#' in output or 'login:'******'admin' and no password while loading_stage2: output = net_connect.read_channel() if 'login:'******'admin\r') time.sleep(tbr) net_connect.write_channel('\r') loading_stage2 = False elif '#' in output: loading_stage2 = False time.sleep(tbr) print("{} - Stage 2 - Logged in device. Sending commands".format(hostname)) # We wait for the login process to complete and then # iterate over all the commands provided and send them # one by one. while loading_stage3: output = net_connect.read_channel() net_connect.write_channel('\r') if 'switch#' in output: for command in commands: net_connect.write_channel(command + '\r') time.sleep(tbr) loading_stage3 = False elif 'config)#' in output: loading_stage3 = False time.sleep(tbr) print("{} - Stage 3 - Device configured.".format(hostname))
#for device in devices[7:9]: # net_connect = ConnectHandler(**device) # print(net_connect.find_prompt()) # net_connect.disconnect() devices[1]["secret"] = lab_password devices[1]["session_log"] = "my_output.txt" connectionHandle = ConnectHandler(**devices[1]) print("\nThe current prompt appears to be:" + connectionHandle.find_prompt()) print("\nNow entering config mode, prompt appears to be:") connectionHandle.config_mode() print(connectionHandle.find_prompt()) print("\nExiting config mode, prompt now:") connectionHandle.exit_config_mode() print(connectionHandle.find_prompt()) print("\nExit privileged exec mode, prompt now:") connectionHandle.write_channel("disable\n") time.sleep(2) print(connectionHandle.read_channel()) print("\nBack to enable mode, prompt now:") connectionHandle.enable() print(connectionHandle.find_prompt()) connectionHandle.disconnect()
This program helps troubleshooting netmiko by obtaining the logging file from the router and displaying it. http://ktbyers.github.io/netmiko/COMMON_ISSUES.html ''' from netmiko import ConnectHandler import time import logging logging.basicConfig(filename='test.log', level=logging.DEBUG) logger = logging.getLogger("netmiko") cisco_device = { 'device_type': 'cisco_ios', 'host': '10.1.1.10', 'username': '******', 'password': '******', 'port': 22, # optional, default 22 'secret': 'cisco', # this is the enable password 'verbose': True # optional, default False } connection = ConnectHandler(**cisco_device) output = connection.send_command('show version') print(output) connection.write_channel('show version\n') time.sleep(2) output = connection.read_channel() print(output) print('Closing connection') connection.disconnect()
from getpass import getpass import time password = getpass() device = { "host": "cisco4.lasthop.io", "username": "******", "password": password, "secret": password, "device_type": "cisco_ios", "session_log": "my_output.txt" } dev_connect = ConnectHandler(**device) print(dev_connect.find_prompt()) dev_connect.config_mode() print(dev_connect.find_prompt()) dev_connect.exit_config_mode() print(dev_connect.find_prompt()) dev_connect.write_channel("disable\n") time.sleep(2) print(dev_connect.read_channel()) dev_connect.enable() print(dev_connect.find_prompt()) dev_connect.disconnect()
"secret": '88newclass', "device_type": 'cisco_ios', "session_log":'my_cmd_logs.txt' } start_time = datetime.now() device = ConnectHandler(**net_device) print(device.find_prompt()) output = device.config_mode() print(device.find_prompt()) output = device.exit_config_mode() print(device.find_prompt()) print(device.write_channel('disable\n')) time.sleep(2) print(device.read_channel()) print(device.find_prompt()) print(device.enable()) print(device.find_prompt()) #pprint(output) device.disconnect() finish = datetime.now() dur = finish - start_time duration = dur.total_seconds() dur2 = "{:.2f}".format(duration) duration_str = str(dur2) print("This script took " + duration_str + "seconds to complete")
def main(): dev = { 'device_type': 'terminal_server', 'ip': sys.argv[1], 'username': '******', 'password': '******', 'port': 830 } cn_host_pass = '******' net_connect = ConnectHandler(**dev) net_connect.write_channel("\r\n") time.sleep(1) net_connect.write_channel("\r\n") time.sleep(1) output = net_connect.read_channel() print(output) # Login to end device from "terminal server" ... ">" expected first if 10x ver or ui if 18x ver if ">" in output: print("Found 10x \n") net_connect.write_channel("diag shell\r\n") time.sleep(1) # output = net_connect.read_channel() net_connect.write_channel("ssh cn_core_host\r\n") time.sleep(1) # output = net_connect.read_channel() # print(output) else: print("Found 18x \n") net_connect.write_channel("ssh cn_core_host\r\n") time.sleep(1) # output = net_connect.read_channel() # print(output) # Manually handle the Username and Password max_loops = 5 i = 1 while i <= max_loops: output = net_connect.read_channel() print(output) # Search for password pattern / send password if 'yes/no' in output: net_connect.write_channel('yes\r\n') time.sleep(.5) elif "password" in output: net_connect.write_channel(cn_host_pass + '\r\n') time.sleep(.5) output = net_connect.read_channel() # Did we successfully login if 'NFV-FRU:' in output: print(output) break net_connect.write_channel('\r\n') time.sleep(.5) i += 1 # Dynamically reset the class back to the proper Netmiko class print("Doing redispatch to dev type linux") redispatch(net_connect, device_type='linux') cmd = "sudo virsh list --all" # net_connect.send_command("sudo su") print("sending command") res = net_connect.send_command(cmd) print(res) net_connect.disconnect() return
"host": 'cisco4.lasthop.io', "username": '******', "password": password, "secret": password, "device_type": 'cisco_ios', "session_log": 'my_session2-6.txt', } # a net_connect = ConnectHandler(**device) print(net_connect.find_prompt()) # b net_connect.config_mode() print(net_connect.find_prompt()) # c net_connect.exit_config_mode() print(net_connect.find_prompt()) # d and e net_connect.write_channel("disable\n") time.sleep(2) print(net_connect.read_channel()) # f net_connect.enable() print(net_connect.find_prompt()) net_connect.disconnect()
from getpass import getpass import time password = getpass() device = { "host": "cisco4", "username": "******", "password": password, 'secret': password, "device_type": "cisco_ios", "session_log": "cisco4_6e.txt" } t1 = datetime.now() ssh_con = ConnectHandler(**device) ssh_con.write_channel('disable\n') time.sleep(3) output = ssh_con.read_channel() print(output) prompt = ssh_con.find_prompt() print(prompt) ssh_con.disconnect() t2 = datetime.now() t3 = t2 - t1 print("\nINICIO: ", t1) print('\nFIN: ', t2) print('\nDuracion ejecucion comando: ', t3)
import time cisco4 = { "host":" cisco4.lasthop.io", "username": "******", "password": "******", "secret": "88newclass", "device_type": "cisco_ios", "session_log": "week2_exercise6_log.txt", } cisco4_connect = ConnectHandler(**cisco4) print(cisco4_connect.find_prompt()) cisco4_connect.config_mode() print(cisco4_connect.find_prompt()) cisco4_connect.exit_config_mode() print(cisco4_connect.find_prompt()) print("\nExit privileged exec (disable), Current Prompt: ") cisco4_connect.write_channel("disable\n") time.sleep(2) output = cisco4_connect.read_channel() print(output) print("\nRe-enter enable mode, Current Prompt: ") cisco4_connect.enable() print(cisco4_connect.find_prompt()) cisco4_connect.disconnect() print()
net_connect = ConnectHandler( device_type="terminal_server", ip="10.10.10.10", username="******", password="******", secret="secret123", ) # Manually handle interaction in the Terminal Server (fictional example, but # hopefully you see the pattern) net_connect.write_channel("\r\n") time.sleep(1) net_connect.write_channel("\r\n") time.sleep(1) output = net_connect.read_channel() # Should hopefully see the terminal server prompt print(output) # Login to end device from terminal server net_connect.write_channel("connect 1\r\n") time.sleep(1) # Manually handle the Username and Password max_loops = 10 i = 1 while i <= max_loops: output = net_connect.read_channel() if "Username" in output: net_connect.write_channel(net_connect.username + "\r\n")
def latency_topo(): mininet={ 'device_type':'linux', 'username':'******', 'password':'******', 'ip':"192.168.10.21", } net_connect1=ConnectHandler(**mininet) net_connect1.send_command("echo mininet | sudo -S mn -c") #spinning the custom topology net_connect1.write_channel("sudo mn --custom sdn_lab8_delay.py --topo=mytopo --controller=remote,ip=192.168.10.22,port=6653 --mac\n") time.sleep(1) output2 = net_connect1.read_channel() if "word" in output2: net_connect1.write_channel("mininet\n") time.sleep(1) url_flow_add = "http://192.168.10.22:8080/stats/flowentry/add" url_flow_del = "http://192.168.10.22:8080/stats/flowentry/delete_strict" url_s1 = 'http://192.168.10.22:8080/router/0000000000000001' data_s1 = '{"address":"10.0.0.2/24"}' url_s5 = 'http://192.168.10.22:8080/router/0000000000000005' data_s5 = '{"address":"1.1.1.2/24"}' r_s1 = requests.post(url = url_s1, data = data_s1) r_s5 = requests.post(url = url_s5, data = data_s5) var_file1 = {6:{"1.1.1.0/24":2, "10.0.0.0/24":1}, 7:{"1.1.1.0/24":1, "10.0.0.0/24":2}, 2:{"1.1.1.0/24":2, "10.0.0.0/24":1}, 3:{"1.1.1.0/24":2, "10.0.0.0/24":1}, 4:{"1.1.1.0/24":2, "10.0.0.0/24":1}, 8:{"1.1.1.0/24":2, "10.0.0.0/24":1} } cookie = 40 #adding required flows on other switches for i in var_file1: for j in var_file1[i]: data_flow = '{"dpid":'+str(i)+', "cookie":'+str(cookie)+', "table_id":0, "priority":1000, "match": { "dl_type":0x800, "nw_dst":"'+str(j)+'", }, "actions":[{"type":"OUTPUT", "port":'+str(var_file1[i][j])+', }]}' r_flow = requests.post(url = url_flow_add, data= data_flow) cookie+=1 latency={} #adding flows to measure the latency of top path s1_top = '{"dpid":1, "cookie":50, "table_id":0, "priority":1000, "match": { "dl_type":0x800, "nw_dst":"1.1.1.0/24", }, "actions":[{"type":"OUTPUT", "port":3, }]}' s5_top = '{"dpid":5, "cookie":50, "table_id":0, "priority":1000, "match": { "dl_type":0x800, "nw_dst":"10.0.0.0/24", }, "actions":[{"type":"OUTPUT", "port":4, }]}' r_flow = requests.post(url = url_flow_add, data= s1_top) r_flow = requests.post(url = url_flow_add, data= s5_top) p1 = net_connect1.send_command("Host ping Server -c 4") reg=r'\/\d+\.?\d+' find=re.findall(reg,p1) latency['up']=float(find[0][1:]) #deleting flows from top path r_flow = requests.post(url = url_flow_del, data= s1_top) r_flow = requests.post(url = url_flow_del, data= s5_top) #adding flows to measure the latency of middle path s1_middle = '{"dpid":1, "cookie":50, "table_id":0, "priority":2000, "match": { "dl_type":0x800, "nw_dst":"1.1.1.0/24", }, "actions":[{"type":"OUTPUT", "port":2, }]}' s5_middle = '{"dpid":5, "cookie":50, "table_id":0, "priority":2000, "match": { "dl_type":0x800, "nw_dst":"10.0.0.0/24", }, "actions":[{"type":"OUTPUT", "port":1, }]}' r_flow = requests.post(url = url_flow_add, data= s1_middle) r_flow = requests.post(url = url_flow_add, data= s5_middle) p2 = net_connect1.send_command("Host ping Server -c 4") reg=r'\/\d+\.?\d+' find=re.findall(reg,p2) latency['middle']=float(find[0][1:]) #deleting flows from middle path r_flow = requests.post(url = url_flow_del, data= s1_middle) r_flow = requests.post(url = url_flow_del, data= s5_middle) #adding flows to measure the latency of bottom path s1_bottom = '{"dpid":1, "cookie":50, "table_id":0, "priority":3000, "match": { "dl_type":0x800, "nw_dst":"1.1.1.0/24", }, "actions":[{"type":"OUTPUT", "port":4, }]}' s5_bottom = '{"dpid":5, "cookie":50, "table_id":0, "priority":3000, "match": { "dl_type":0x800, "nw_dst":"10.0.0.0/24", }, "actions":[{"type":"OUTPUT", "port":3, }]}' r_flow = requests.post(url = url_flow_add, data= s1_bottom) r_flow = requests.post(url = url_flow_add, data= s5_bottom) p3 = net_connect1.send_command("Host ping Server -c 4") reg=r'\/\d+\.?\d+' find=re.findall(reg,p3) latency['bottom']=float(find[0][1:]) #deleting flows from bottom path r_flow = requests.post(url = url_flow_del, data= s1_bottom) r_flow = requests.post(url = url_flow_del, data= s5_bottom) #finding the lowest latency path key_min = min(latency.keys(), key=(lambda k: latency[k])) http_path="HTTP traffic is going via {}".format(path[key_min]) #adding flows for the lowest latency path s1_http_middle='{"dpid":1, "cookie":60, "table_id":0, "priority":3000, "match": { "dl_type":0x800, "nw_proto":6, "tp_dst":80, }, "actions":[{"type":"OUTPUT", "port":2, }]}' s5_http_middle='{"dpid":5, "cookie":61, "table_id":0, "priority":3000, "match": { "dl_type":0x800, "nw_proto":6, "tp_src":80, }, "actions":[{"type":"OUTPUT", "port":1, }]}' r_flow = requests.post(url = url_flow_add, data= s1_http_middle) r_flow = requests.post(url = url_flow_add, data= s5_http_middle) r_flow = requests.post(url = url_flow_add, data= s1_top) r_flow = requests.post(url = url_flow_add, data= s5_top) #testing the end-to-end connectivity for ICMP traffic print("Look at the flow-dumps & n_packets on switches to test the ICMP traffic") time.sleep(30) p_test = net_connect1.send_command("Host ping Server -c 4") print(p_test) #testing the end-to-end connectivity for HTTP traffic http_run = net_connect1.send_command("Server python -m SimpleHTTPServer 80 &") print("Look at the flow-dumps & n_packets on switches to test the HTTP traffic") time.sleep(30) http_test = net_connect1.send_command("Host wget -O - Server") print(http_test) #performing the traceroute for ICMP traffic f1 = net_connect1.send_command("sh ovs-ofctl dump-flows -O OpenFlow13 OvS1 | grep actions=output:3") value1= int(f1.split(',')[3].split('=')[1]) p1 = net_connect1.send_command("Host ping Server -c 4") f2 = net_connect1.send_command("sh ovs-ofctl dump-flows -O OpenFlow13 OvS1 | grep actions=output:3") value2= int(f2.split(',')[3].split('=')[1]) if value2>value1: icmp_path="ICMP traffic is going via {}".format(path["upper"]) else: icmp_path="ICMP traffic is going via either {} or {} path.".format(path["middle"],path["bottom"]) return render_template('sdn_lab8_latency.html',icmp_path=icmp_path, http_path=http_path)
cisco4 = { "host": "cisco4.lasthop.io", "username": "******", "password": password, "device_type": "cisco_ios", "secret": "88newclass", "session_log": "my_output.txt", } connection = ConnectHandler(**cisco4) print(connection.find_prompt()) connection.config_mode() print(connection.find_prompt()) connection.exit_config_mode() print(connection.find_prompt()) connection.write_channel("disable\n") time.sleep(2) print(connection.read_channel()) connection.enable() print(connection.find_prompt())
import time host_cisco4 = { "host": 'cisco4.lasthop.io', "username": '******', "password": getpass(), "secret": getpass(), "device_type": 'cisco_ios', #"fast_cli": True, "session_log": './session_logs/session_log_cisco4.txt', } host_connect = ConnectHandler(**host_cisco4) print(host_connect.find_prompt()) host_connect.config_mode() print(host_connect.find_prompt()) host_connect.exit_config_mode() print(host_connect.find_prompt()) host_connect.write_channel("disable\n") time.sleep(2) print(host_connect.read_channel()) host_connect.enable() print(host_connect.find_prompt()) host_connect.disconnect()
def underlay(): ios_r1={ 'device_type':'cisco_ios', 'username':'******', 'password':'******', 'ip':'192.168.100.1', } ios_r2={ 'device_type':'cisco_ios', 'username':'******', 'password':'******', 'ip':'192.168.200.2', } ios_r3={ 'device_type':'cisco_ios', 'username':'******', 'password':'******', 'ip':'172.16.100.1', } net_connect1=ConnectHandler(**ios_r1) print("----------Adding routes to R1----------") net_connect1.send_config_set(["ip route 172.16.100.0 255.255.255.0 192.168.200.2"]) print("ip route 172.16.100.0 255.255.255.0 192.168.200.2") net_connect1.send_config_set(["ip route 10.20.30.0 255.255.255.0 192.168.200.2"]) print("ip route 10.20.30.0 255.255.255.0 192.168.200.2") print("----------Routes added to R1----------") print("----------Adding routes to R2----------") net_connect1.write_channel("ssh -l sdn 192.168.200.2\n") time.sleep(1) output2 = net_connect1.read_channel() if "word" in output2: net_connect1.write_channel(net_connect1.password + '\n') time.sleep(1) output2 += net_connect1.read_channel() net_connect1.write_channel("conf t\n") time.sleep(1) net_connect1.write_channel("ip route 192.168.100.0 255.255.255.0 192.168.200.1\n") print("ip route 192.168.100.0 255.255.255.0 192.168.200.1") net_connect1.write_channel("ip route 10.20.30.0 255.255.255.0 172.16.100.1\n") print("ip route 10.20.30.0 255.255.255.0 172.16.100.1") time.sleep(1) net_connect1.write_channel("exit\n") print("----------Routes added to R2----------") print("----------Adding routes to R4----------") net_connect1.write_channel("ssh -l sdn 172.16.100.1\n") time.sleep(1) output2 = net_connect1.read_channel() if "word" in output2: net_connect1.write_channel(net_connect1.password + '\n') time.sleep(1) net_connect1.write_channel("conf t\n") time.sleep(1) net_connect1.write_channel("ip route 192.168.100.0 255.255.255.0 172.16.100.2\n") print("ip route 192.168.100.0 255.255.255.0 172.16.100.2") net_connect1.write_channel("ip route 192.168.200.0 255.255.255.0 172.16.100.2\n") print("ip route 192.168.200.0 255.255.255.0 172.16.100.2") time.sleep(1) print("----------Routes added to R4----------") net_connect1.disconnect()
print("\nEnter Config mode") net_connect.config_mode() print ("\n>>>>>>>") print("Checking if it's in config mode") print("Config mode check: {}".format(net_connect.check_config_mode())) print("Current Prompt: {}".format(net_connect.find_prompt())) print("\nExit Config mode") net_connect.exit_config_mode() print ("\n>>>>>>>") # print("Config mode check: {}".format(net_connect.exit_config_mode()) print("Current Prompt: {}".format(net_connect.find_prompt())) net_connect = ConnectHandler(**device) print("\nExit priviledged exec (disable), Current prompt") net_connect.write_channel("disable\n") time.sleep(2) print ("\n>>>>>>>") output = net_connect.read_channel() print(output) net_connect = ConnectHandler(**device) print("\nExecute enable() method, Current prompt") net_connect.enable() print(net_connect.find_prompt()) net_connect.disconnect() print()
import time logging.basicConfig(filename='netmiko_global.log', level=logging.DEBUG) logger = logging.getLogger("netmiko") device123 = { "device_type": "terminal_server", "ip": "192.168.29.141", "username": "******", "password": "******", } ssh123 = ConnectHandler(**device123) output123 = ssh123.send_command("ifconfig") print(output123) #cisco ip123 = [" 192.168.29.133"] for xyz123 in ip123: usernamer123 = "admin" ssh123.write_channel("ssh -l " + usernamer123 + xyz123 + "\n") max_trial = 4 i = 1 while i <= max_trial: ssh123.write_channel(input("enter the password for ") + "\n") time.sleep(1) output345 = ssh123.read_channel() if ">" in output345 or "#" in output345: break i += 1 redispatch(ssh123, device_type="cisco_ios") output124 = ssh123.send_config_set("logging host 2.2.2.2") print(output124) *redispatch used for changing device_type