示例#1
0
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

        self.env_creds = env_file.get(path="env\ssh")

        self.ssh_details = {
            "device_type": "cisco_ios",
            "ip": self.ip,
            "port": self.port,
            "username": self.env_creds["SSH_USERNAME"],
            "password": self.env_creds["SSH_PASSWORD"],
            "secret": self.env_creds["SSH_SECRET"]
        }

        self.ssh_session = Netmiko(**self.ssh_details)
        self.ssh_session.enable()
示例#2
0
def show_arp(x_ip):

    my_device = {
        "host": x_ip,
        "username": "******",
        "password": "******",
        "device_type": "cisco_ios",
    }
    try:
        net_connect = Netmiko(**my_device)
        arp_res = net_connect.send_command('show ip arp')
        net_connect.disconnect()

        return arp_res  #return一定要写在最后

    except:
        print("Something wrong")
示例#3
0
def save_loc():
    start = time.time()
    with open('router.list') as f:
        ip_r = f.read().splitlines()
    with open('switch.list') as f:
        ip_s = f.read().splitlines()

    ip_add = ip_r + ip_s
#On parcourt la liste d'IP
    for ip in ip_add:        
        print("Sauvegarde de la configuration de l'équipement ayant l'adresse : "+ ip)

        equipment = {
        'device_type': 'cisco_ios',
        'ip': ip,
        'username': username,
        'password': password,
         }
      
        #On initialise la connexion Netmiko sur l'équipement cible
        net_connect = Netmiko(**equipment)
        #récupération de la running-config
        run_cnf = net_connect.send_command("show running-config")
        print("Configuration Sauvegardée : "+ "\n" + run_cnf)
        now = datetime.now()
        date = now.strftime("%d_%m_%Y")
        
        #Récupération du hostname
        def hostname():
            hst = net_connect.send_command("show running-config | in hostname")
            hostname = hst.split()
            return hostname[1]
        path_save = "save/{0}/".format(hostname())
      
        #Création du dossier de backup si nécessaire
        try:
            os.makedirs(path_save)
        except:
            pass
        file_save = "save/{0}/{1}.txt".format(hostname(),date)
        #Ajoute la configuration au fichier texte créer ci dessus
        with open(file_save, "a") as file:
            file.write(run_cnf  + "\n")
        print("Configuration Sauvegardée dans le fichier:" + file_save +"\n")
        net_connect.disconnect()
    duration(start)
示例#4
0
def deviceconnector(i,q):

    # This while loop runs indefinitely and grabs IP addresses from the queue and processes them
    # Loop will stop and restart if "ip = q.get()" is empty
    while True:
        
        # These print statements are largely for the user indicating where the process is at
        # and aren't required
        print("{}: Waiting for IP address...".format(i))
        ip = q.get()
        print("{}: Acquired IP: {}".format(i,ip))
        
        # k,v passed to net_connect
        device_dict =  {
            'host': ip,
            'username': '******',
            'password': password,
            'device_type': 'cisco_ios'
        }

        # Connect to the device, and print out auth or timeout errors
        try:
            net_connect = Netmiko(**device_dict)
        except NetMikoTimeoutException:
            with print_lock:
                print("\n{}: ERROR: Connection to {} timed-out.\n".format(i,ip))
            q.task_done()
            continue
        except NetMikoAuthenticationException:
            with print_lock:
                print("\n{}: ERROR: Authenticaftion failed for {}. Stopping script. \n".format(i,ip))
            q.task_done()
            os.kill(os.getpid(), signal.SIGUSR1)

        # Capture the output, and use TextFSM (in this case) to parse data
        output = net_connect.send_command(command,use_textfsm=True)
        
        with print_lock:
            print("{}: Printing output...".format(i))
            pprint(output)

        # Disconnect from device
        net_connect.disconnect

        # Set the queue task as complete, thereby removing it from the queue indefinitely
        q.task_done()
