def config_change(ips): try: cisco_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**cisco_IOS) net_connect.enable() with open('config_change.txt') as commands: command = commands.read().splitlines() # g_output = net_connect.send_config_from_file(config_file="config_change.txt") g_output = net_connect.send_config_set(command) net_connect.disconnect() return "-----------Working on host " + ips + " -----------\n" + g_output + "\n" # except ValueError: except NetMikoTimeoutException: w = open('status_output.txt', 'a') w.write("ERROR: connection to " + ips + " timed-out.") w.close() except NetMikoAuthenticationException: k = open('status_output.txt', 'a') k.write("ERROR: Authentication failed for " + ips) k.close()
def status_check(ips): try: cisco_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**cisco_IOS) net_connect.enable() with open('status_check.txt') as command: output = '' for commands in command: output += "=====>" + commands + net_connect.send_command( commands) + '\n' net_connect.disconnect() return "-----> Working on host " + ips + " <-----" "\n" + output + "\n" except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authentication failed for " + ips)
def backupH(ips): try: hirschmann_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**hirschmann_IOS) net_connect.enable() out = net_connect.send_command( "copy config running-config remote tftp://" + tftp_ip + "/OSC." + ips + ".xml") net_connect.disconnect() except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authenticaftion failed for " + ips)
def backup(ips): try: cisco_IOS = { 'device_type': 'cisco_ios', 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**cisco_IOS) net_connect.enable() out = net_connect.send_command("show running-config") net_connect.disconnect() with open(path + '/' + ips + '.txt', 'w') as fileouts: fileouts.write(out) except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authenticaftion failed for " + ips)
def get_ip_dhcp(ip): show_info("Waiting DHCP ACK...") # Attente de l'ip avant de continuer time.sleep(12) net_connect = Netmiko(**get_dic(ip)) net_connect.enable() dhcp_check = net_connect.send_command("sh ip int brief | in DHCP") dhcp = dhcp_check.split() return dhcp[1]
def main(): """ Funcion principal """ # Llamada a la funcion "clear_screen" clear_screen() # variable de texto con el valor "ips.txt" name_file_ip_list = "ips.txt" # variable de texto con el valor "commands.txt" name_file_commands_list = "commands.txt" # Llamada a la funcion "read_files" y guardarla en la variable "ips_list". ips_list = read_files(name_file_ip_list) # Dividir las lineas de la variable ips_list en una lista. ips_list = ips_list.splitlines() # Llamada a la funcion "read_files" y guardarla en la variable # "command_list". command_list = read_files(name_file_commands_list) # Dividir las lineas de la variable ips_list en una lista. command_list = command_list.splitlines() # Realizar ciclo for con la lista "ip_list". para determinar que "ips" # estan activas. for ip in ips_list: # Llamada a la funcion "ping_alive" con el argumento "ip". ping_alive(ip) # Realizar ciclo for con la lista "ip_list". para realizar las conexions # y configuraciones con la libreria Netmiko. for ip in ips_list: dispositivo = { "username": "******", "ip": ip, "password": "******", "device_type": "cisco_ios", "secret": "pythonautomationcourse", } # Creacion de la conexion SSH. net_connect = Netmiko(**dispositivo) # ** Significa que es pasado # todos los valores del # Diccionario. net_connect.enable() # Entrar en modo Privilegiado. # Enviar lista "command_list" en modo "Configuracion Global". net_connect.send_config_set(command_list) # Salvar la configuracion en los dispositivos. net_connect.save_config() # Finalizar la conexión del dispositivo. net_connect.disconnect()
def connect_and_send_command(host, command): # Connect to devices net_connection = Netmiko(host=host['ip'], username=host['username'], password=host['password'], port=host['port'], device_type=host['type'], secret=host['secret']) net_connection.enable() output = net_connection.send_command(command) return output
def connectToDevice(): fromDevice = Netmiko( device_type="cisco_ios", ip="10.54.153.52", username="******", password="******", secret='cisco1234', fast_cli = True ) fromDevice.enable() return fromDevice
def dhcp_pool(ip): show_result("Reading dhcp_pool file...") net_connect = Netmiko(**get_dic(ip)) print("-------------------------------------------------") net_connect.enable() # Envoie la configuration du fichier dhcp_pool net_connect.send_config_from_file("dhcp_pool") show_result("DHCP pool configured !") # Demande de write la conf save = input(show_input("Do you want to write configuration ? (y/n) : ")) if save == "y" or save == "yes": write_conf(ip) end_task() print("-------------------------------------------------")
def connect_to_device(import_file, command): for host in import_file['hosts']: net_connection = Netmiko(host=host['ip'], username=host['username'], password=host['password'], port=host['port'], device_type=host['type'], secret=host['secret']) net_connection.enable() output = net_connection.send_command(command) # print(host['ip']) with open(f"{host['name']}" + "_tech-support.txt", 'w') as f: f.write(output) return output
def ssh_session(ip): #This establishes the SSH session using Netmiko ssh_creds = env_file.get(path="env/ssh") netmiko_creds = { "device_type": "cisco_ios", "ip": ip, "username": ssh_creds["SSH_USERNAME"], "password": ssh_creds["SSH_PASSWORD"], "secret": ssh_creds["SSH_SECRET"] } netmiko_session = Netmiko(**netmiko_creds) netmiko_session.enable() return netmiko_session
def ciscoasacon(ipaddr, username, password, secret, networknodetype): if secret == "none": CiscoASAConnectNoEnable = { "host": ipaddr, "username": username, "password": password, "device_type": networknodetype} net_connect = Netmiko(**CiscoASAConnectNoEnable) # This is where it connect with SSH for no enable/secret elif secret != "none": CiscoASAConnectWithEnable = { "host": ipaddr, "username": username, "secret": secret, "password": password, "device_type": networknodetype} net_connect = Netmiko(**CiscoASAConnectWithEnable) # This is where it connect with SSH print("\n") print(net_connect.find_prompt()) print(net_connect.enable()) print(net_connect.send_command("sh clock")) clock = net_connect.send_command("sh clock") print(net_connect.send_command("sh int ip brief")) interfaces = net_connect.send_command("sh int ip brief") shrun = net_connect.send_command("sh run") print(net_connect.send_command("sh run")) net_connect.disconnect() writetohdd(interfaces, shrun)
def config_applier(): config = open("configs.txt") devicelist = [] device = open("device_generated.txt") username = input("Input device username: "******"Input device password: "******"Input device secret: ") for line in device: line = line.rstrip() devicelist.append(line) config_set = config for host in devicelist: net_connect = Netmiko(host, username=username, password=password, device_type="cisco_nxos", secret=secret) print(net_connect.find_prompt()) print(net_connect.enable()) output = net_connect.send_config_set(config_set) print(net_connect.send_config_set(config_set)) print(net_connect.save_config()) print(net_connect.disconnect()) with open("audit.txt", "a") as f: f.write(output) print("See 'audit.txt' for confirmation of process")
def confgen(vars): # Generate configuration lines with Jinja2 with open(jinja_template) as f: tfile = f.read() template = jinja2.Template(tfile) cfg_list = template.render(vars) print('-' * 80) print(cfg_list) print('-' * 80) # Connect directly to host via telnet on the specified port conn = Netmiko(host=hostip, device_type='cisco_ios_telnet', port=vars['port']) # Check if host is in initial config state conn.write_channel("\n") time.sleep(1) output = conn.read_channel() if 'initial configuration dialog' in output: conn.write_channel('no\n') time.sleep(1) # Send generated commands to host output = conn.enable() output = conn.send_config_set(cfg_list) # Display results print('-' * 80) print('\nConfiguration applied on ' + vars['host'] + ': \n\n' + output) print('-' * 80) # Probably a good idea conn.disconnect()
class IOSDevice(): def __init__(self, host, username, password, enable, secret): self.device = { 'device_type': 'cisco_ios', 'host': host, 'username': username, 'password': password, 'secret': secret } self.enable = enable self.dev_connection = Netmiko(**self.device) def get_config(self): if self.enable: self.dev_connection.enable() return self.dev_connection.send_command('show runn')
def dhcp_client(ip): interface = input(show_input("Specify target interface : ")) net_connect = Netmiko(**get_dic(ip)) print("-------------------------------------------------") net_connect.enable() enable = [interface, 'ip address dhcp', 'no sh'] conf_t = net_connect.send_config_set(enable) print(conf_t) print("-------------------------------------------------") # Affiche l'IP reçue par le DHCP show_result("You got {0} from DHCP".format(get_ip_dhcp(ip))) # Demande de write la conf save = input(show_input("Do you want to write configuration ? (y/n) : ")) if save == "y" or save == "yes": write_conf(ip) end_task() print("-------------------------------------------------")
def make_connection_to_device(): '''Helper invoked from main() to set up a netmiko connection to the device, and put it into enable mode''' # access the netrc to read the credentials try: rc = netrc.netrc() except FileNotFoundError as e: print('(Failed to access netrc file for gathering ', 'login credentials: {})'.format(str(e)), file=sys.stderr) sys.exit(-1) netmiko_device_info = {} netmiko_device_info['host'] = DESIRED_SETTINGS['device'] netmiko_device_info['device_type'] = 'cisco_ios' try: host = netmiko_device_info['host'] (login, enable_password, password) = rc.authenticators(host) except TypeError: print('No entry in netrc file for device "{}", and no default ' 'either.'.format(netmiko_device_info['host']), file=sys.stderr) sys.exit(-1) # Fill in the user name / password / enable password device_info # attributes from the info we read from .netrc netmiko_device_info['username'] = login netmiko_device_info['password'] = password if enable_password: netmiko_device_info['secret'] = enable_password print('Connecting to device_info "{}"...'.format( netmiko_device_info['host']), end='', flush=True) device = Netmiko(**netmiko_device_info) print('connected.') print('Entering enable mode...', end='', flush=True) device.enable() print('done.') prompt = device.find_prompt() print('Prompt is "{}"'.format(prompt)) return device
def save_configH(ips): try: hirschmann_IOS = { 'device_type': "hirschmann_ssh", 'host': ips, 'username': username, 'password': password, 'secret': password, 'timeout': 10000, 'session_timeout': 10000 } net_connect = Netmiko(**hirschmann_IOS) net_connect.enable() output = net_connect.send_command('copy config running-config nvm') net_connect.disconnect() return output except ValueError: pass except NetMikoTimeoutException: print("ERROR: connection to " + ips + " timed-out.\n") except NetMikoAuthenticationException: print("ERROR: Authentication failed for " + ips)
try: host = raw_input("Enter host to connect to: ") except NameError: host = input("Enter host to connect to: ") password = getpass() device = { 'host': host, 'username': '******', 'password': password, 'device_type': 'cisco_ios', "secret": "cisco" } net_connect = Netmiko(**device) net_connect.enable() # Use send_config_set() to make config change config = ['logging console', 'logging buffer 15000'] output = net_connect.send_config_set(config) output_printer(output) # Use send_config_from_file() to make config change output = net_connect.send_config_from_file('config.txt') output_printer(output) message = "Verifying config change\n" output = net_connect.send_command("show run | inc logging") if '8000' in output: message += "Logging buffer is size 8000" else: message += "Logging buffer size is not correct!"
ios_device = { "device_type": "cisco_ios", # Tipo de dispositivo. "ip": ip_list, # IP Address. "username": "******", # Nombre de Usuario. "password": "******", # Password de usuario. "secret": "pythonautomationcourse", # Password enable secret. } # Creacion de la conexion SSH net_connect = Netmiko(**ios_device) # ** Significa que es pasado todas los # valores de las llaves del diccionario. net_connect.enable() # Entrar en "Modo Privilegiado". # Variable de texto con valor del comando para L2 o L3. show_version = "show version | section include Cisco IOS Software" # Enviar el comando "show_version" y guardar en la variable "output" # para su posterior tratamiento. output = net_connect.send_command(show_version) # Si "el texto" se encuentra en la variable "output" entonces se realiza # la siguiente actividad. if "vios_l2-ADVENTERPRISEK9-M" in output: # Declaracion de la lista vacia de "vlan_list". vlan_list = [] # Crear vlans.
host = input("Enter host to connect to: ") # Create dicionary of parameter to feed into 'net_connect' my_device = { 'host': host, 'username': '******', 'password': password, 'secret': password, 'device_type': 'cisco_ios' } # Establish SSH Connection net_conn = Netmiko(**my_device) # Enter enable mode net_conn.enable() # Automatically enter enable mode # Send command down the channel, expecting raw output output = net_conn.send_command('show ip interface brief') print('\nOutput Type = ', type(output)) print('\n\n') print(output) # Send command down the channel and parse through TextFSM output = net_conn.send_command('show ip interface brief', use_textfsm=True) print('\nOutput Type = ', type(output)) print('\n\n') print(output) # Print structured output header print('\n\n')
'host': '10.1.1.253', 'username': '******', 'password': '******', 'device_type': 'cisco_ios_telnet', # Telnet # 'device_type': 'cisco_ios', # SSH 'secret': 'Cisc0123', } # 支持的device_types # https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py # 主要是CLASS_MAPPER_BASE部分 # ">" 下的exec命令 net_connect = Netmiko(**CSR1) # ** 表示使用字典映射的方式来传参数 # Netmiko(host='10.1.1.253', username='******', password='******', device_type='cisco_ios_telnet', secret='Cisc0123') print(net_connect.send_command("show ip interface brief")) # "#" 下的exec命令 net_connect.enable() # 如果需要, 使用enable进入特权模式 print(net_connect.send_command("show run")) # 全局配置模式下的配置命令 config_commands = [ 'router ospf 1', 'router-id 1.1.1.1', 'network 1.1.1.1 0.0.0.0 a 0' ] output = net_connect.send_config_set(config_commands) print(output) net_connect.disconnect()
class Client: def __init__(self, platform, hostname, username, password, port, keys): self.platform = platform self.hostname = hostname self.username = username self.password = password self.port = port self.keys = keys self.net_connect = None def connect(self): if self.keys: try: self.net_connect = Netmiko(device_type=self.platform, host=self.hostname, port=self.port, pkey=self.keys, use_keys=True, username=self.username, passphrase=self.password) except Exception as err: return_error(err) else: try: self.net_connect = Netmiko(device_type=self.platform, host=self.hostname, port=self.port, use_keys=True, username=self.username, password=self.password) except Exception as err: return_error(err) def disconnect(self): try: if self.net_connect: self.net_connect.disconnect() except Exception as err: return_error(err) def cmds(self, require_exit, exit_argument, commands, enable, isConfig): try: output = { "Hostname": self.hostname, "Platform": self.platform, "Commands": [] } self.connect() if enable: self.net_connect.enable() # type: ignore if isConfig: output['Commands'].append({ "Hostname": self.hostname, "DateTimeUTC": datetime.utcnow().isoformat(), "Config": self.net_connect.send_config_set(commands) }) # type: ignore if not isConfig: for cmd in commands: prompt = self.net_connect.find_prompt() # type: ignore c = { "Hostname": self.hostname, "DateTimeUTC": datetime.utcnow().isoformat(), "Command": cmd, "Output": f"{prompt} {self.net_connect.send_command_timing(cmd)}" } # type: ignore output['Commands'].append(c) except Exception as err: return_error(err) finally: self.disconnect() return output
def gns3_send_start_config_telnet(gns3_server, project_id, gns3_code_topology_data, global_delay_factor): print(""" ╔═╗┌┬┐┌─┐┌─┐ ╦╦ ╦ ┌─┐┌─┐┌┐┌┌┬┐ ┌─┐┌┬┐┌─┐┬─┐┌┬┐┬ ┬┌─┐ ┌─┐┌─┐┌┐┌┌─┐┬┌─┐ ╚═╗ │ ├┤ ├─┘ ║╚╗╔╝ └─┐├┤ │││ ││ └─┐ │ ├─┤├┬┘ │ │ │├─┘ │ │ ││││├┤ ││ ┬ ╚═╝ ┴ └─┘┴ ╩ ╚╝. └─┘└─┘┘└┘─┴┘ └─┘ ┴ ┴ ┴┴└─ ┴ └─┘┴ └─┘└─┘┘└┘└ ┴└─┘. """) gns3_host_ip = gns3_code_topology_data['gns3_host_ip'] START_CFGS_PATH = gns3_code_topology_data['START_CFGS_PATH'] list_start_config_nodes = [] for node in gns3_code_topology_data['gns3_startup_config_telnet']: name = node['name'] list_start_config_nodes.append(name) for node_name in list_start_config_nodes: print() print( 'Applying startup config to', node_name + ' from', '[' + gns3_code_topology_data['START_CFGS_PATH'] + node_name + ']') print() r_get_nodes = requests.get(gns3_server + '/v2/projects/' + str(project_id) + '/nodes') r_get_nodes_dict = r_get_nodes.json() for dictionary_node in r_get_nodes_dict: if dictionary_node['name'] == node_name: # For VPCS if dictionary_node['node_type'] == 'vpcs': device_type = 'generic_termserver_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } net_connect = Netmiko(**device) net_connect.send_config_from_file(config_file=config_path, exit_config_mode=False) net_connect.disconnect() continue # For VyOS. elif dictionary_node['port_name_format'] == 'eth{0}': device_type = 'generic_termserver_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } vyos = pexpect.spawn('telnet ' + gns3_host_ip + ' ' + str(telnet_port)) vyos.expect('') vyos.sendline('\n') vyos.expect('login: '******'vyos\n') vyos.expect('Password:'******'vyos') net_connect = Netmiko(**device) net_connect.send_config_from_file(config_file=config_path, exit_config_mode=False) net_connect.disconnect() continue # For JunOS. elif dictionary_node['port_name_format'] == 'ge-0/0/{0}': device_type = 'juniper_junos_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } juniper = pexpect.spawn('telnet ' + gns3_host_ip + ' ' + str(telnet_port)) juniper.expect('') juniper.sendline('\n') juniper.expect('login: '******'root\n') juniper.expect('') juniper.sendline('\n') juniper.expect('root@% ', timeout=120) juniper.sendline('cli') with open(config_path) as f: lines = f.read().splitlines() net_connect = Netmiko(**device) net_connect.config_mode() for line in lines: net_connect.send_command_timing(line) time.sleep(1) net_connect.disconnect() continue # For Cisco IOS and Cisco ASA. else: device_type = 'cisco_ios_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } net_connect = Netmiko(**device) net_connect.enable() net_connect.send_config_from_file(config_file=config_path) net_connect.disconnect() continue print('Success -', node_name) print('=' * 100)
def ssh_connection(request): ssh = Netmiko(**request.param) ssh.enable() yield ssh ssh.disconnect()
# Part a - find and print the prompt to the screen print(net_connect.find_prompt()) # Part B - Enter config mode and find the prompt print(net_connect.config_mode()) print(net_connect.find_prompt()) # Part C - exit config mode and print the prompt print(net_connect.exit_config_mode()) print(net_connect.find_prompt()) # Part D - send disable down the SSH channel print(net_connect.write_channel('disable\n')) # Part E - Sleep for 2s and read back from SSH channel time.sleep(2) print(net_connect.read_channel()) # Part F - Go into enable mode and print prompt print(net_connect.enable()) print(net_connect.find_prompt()) net_connect.disconnect()
inp_file = in_file.readlines() for ip in inp_file: Devices = { 'device_type': 'cisco_ios', 'host': ip, 'username': '******', 'password': '******', 'port': 22, # optional, defaults to 22 'secret': '', # optional, defaults to '' 'auth_timeout': 20 } net_connect = Netmiko(**Devices) time.sleep(20) cfg_file = "configfile.txt" print() print(net_connect.find_prompt()) output = net_connect.enable() output = net_connect.send_config_from_file(cfg_file) print(output) print() net_connect.save_config() net_connect.disconnect() #---------------------------------------------[Code Ends]------------------------------------------------------#
print("ip address 10.1." + str(i) + ".1 255.255.255.0") print("security-level 75") for i in range(200, 250): print("interface GigabitEthernet0/3." + str(i)) print("vlan " + str(i)) print("nameif wired_user-v" + str(i)) print("ip address 10.1." + str(i) + ".1 255.255.255.0") print("security-level 75") # close the file, stop redirecting stdout sys.stdout.close() sys.stdout = orig_stdout # setup Netmiko firewall = { 'host': '10.139.146.1', 'username': '******', 'password': '******', 'device_type': 'cisco_asa', 'secret': 'not_the_real_enable_password_either', } firewallconnect = Netmiko(**firewall) firewallconnect.enable() # run Netmiko, print what happens on firewall, disconnect # https://github.com/ktbyers/netmiko/issues/2025 for why we want that cmd_verify=False here output = firewallconnect.send_config_from_file("firewallfile", cmd_verify=False) print(output) firewallconnect.disconnect()
#!/usr/bin/env python from __future__ import print_function, unicode_literals # Netmiko is the same as ConnectHandler from netmiko import Netmiko from getpass import getpass my_device = { 'host': "host.domain.com", 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', } net_connect = Netmiko(**my_device) # Ensure in enable mode net_connect.enable() print(net_connect.find_prompt()) net_connect.disconnect()
# Learning Python 2018 / Week 6, Netmiko Intro and Basics from netmiko import Netmiko my_device = { 'host': '192.168.250.254', 'username': '******', 'password': '******', 'secret': 'password', 'device_type': 'cisco_ios' } net_conn = Netmiko(**my_device) #output = net_conn.find_prompt() net_conn.enable() output = net_conn.send_command("show ip arp", use_textfsm=True) print(output)
from netmiko import Netmiko from getpass import getpass import time password = getpass() ios4 = { 'device_type':'cisco_ios', 'host':'cisco4.lasthop.io', 'username':'******', 'password':password, 'secret':password, 'session_log':'my_output.txt', } conn = Netmiko(**ios4) conn.enable() print(conn.find_prompt())