示例#5
0
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("-------------------------------------------------")
示例#6
0
    def connect(self):
        print(f"\n\n----- Connecting to {self.hostname}:{self.port}")
        try:
            self.connection = Netmiko(
                self.hostname,
                port=self.port,
                username=self.username,
                password=self.password,
                device_type=self.device_type,
            )
        except:
            self.connection = None
            print("----- Could not connect --------------------")
            return False

        print(f"----- Connected! --------------------")
        return True
示例#7
0
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)
示例#8
0
def hello():
    try:
        print(request)
        json_data = request.get_json(force=True)
        print(json_data)
        router_name = json_data['router']
        interface = json_data['interface']
        # get ip from router
        #start for router config

        net_connect = Netmiko(**cisco1)
        #        command = "show ip int brief"

        command = ("show ip int brief")

        print()
        # print(net_connect.find_prompt())
        output = net_connect.send_command(command)
        net_connect.disconnect()
        # print(output)
        newStr = output.split("Protocol", 1)[1]
        #        res= newStr[0:40]
        res = newStr[0:40]
        newres = ' '.join(res.split())
        result = newres.split(' ')[1]
        #print('*********************************')
        #print(res)
        #print('#####')
        #print(result)
        #        print()

        #end of router add

        #ipadd = "10.20.0.0"
        return jsonify(ip=result)

    #end of router add

    #ipadd = "10.20.0.0"


#        return jsonify(ip = output)
    except Exception as e:
        print(e)
        print("Something went wrong")
示例#9
0
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
示例#10
0
def proxy_vsr():

    vsr_host = {
        "host": vsr,  # Far-end vSR behind JumpServer
        "username": "******",  # Username to the vSR should never change.
        "password": "******",  # Password to the vSR should never change.
        "device_type": "alcatel_sros",
        "ssh_config_file":
        "~/.ssh/config",  # location of the ssh config on the local machine running this script, in order to use jumpserver as proxy.
    }

    net_connect = Netmiko(**vsr_host)

    # Display the Chassis type to screen.
    system_type = net_connect.send_command(
        'show system information | match "System Type"')
    execute = f"Executing Commands on vSR: {system_type} Using the file: {ftp_file}"
    print(execute)

    syntax = net_connect.send_command('exec -syntax ' + 'ftp://*****:*****@' +
                                      JumpServer + '/pub/vzw/' + ftp_file)
    if 'Verified' in syntax:
        print("Syntax Check Verified. Executing configuration.")
    else:
        print(syntax)

    syntax = net_connect.send_command('exec ' + 'ftp://*****:*****@' + JumpServer +
                                      '/pub/vzw/' + ftp_file,
                                      expect_string=r'#')
    if 'failed' in syntax:
        print(":: Failed ::: " + syntax)
    else:
        print(syntax)

    net_connect.disconnect()
示例#11
0
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)
示例#12
0
def main():
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')

    # Get input from user
    while True:
        try:
            subnets = input(
                "Enter a subnet(s) (CIDR notation, space delimited): ").split(
                )
            for i in range(0, len(subnets)):
                subnets[i] = ipaddress.IPv4Network(subnets[i])
        except:
            if input(
                    "Invalid data entered. Press any key to continue or 'q' to quit. "
            ) == 'q':
                exit()
        else:
            break

    if len(subnets) > 0:

        # gather username and password
        cisco_user = input("Device Username: "******"Device Password: "******"Please wait while inventory report is being generated")

        # Open csv file for write operation
        with open(f'{os.getcwd()}/discovered_switches_{timestamp}.csv',
                  'w') as csv_file:
            report_writer = csv.writer(csv_file,
                                       delimiter=',',
                                       quotechar='"',
                                       quoting=csv.QUOTE_MINIMAL)
            report_writer.writerow(['Hostname', 'IP Address', 'Model'])
            for subnet in subnets:
                for ip in subnet.hosts():

                    # Create connection object for Netmiko
                    conn = {
                        "host": str(ip),
                        "username": cisco_user,
                        "password": cisco_pass,
                        "device_type": "cisco_ios",
                    }

                    # Attempt connection
                    try:
                        net_connect = Netmiko(**conn)
                        vers = net_connect.send_command('show version')
                    except:
                        print(f"Error connecting to {str(ip)}")

                    else:
                        hostname = net_connect.find_prompt().split('#')[0]
                        model = net_connect.send_command(
                            'show inventory | inc PID').splitlines()[0].split(
                                ',')[0].lstrip('PID:').strip()
                        report_writer.writerow([hostname, str(ip), model])
                        net_connect.disconnect()
                        print(f"Completed successfully on {str(ip)}")
示例#13
0
 def push_config(self):
     for node in self.data["site_list"]:
         net_connect = Netmiko(**node['login'])
         with open('commands/XC_command_{}_create.txt'.format(node["Node_name"]),'r') as f:
             f2 = f.readlines()
             output = net_connect.send_config_set(f2)
             if node['login']['device_type'] == 'cisco_xr':
                 net_connect.commit()
             else:
                 pass
             #print(output)
             print("****  Configration completed on {}".format(node['Node_name']))
             net_connect.exit_config_mode()
             net_connect.disconnect()
示例#14
0
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()
示例#15
0
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)
示例#16
0
def main():

    my_device = {
        'host': 'ios-xe-mgmt.cisco.com',
        'username': '******',
        'password': '******',
        'device_type': 'cisco_ios',
        'port': 8181
    }
    net_connect = Netmiko(**my_device)

    routes = net_connect.send_command('sh ip route', use_textfsm=True)
    neigbors = net_connect.send_command('sh cdp neighbor', use_textfsm=True)
    arp_entries = net_connect.send_command('sh ip arp', use_textfsm=True)

    print("ROUTES : \n")
    for route in routes:
        print(route)

    print("NEIGHBORS : \n")
    if type(neigbors) == list:
        for nei in neigbors:
            print(nei)

    print("ARPs : \n")
    for arp in arp_entries:
        print(arp)

    net_connect.disconnect()
示例#17
0
def getLicense(host, user, passwd):
    net_connect = Netmiko(
        host, username=user, password=passwd, device_type="juniper_junos"
    )

    command = "show system license"

    print("Logging in as " + user)
    print("*" * 30)
    # print(net_connect.find_prompt())
    print()

    print("Sending command: " + command)
    output = net_connect.send_command(command)
    print(output)
    print()
    print("Logging out and closing session . . .")
    net_connect.disconnect()
示例#18
0
def get_arp_ios(host_dict, vrf=""):
    hostname = host_dict['host']
    #print("Trying connection to " + hostname)
    try:
    # Establish connection
        connection = Netmiko(**host_dict)
    except:
        print("get_arp_ios - Could not establish ssh connection to host" + hostname)
        return -1
    # Run command with textfsm - this should return structured data
    #print("Running command")
    if vrf == "":
        output = connection.send_command("sh ip arp", use_textfsm = True)
    else:
        output = connection.send_command("sh ip arp vrf " + vrf, use_textfsm = True)
    # Return structured data
    #print("Returning output")
    return output
示例#19
0
def Input(ip):

    my_device = {
        "host": ip,
        "username": "******",
        "password": "******",
        "device_type": "cisco_ios",
    }
    try:
        net_connect = Netmiko(
            **my_device)  #Netmiko是一个类,net_connect是一个实例,my_device是产生实例时需要的数据属性
        result = net_connect.send_config_from_file(
            config_file='commands.txt'
        )  #通过实例去调用类函数,实例本身并没有函数属性,是通过风湿理论去调用类里的函数
        net_connect.disconnect()
        return "done"
    except:
        return "something wrong"
示例#20
0
    def sendCommand(self, commandStr, fileName="noname"):

        my_device = {}
        my_device.update({"host": self.ip_addr})
        my_device.update({"username": self.username})
        my_device.update({"password": self.password})
        my_device.update({"device_type": self.deviceType})

        print(my_device)
        net_connect = Netmiko(**my_device)
        output = net_connect.send_command(commandStr)

        # f = open(...)

        if fileName == "noname":
            fileName = "outputs/" + self.hostname + ".cfg"
        with open(fileName, "w", encoding="utf-8") as f:
            f.write(output)
示例#21
0
 def check_bri(self):
     cmd = [
         'config vdom', 'edit SERVICES',
         f'get router info routing-table details | grep {svrbri}'
     ]
     device = {
         'ip': 'extfw-a',
         'username': self.username,
         'password': self.password,
         'use_keys': self.keys,
         'device_type': 'fortinet',
     }
     net_connect = Netmiko(**device, fast_cli=True)
     for command in cmd[:-1]:
         net_connect.send_command(command, expect_string=r"#")
     gateway = re.findall(r'[0-9]+(?:\.[0-9]+){3}',
                          net_connect.send_command(cmd[-1]))[-1]
     return gateway
示例#22
0
def check_if_vlan_exists():
    req_data = request.get_json(force=True)
    vlan_id = req_data['vlan_id']
    vlan_name = req_data['vlan_name']
    cisco = {
        'device_type': 'cisco_ios',
        'ip': '172.16.200.2',
        'username': '******',
        'password': '******'
    }
    switches = [cisco]
    for devices in switches:
        net_connect = Netmiko(**devices)
        command = "show vlan"
        # print()
        # print(net_connect.find_prompt())
        output = net_connect.send_command(command)
        net_connect.disconnect()
        lines = output.split('\n')
        id_arr = []
        name_arr = []
        for x in range(2, len(lines) - 8):
            id = lines[x].split(' ')[0]
            id_arr.append(id)
            if len(id) == 1:
                name = lines[x].split(' ')[4]
            if len(id) == 2:
                name = lines[x].split(' ')[3]
            if len(id) == 3:
                name = lines[x].split(' ')[2]
            if len(id) == 4:
                name = lines[x].split(' ')[1]
            name_arr.append(name)
        if vlan_id in id_arr and vlan_name in name_arr:
            print(f"vlan {vlan_name} already exists")
            return "false"
        elif vlan_id in id_arr:
            print(f"vlan {vlan_id} already exists")
            return "id"
        elif vlan_name in name_arr:
            print(f"Name {vlan_name} already exists")
            return "name"
        else:
            return "true"
示例#23
0
 def delete_config(self):
     for node in self.data["site_list"]:
         net_connect = Netmiko(**node['login'])
         with open(
                 'templates/XC_command_{}_delete.txt'.format(
                     node["Node_name"]), 'r') as f:
             f2 = f.readlines()
             output = net_connect.send_config_set(f2)
             print(output)
             if node['login']['device_type'] == 'cisco_xr':
                 net_connect.commit()
             else:
                 pass
             net_connect.exit_config_mode()
             net_connect.disconnect()
示例#24
0
def main():
    """
    Execution starts here.
    """

    # Read the hosts file into structured data, may raise YAMLError
    with open("hosts.yml", "r") as handle:
        host_root = safe_load(handle)

    # Load the generic variables for all devices outside of the loop
    with open("vars/inputs.yml", "r") as handle:
        data = safe_load(handle)

    # Iterate over the list of hosts (list of dictionaries)
    for host in host_root["production"]:

        # Setup the jinja2 templating environment and render the template
        j2_env = Environment(loader=FileSystemLoader("."),
                             trim_blocks=True,
                             autoescape=True)
        template = j2_env.get_template("templates/routing.j2")
        new_config = template.render(data=data)

        # Create netmiko SSH connection handler to access the device
        conn = Netmiko(
            host=host["name"],
            username="******",
            password="******",
            device_type="cisco_ios",
        )

        print(f"Logged into {conn.find_prompt()} successfully")

        # Send the configuration string to the device. Netmiko
        # takes a list of strings, not a giant \n-delimited string,
        # so use the .split() function
        result = conn.send_config_set(new_config.split("\n"))

        # Netmiko automatically collects the results; you can ignore them
        # or process them further
        print(result)

        conn.disconnect()
示例#25
0
def showint():
    array = []
    array = read_excel('Zhu_list.xlsx', 0)
    b = len(array)
    for j in range(1, b):
        print(array[j][2], array[j][3], array[j][4])
        my_device = {
            "host": array[j][2],
            "username": array[j][4],
            "password": array[j][5],
            "device_type": "cisco_ios",
        }

        net_connect = Netmiko(**my_device)

        output = net_connect.send_command("show ip int brief")
        print(output)

    net_connect.disconnect()
示例#26
0
def netmiko_connect(device_type):

    print(
        f"\n\nConnecting to {cisco_sandbox_device[device_type]['ip']}:{cisco_sandbox_device[device_type]['port']}"
    )
    print("... this may take a little while.")

    connection = Netmiko(**cisco_sandbox_device[device_type])

    return connection
示例#27
0
def netmiko_config_cred(host, username, password, cmds_list, enable='Cisc0123', ssh=True, verbose=False):
    device_info = {
                    'host': host,
                    'username': username,
                    'password': password,
                    'device_type': 'cisco_ios' if ssh else 'cisco_ios_telnet',
                    'secret': enable
    }
    try:
        net_connect = Netmiko(**device_info)
        if verbose:
            output = net_connect.send_config_set(cmds_list)
            return output
        else:
            net_connect.send_config_set(cmds_list)

    except Exception as e:
        print(f'connection error ip: {host} error: {str(e)}')
        return
示例#28
0
def main(argv):
    """
    Execution starts here.
    """

    # Read the hosts file into structured data, may raise YAMLError
    with open("hosts.yml", "r") as handle:
        host_root = safe_load(handle)

    # Netmiko uses "cisco_ios" instead of "ios" and
    # "cisco_xr" instead of "iosxr", so use a mapping dict to convert
    platform_map = {"ios": "cisco_ios", "iosxr": "cisco_xr"}

    # Iterate over the list of hosts (list of dictionaries)
    for host in host_root["host_list"]:

        # Use the map to get the proper Netmiko platform
        platform = platform_map[host["platform"]]

        # Initialize the SSH connection
        print(f"Connecting to {host['name']}")
        conn = Netmiko(
            host=host["name"],
            username="******",
            password="******",
            device_type=platform,
        )

        # Upload the file specified. The dict.get(key) function tries
        # to retrieve the value at the specified key and returns None
        # if it does not exist. Very useful in network automation!
        print(f"  Uploading {argv[1]}")
        result = file_transfer(
            conn,
            source_file=argv[1],
            dest_file=argv[1],
            file_system=host.get("file_system"),
        )

        # Print the resulting details
        print(f"  Details: {result}\n")
        conn.disconnect()
示例#29
0
def worker(host, jobs):
    """ Обработчик заданий
    """
    device = {
        "device_type": "cisco_ios",
        "host": host,
        "username": USERNAME,
        "password": PASSWORD,
        "secret": SECRET
    }
    con = Netmiko(**device)

    if con.find_prompt():
        device = {"con": con, "host": host}
        result = [host]
        for job in jobs:
            result.append(job(**device))
        return result
    else:
        return "Не удалось подключиться к f{host}"
示例#30
0
 def command_firewall(self, hosts, set_command):
     device = {
         'ip': hosts,
         'username': self.username,
         'password': self.password,
         'use_keys': self.keys,
         'device_type': 'fortinet',
     }
     try:
         net_connect = Netmiko(**device, fast_cli=True)
         if isinstance(set_command, list):
             result = []
             for command in set_command:
                 result.append(net_connect.send_command(command))
             return result
         else:
             return net_connect.send_command(set_command,
                                             auto_find_prompt=False)
     except paramiko.ssh_exception.AuthenticationException:
         print("\nWrong Password\n")
示例#31
0
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',
}

filename = 'smallfile'
command = 'delete flash:{}'.format(filename)

net_connect = Netmiko(**device)
output = net_connect.send_command_timing(command, strip_prompt=False, strip_command=False)
if 'confirm' in output:
    # I don't confirm the file delete.
    output += net_connect.send_command_timing('n', strip_prompt=False, strip_command=False)
else:
    raise ValueError("Expected confirm message in output")

print()
print('-' * 80)
print(output)
print('-' * 80)
print()
示例#32
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

cisco1 = {
    'host': 'cisco1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**cisco1)
command = 'copy flash:c880data-universalk9-mz.154-2.T1.bin flash:test1.bin'

print()
print(net_connect.find_prompt())
output = net_connect.send_command(command, delay_factor=4)
print(output)
print()
示例#33
0
#!/usr/bin/env python
from netmiko import SSHDetect, Netmiko
from getpass import getpass

device = {
    'device_type': 'autodetect',
    'host': 'cisco1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
}

guesser = SSHDetect(**device)
best_match = guesser.autodetect()
print(best_match)                   # Name of the best device_type to use further
print(guesser.potential_matches)    # Dictionary of the whole matching result

device['device_type'] = best_match
connection = Netmiko(**device)

print(connection.find_prompt())
示例#34
0
文件: enable.py 项目: ilique/netmiko
#!/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()
示例#35
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

cisco1 = {
    "host": "cisco1.twb-tech.com",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios",
}

net_connect = Netmiko(**cisco1)
command = "del flash:/test1.txt"
print()
print(net_connect.find_prompt())
output = net_connect.send_command_timing(command)
if "confirm" in output:
    output += net_connect.send_command_timing(
        "y", strip_prompt=False, strip_command=False
    )
net_connect.disconnect()
print(output)
print()
示例#36
0
#!/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',
    # Increase (essentially) all sleeps by a factor of 2
    'global_delay_factor': 2,
}

net_connect = Netmiko(**my_device)
# Increase the sleeps for just send_command by a factor of 2
output = net_connect.send_command("show ip int brief", delay_factor=2)
print(output)
net_connect.disconnect()
示例#37
0
#!/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)

output = net_connect.send_command("show ip int brief")
print(output)

net_connect.disconnect()
示例#38
0
"""
Optional, use send_command() in conjunction with ntc-templates to execute a show command. Have
TextFSM automatically convert this show command output to structured data.
"""
from __future__ import print_function, unicode_literals
from netmiko import Netmiko
from getpass import getpass
from pprint import pprint

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',
}

command = 'show ip int brief'
net_connect = Netmiko(**device)
output = net_connect.send_command(command, use_textfsm=True)
print()
print('-' * 80)
pprint(output)
print('-' * 80)
print()
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

R01 = {
    "host": "192.168.1.32",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios",
}

cfg_file = "config_changes.txt"
net_connect = Netmiko(**R01)

# routing table before change #
command = "show ip route"
print('routes PRE changes')
print(net_connect.find_prompt())
pre_routes = net_connect.send_command(command) 
print(pre_routes)
print()

# make changes #
print()
print(net_connect.find_prompt())
output = net_connect.send_config_from_file(cfg_file)
print(output)
print()

# routing table after changes #
print('routes POST changes')
示例#40
0
#!/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)
# Requires ntc-templates to be installed in ~/ntc-templates/templates
output = net_connect.send_command("show ip int brief", use_textfsm=True)
print(output)
示例#41
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

nxos1 = {
    "host": "nxos1.twb-tech.com",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_nxos",
}

commands = ["logging history size 500"]

net_connect = Netmiko(**nxos1)

print()
print(net_connect.find_prompt())
output = net_connect.send_config_set(commands)
output += net_connect.send_command("copy run start")
print(output)
print()
示例#42
0
#!/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)

# Make configuration changes using an external file
output = net_connect.send_config_from_file("change_file.txt")
print(output)

net_connect.disconnect()
示例#43
0

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',
}

net_connect = Netmiko(**device)

# 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"
示例#44
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

key_file = "/home/gituser/.ssh/test_rsa"

cisco1 = {
    "device_type": "cisco_ios",
    "host": "cisco1.twb-tech.com",
    "username": "******",
    "use_keys": True,
    "key_file": key_file,
}

net_connect = Netmiko(**cisco1)
print(net_connect.find_prompt())
output = net_connect.send_command("show ip arp")
print(output)
示例#45
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

net_connect = Netmiko(
    "cisco1.twb-tech.com",
    username="******",
    password=getpass(),
    device_type="cisco_ios",
)

print(net_connect.find_prompt())
net_connect.disconnect()
示例#46
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

cisco1 = {
    "host": "cisco1.twb-tech.com",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios",
}

net_connect = Netmiko(**cisco1)
command = "show ip int brief"

print()
print(net_connect.find_prompt())
output = net_connect.send_command(command)
net_connect.disconnect()
print(output)
print()
示例#47
0
文件: enable.py 项目: ilique/netmiko
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

password = getpass()

cisco1 = {
    'host': 'cisco1.twb-tech.com',
    'username': '******',
    'password': password,
    'device_type': 'cisco_ios',
    'secret': password,
}

net_connect = Netmiko(**cisco1)
print(net_connect.find_prompt())
net_connect.send_command_timing("disable")
print(net_connect.find_prompt())
net_connect.enable()
print(net_connect.find_prompt())

# Go into config mode
net_connect.config_mode()
print(net_connect.find_prompt())
net_connect.exit_config_mode()
print(net_connect.find_prompt())
net_connect.disconnect()
示例#48
0
from getpass import getpass

my_device = {
    "host": "host.domain.com",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios",
}

"""
Cisco IOS behavior on file delete:

pynet-rtr1# delete flash:/small_file_bim.txt
Delete flash:/test1.txt? [confirm]y
pynet-rtr1
"""

net_connect = Netmiko(**my_device)
filename = "text1234.txt"
cmd = "delete flash:{}".format(filename)

# send_command_timing as the router prompt is not returned
output = net_connect.send_command_timing(cmd, strip_command=False, strip_prompt=False)
if "confirm" in output:
    output += net_connect.send_command_timing(
        "\n", strip_command=False, strip_prompt=False
    )

net_connect.disconnect()
print(output)
示例#49
0
# SNMPv3
from netmiko.snmp_autodetect import SNMPDetect
from netmiko import Netmiko
from getpass import getpass

device = {
    'host': 'cisco1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
}

snmp_key = getpass("Enter SNMP community: ")
my_snmp = SNMPDetect("cisco1.twb-tech.com", snmp_version="v3", user='******',
                     auth_key=snmp_key, encrypt_key=snmp_key, auth_proto="sha",
                     encrypt_proto="aes128")
device_type = my_snmp.autodetect()
print(device_type)

device['device_type'] = device_type
net_connect = Netmiko(**device)
print(net_connect.find_prompt())
示例#50
0
#!/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)
cfg_commands = ['logging buffered 10000', 'no logging console']

# send_config_set() will automatically enter/exit config mode
output = net_connect.send_config_set(cfg_commands)
print(output)

net_connect.disconnect()
示例#51
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

cisco1 = {
    "host": "cisco1.twb-tech.com",
    "username": "******",
    "password": getpass(),
    "device_type": "cisco_ios",
}

net_connect = Netmiko(**cisco1)
command = "show ip int brief"

print()
print(net_connect.find_prompt())
output = net_connect.send_command(command, use_textfsm=True)
net_connect.disconnect()
print(output)
print()
示例#52
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

nxos1 = {
    'host': 'nxos1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'cisco_nxos',
}

cfg_file = 'config_changes.txt'
net_connect = Netmiko(**nxos1)

print()
print(net_connect.find_prompt())
output = net_connect.send_config_from_file(cfg_file)
print(output)
print()

net_connect.save_config()
net_connect.disconnect()
示例#53
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass
import time

cisco1 = {
    'host': 'cisco1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**cisco1)
print(net_connect.find_prompt())
net_connect.write_channel("show ip int brief\n")
time.sleep(1)
output = net_connect.read_channel()
print(output)
net_connect.disconnect()
示例#54
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

device = {
    'host': 'srx1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'juniper_junos',
}

commands = [
    'set system syslog archive size 240k files 3 '
]

net_connect = Netmiko(**device)

print()
print(net_connect.find_prompt())
output = net_connect.send_config_set(commands, exit_config_mode=False)
output += net_connect.commit(and_quit=True)
print(output)
print()

net_connect.disconnect()