Exemple #1
0
def Hardware_Monitoring():
    if DeviceType == 'f5_ltm' or DeviceType == 'f5':
        redispatch(net_connect, device_type='f5_ltm')
        output1 = net_connect.read_channel()
        if '(tmos)' in output1:
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            Fan_Status = net_connect.send_command("show /sys hardware | grep 'Chassis Fan Status' -A 5", delay_factor=5,
                                                  max_loops=10)
            Power_Status = net_connect.send_command("show /sys hardware | grep 'Chassis Power' -A 4", delay_factor=5,
                                                    max_loops=10)
            new_output = str(Fan_Status) + '\n\n' + str(Power_Status)
        else:
            net_connect.send_command("tmsh", delay_factor=5, max_loops=10)
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            Fan_Status = net_connect.send_command("show /sys hardware | grep 'Chassis Fan Status' -A 5",
                                                  delay_factor=5, max_loops=10)
            Power_Status = net_connect.send_command("show /sys hardware | grep 'Chassis Power' -A 4",
                                                    delay_factor=5, max_loops=10)
            new_output = str(Fan_Status) + '\n\n' + str(Power_Status)
        if 'down' in new_output or 'Down' in new_output or 'error' in new_output or 'Error' in new_output or 'bad' in new_output or 'Bad' in str(
                new_output) or 'FAULTY' in str(new_output) or 'Fail' in str(new_output) or 'fail' in str(
                new_output) or 'Invalid' in str(new_output) or 'invalid' in str(new_output):
            print('Issue in Device end')
            Status = 'Issue in Device end, Manual action required'
            decision = 2
        else:
            Status = 'No issue found'
            decision = 1
        Details = new_output.encode('ascii', 'ignore')
        # response_content = 'Utilization Summary: ' + Status + '\n Utilization Details:  +' + Details + '%'
        response_content = 'Device Clock: ' + str(clock) + '\n Hardware Status: ' + str(
            Status) + '\n Hardware Summary:' + str(new_output)
    return response_content
def main():

    dev = {
        'device_type': 'vyos',
        'ip': '172.17.143.1',
        'username': '******',
        'password': '******',
        'port': 22
    }

    saos = {"ip": "172.17.143.3", "user": "******", "passwd": "pass"}

    # logger for dbg
    # logging.basicConfig(filename="test.log", level=logging.DEBUG)
    # logger = logging.getLogger("netmiko")

    # connect to vrouter
    net_connect = ConnectHandler(**dev)
    print(net_connect.find_prompt())

    # jump to saos from vrouter ... MGMT vrf is device specific config
    cmd = f"ssh {saos['user']}@{saos['ip']} routing-instance MGMT"
    try:
        output = net_connect.send_command_expect(cmd, expect_string="Password")
        print(output)
    except:
        try:
            net_connect.send_command_expect(cmd, expect_string="(yes/no)?")
            output = net_connect.send_command_expect('yes',
                                                     expect_string="Password")
            print(output)
        except:
            print("Error connecting to SAOS")
            net_connect.disconnect()
            return

    output = net_connect.send_command_timing(saos['passwd'])
    print(output)

    print("Doing redispatch to dev type ciena_saos")
    try:
        redispatch(net_connect, device_type='ciena_saos')
    except:
        print(
            "ERROR redispatching, SAOS prompt not found ... verify login credentials"
        )
        net_connect.disconnect()
        return

    net_connect.set_base_prompt(pri_prompt_terminator=">",
                                alt_prompt_terminator="*>")

    cmd = "port show status"
    print("sending command")
    # import ipdb; ipdb.set_trace() # dbg
    res = net_connect.send_command(cmd, auto_find_prompt=False)
    print(res)

    net_connect.disconnect()
    return
Exemple #3
0
def Interface_down(Interface):
    if DeviceType == 'f5_ltm' or DeviceType == 'f5':
        redispatch(net_connect, device_type='f5_ltm')
        output1 = net_connect.read_channel()
        if '(tmos)' in output1:
            new_output = net_connect.send_command("show net interface " + Interface + ' ', delay_factor=5, max_loops=10)
            decision = 1
        else:
            net_connect.send_command("tmsh", delay_factor=5, max_loops=10)
            new_output = net_connect.send_command("show net interface " + Interface + ' ', delay_factor=5, max_loops=10)
            decision = 2
        # Details = new_output.encode('ascii','ignore')
        if 'up' in new_output:
            # print('Processor_percentage is high which is ' + str(Processor_percentage) + ' ')
            Load_percentage_Status = 'Interface status Up -- Details are ' + new_output
            decision = 1
        elif 'down' in new_output:
            Load_percentage_Status = 'Interface status Down -- Detaills are ' + new_output
            decision = 2
        else:
            Load_percentage_Status = 'Interface status unknown -- Please check the device'
            decision = 2
        Details = new_output.encode('ascii', 'ignore')
        response_content = Load_percentage_Status
    return response_content, decision
 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
Exemple #5
0
def close_cross_connection(nc):
    time.sleep(1)
    main_logger.info(nc.write_channel("exit\n"))
    time.sleep(1)
    main_logger.info(nc.write_channel("exit\n"))
    time.sleep(1)
    redispatch(nc, device_type='versa')
    main_logger.info(nc.find_prompt())
Exemple #6
0
    def __set_config(self, net_connect=None, device_type='cisco') -> str:
        if device_type != consts.MF_AUTODETECT:
            netmiko.redispatch(net_connect, device_type=device_type)

        # Now just do your normal Netmiko operations
        output = net_connect.send_config_set(
            enter_config_mode=True,
            exit_config_mode=True,
            config_commands=self.cos.command_list,
        )
        return output
Exemple #7
0
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
Exemple #8
0
def Interface_Utilization(Interface):
    if DeviceType == 'f5' or DeviceType == 'f5_ltm':
        redispatch(net_connect, device_type='f5_ltm')
        output1 = net_connect.read_channel()
        if '(tmos)' in output1:
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            TMM = net_connect.send_command("show net interface " + Interface, delay_factor=5, max_loops=100)
            decision = 1
        else:
            net_connect.send_command("tmsh", delay_factor=5, max_loops=10)
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            TMM = net_connect.send_command("show net interface " + Interface, delay_factor=5, max_loops=100)
            decision = 1
        # Details = new_output.encode('ascii','ignore')
        response_content = 'Device Clock :' + clock + '\nUtilization Summary: \n ' + str(TMM)
    return response_content, decision
    def reset_cfg(self, task):
        task.host.open_connection("netmiko", None)
        conn = task.host.connections["netmiko"].connection
        conn.find_prompt()
        print("Connected to terminal server or KVM host...")

        conn.write_channel(f"telnet localhost {task.host['console_port']}")
        time.sleep(0.5)
        conn.write_channel("\r\n")
        time.sleep(0.5)

        for k, v in task.host["end_host_args"].items():
            if k != "device_type":
                setattr(conn, k, v)

        conn.telnet_login()
        redispatch(conn, task.host["end_host_args"]["device_type"])
        conn.find_prompt()
        conn.enable()
        print(f"Redispatched to {task.host}")

        cfg_check = conn.send_command(
            f"dir {task.host['filesystem']}:/{task.host['default_cfg']}",
            strip_prompt=False,
            strip_command=False,
        )
        if "No such file" in cfg_check:
            print(f"{task.host['default_cfg']} is not in {task.host['filesystem']}")
            raise ValueError(f"Default config file not found")

        cfg_replace = conn.send_command(
            f"{task.host['default_cfg_cmd']} {task.host['filesystem']}:/{task.host['default_cfg']}",
            strip_prompt=False,
            strip_command=False,
        )
        if "Rollback failed." in cfg_replace:
            failed = True
            print(f"{task.host} configuration replace failed. Output: {cfg_replace}")
        else:
            failed = False
            conn.save_config()
            print(f"{task.host} configuration replaced and config saved")

        return Result(host=task.host, result=cfg_replace, changed=True, failed=failed)
def cleanBoot():
    moxa = netmiko.ConnectHandler(**moxaTermServer)
    redispatch(moxa, device_type='cisco_ios'
               )  #redispatch connection to use Cisco commands using Netmiko
    output = moxa.find_prompt()
    print(output)
    moxa.enable()
    print("[Status]: Checking Version...")
    version = moxa.send_command('show version',
                                use_textfsm=True)  #uses textfsm for parsing
    version = version[0]
    if version[
            'running_image'] == CURRENT_VERSION:  #current version termination
        print("[TASK]: Current CISCO IOS found - " + version['running_image'])
        print('[Success]: CISCO IOS PreCheck - Complete!')
        moxa.disconnect()
    else:  #Cisco version out of date
        print("[TASK]: CISCO IOS found: " + version['running_image'])
        print("[Status]: CISCO IOS Upgrade Required")
        moxa.config_mode()
        moxa.send_config_set(mgmt_cmd)
        moxa.enable()
        if moxa.check_enable_mode() == True:
            moxa.send_command_timing('del /f /r *')
            print('[Status]: Cisco IOS Updating.')
            output = moxa.send_command(copy_cmd, delay_factor=20)
            print(output)
            if output[-1] != ')':
                print('File Transfer Failed.')
                moxa.disconnect()
                cleanBoot()
        print('[Task]: CISCO IOS Updated.')
        output = moxa.send_command('wr erase')
        if 'Continue?' in output:
            moxa.send_command_timing('\n')
        output = moxa.send_command_timing('reload')
        if 'yes/no' in output:
            output = moxa.send_command_timing(no_cmd)
        if 'confirm' in output:
            moxa.send_command_timing('\n')
        print('[Status]: Reboot Initiated')
        moxa.disconnect()
        initialCheck()
Exemple #11
0
def After_Intermediate_Server_Login(ais_id, ais_ip, ais_name, ais_cfile):
    net_connect.write_channel('shebin')
    net_connect.write_channel('\n')
    redispatch(net_connect, device_type='cisco_ios')
    console.print(
        '[bold][blue] Connecting to device with Sol_Id-> [/bold][/blue]' +
        ais_id,
        style='bold purple')
    console.print('[bold][blue] Branch-> [/bold][/blue]' + ais_name,
                  style='bold purple')
    console.print('[bold][blue] IP-> [/bold][/blue]' + ais_ip,
                  style='bold purple')
    console.print(Panel('Connected ! :smiley: '), style='bold green')
    console.print(Panel('[yellow][bold]Pushing configuration to the device'))
    net_connect.send_config_from_file(config_file=ais_cfile,
                                      enter_config_mode=True)
    console.print(
        Panel('Configuration Push Successfully !!!', style='bold green'))
    table.add_row(ais_id, ais_ip, config_success)
Exemple #12
0
def do_cross_connection(vd_ssh_dict, dev_dict):
    global cpe_logger
    netconnect = make_connection(vd_ssh_dict)
    netconnect.write_channel("ssh " + dev_dict["username"] + "@" +
                             dev_dict["ip"] + "\n")
    time.sleep(5)
    output = netconnect.read_channel()
    main_logger.debug(output)
    if 'assword:' in output:
        netconnect.write_channel(dev_dict["password"] + "\n")
        time.sleep(5)
        output = netconnect.read_channel()
        main_logger.debug(output)
    elif 'yes' in output:
        print "am in yes condition"
        netconnect.write_channel("yes\n")
        time.sleep(5)
        output = netconnect.read_channel()
        main_logger.debug(output)
        time.sleep(1)
        netconnect.write_channel(dev_dict["password"] + "\n")
        time.sleep(5)
        output = netconnect.read_channel()
        main_logger.debug(output)
    else:
        # cpe_logger.info(output)
        return "VD to CPE " + dev_dict["ip"] + "ssh Failed."
    # netconnect.write_channel("cli\n")
    # time.sleep(2)
    # output1 = netconnect.read_channel()
    # main_logger.info(output1)
    # time.sleep(2)
    try:
        main_logger.debug("doing redispatch")
        redispatch(netconnect, device_type='versa')
    except ValueError as Va:
        main_logger.info(Va)
        main_logger.info("Not able to get router prompt from CPE" +
                         dev_dict["ip"] + " CLI. please check")
        return "Redispatch not Success"
    time.sleep(2)
    return netconnect
Exemple #13
0
def Memory_Utilization():
    if DeviceType == 'f5_ltm' or DeviceType == 'f5':
        redispatch(net_connect, device_type='f5_ltm')
        output1 = net_connect.read_channel()

        if '(tmos)' in output1:
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            TMM = net_connect.send_command("show sys memory | grep 'TMM Memory Used'", delay_factor=5, max_loops=10)
            Other = net_connect.send_command("show sys memory | grep 'Other Memory Used'", delay_factor=5, max_loops=10)
            Swap = net_connect.send_command("show sys memory | grep 'Swap Used '", delay_factor=5, max_loops=10)
            # decision = 1
        else:
            net_connect.send_command("tmsh", delay_factor=5, max_loops=10)
            clock = net_connect.send_command("show sys clock ", delay_factor=5, max_loops=100)
            TMM = net_connect.send_command("show sys memory | grep 'TMM Memory Used'", delay_factor=5, max_loops=10)
            Other = net_connect.send_command("show sys memory | grep 'Other Memory Used'", delay_factor=5, max_loops=10)
            Swap = net_connect.send_command("show sys memory | grep 'Swap Used '", delay_factor=5, max_loops=10)
            # decision = 1
        # Details = new_output.encode('ascii','ignore')
        TMM_Load = re.findall('[0-9]+ +([0-9]+)', str(TMM))
        Other_Load = re.findall('[0-9]+ +([0-9]+)', str(Other))
        Swap_Load = re.findall('[0-9]+ +([0-9]+)', str(Swap))
        TMM_Vaue = int(TMM_Load[0])
        Other_Vaue = int(Other_Load[0])
        Swap_Vaue = int(Swap_Load[0])
        if TMM_Vaue >= 70 or Other_Vaue >= 70 or Swap_Vaue >= 70:
            print('Utilization is high')
            Status = 'Utilization is high'
            decision = 2
        else:
            Status = 'Utilization is Low'
            decision = 1
        # Details = new_output.encode('ascii','ignore')
        response_content = 'Device Clock :' + clock + '\nUtilization Summary: \n ' + str(
            Status) + '\nUtilization Details:\n TMM Value ' + str(
            TMM_Vaue) + '%\n Other Value :' + str(Other_Vaue) + '% \n Swap Value: ' + str(Swap_Vaue)

    # response_content ='Device clock :  '+clock+'\nUtilization Summary: \n '+str(Status)+'\n Input load is '+str(Input_Load_percent)+'%\n Output Load is'+str(Output_Load_percent)+'\nUtilization Details:\n +'+str(validate)+'%'
        # print(response_content))
    return response_content, decision
Exemple #14
0
class main:
    """
    This shows the set of commands to connect to a Terminal Server and perform SSH to a Huawei NE device.
    """

    #THIS METHOD WILL CONNECT TO A TERMINAL SERVER

    SERVER_IP = '10.103.23.133'
    USERNAME = '******'
    username = '******'
    router_ip = '10.112.116.1'

    jumpserver = {
        'device_type': 'terminal_server',
        'ip': SERVER_IP,
        'username': USERNAME,
        'password': getpass(),
        "global_delay_factor": 1
    }

    net_connect = ConnectHandler(**jumpserver)
    print(net_connect.find_prompt())
    time.sleep(3)
    net_connect.write_channel('ssh {}@{}'.format(username, router_ip))
    print(net_connect.find_prompt())
    net_connect.write_channel(getpass())

    redispatch(net_connect, device_type='huawei')
    net_connect.username(username)
    net_connect.ip(router_ip)
    net_connect.password(getpass())
    net_connect.global_delay_factor(1)
    net_connect.find_prompt()

    output = net_connect.send_command("display version")
    print(output)
    net_connect.disconnect()
net_connect = ConnectHandler(**device)
print(net_connect.find_prompt())

# Update the password as the terminal server uses different credentials
net_connect.password = term_serv_pass
net_connect.secret = term_serv_pass
# Telnet to the terminal server
command = f"telnet {terminal_server_ip}\n"
net_connect.write_channel(command)
# Use the telnet_login() method to handle the login process
net_connect.telnet_login()
print(net_connect.find_prompt())

# Made it to the terminal server (this terminal server is "cisco_ios")
# Use redispatch to re-initialize the right class.
redispatch(net_connect, device_type="cisco_ios")
net_connect.enable()
print(net_connect.find_prompt())

# Now connect to the end-device via the terminal server (Juniper SRX2)
net_connect.write_channel("srx2\n")
# Update the credentials for SRX2 as these are different.
net_connect.username = "******"
net_connect.password = srx2_pass
# Use the telnet_login() method to connect to the SRX
net_connect.telnet_login()
redispatch(net_connect, device_type="juniper_junos")
print(net_connect.find_prompt())

# Now we could do something on the SRX
output = net_connect.send_command("show version")
c.write_channel(f'open /{our_lab.id}/{xr_node.id}/0\r')

c.write_channel('\r\n')
sleep(1)
c.write_channel('\r\n')
sleep(1)

# router login
# this makes an assumption that it's required to login

#c.write_channel(LAB_USERNAME + '\r')
#c.write_channel(LAB_PASSWORD + '\r')
logging.info("Sending a few carriage returns")
#c.write_channel('\r\n\r\n\r\n')
# switch to Cisco XR mode
netmiko.redispatch(c, device_type='cisco_ios')
c.find_prompt()

# get the list of interfaces
c.enable()
result = c.send_command('show run')
print(result)

# # create the keys
# result = c.send_command('crypto key generate rsa',
#                         expect_string='How many bits in the modul us \[2048\]\: ')
# print(result)

# # send the key length
# c.write_channel('2048\n')
Exemple #17
0
# 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")
        time.sleep(1)
        output = net_connect.read_channel()

    # Search for password pattern / send password
    if "Password" in output:
        net_connect.write_channel(net_connect.password + "\r\n")
        time.sleep(0.5)
        output = net_connect.read_channel()
        # Did we successfully login
        if ">" in output or "#" in output:
            break

    net_connect.write_channel("\r\n")
    time.sleep(0.5)
    i += 1

# We are now logged into the end device
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type="cisco_ios")

# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")
Exemple #18
0
import time
from netmiko import ConnectHandler, redispatch

zpe_username = "******"
zpe_password = "******"
zpe_hostname = "server_ip"
console_username = zpe_username
console_server = {
    "host": zpe_hostname,
    "username": console_username,
    "password": zpe_password,
    "device_type": "terminal_server",
}
print("ssh " + console_username + "@" + zpe_hostname)

net_connect = ConnectHandler(**console_server)
print(net_connect.find_prompt())
net_connect.write_channel("ssh username@router\n")
time.sleep(1)
net_connect.read_channel()
net_connect.write_channel("Router_password\n")
time.sleep(1)
net_connect.read_channel()
redispatch(net_connect, device_type='alcatel_sros')
command_output = net_connect.send_command('/configure router policy-options')
Exemple #19
0
def off(net_connect):
    redispatch(net_connect, device_type='terminal_server')
def config_worker(param):

    netmiko_delay = 0.1

    client = ClientLibrary(
        param["virl_controller"],
        param["virl_username"],
        param["virl_password"],
        ssl_verify=False,
    )
    client.wait_for_lld_connected()

    with print_lock:
        print(f"{param['hostname']}: Connected to VIRL")

    our_lab = client.find_labs_by_title(param["lab_id"])[0]
    our_node = our_lab.get_node_by_label(param["hostname"])

    with print_lock:
        print(
            f"{param['hostname']}: Identified lab and device: /{our_lab.id}/{our_node.id}/0"
        )

    c = netmiko.ConnectHandler(
        device_type="terminal_server",
        host=param["virl_controller"],
        username=param["virl_username"],
        password=param["virl_password"],
    )

    with print_lock:
        print(f"{param['hostname']}: Connected to terminal server")

    c.write_channel("\r\n")
    time.sleep(1)
    c.write_channel("\r\n")
    time.sleep(1)

    c.write_channel(f"open /{our_lab.id}/{our_node.id}/0\r")

    c.write_channel("\r\n")
    time.sleep(1)
    c.write_channel("\r\n")
    time.sleep(1)
    c.write_channel("\r\n")
    time.sleep(1)
    c.write_channel("\r\n")

    with print_lock:
        print(f"{param['hostname']} : Switching to IOS interpreter")
    try:
        netmiko.redispatch(c, device_type="cisco_ios")
    except Exception as e:
        with print_lock:
            print(
                f"{param['hostname']} : Failed to switch to IOS interpreter. {e}"
            )
    c.find_prompt()
    # c.enable()

    with print_lock:
        print(f"{param['hostname']} : Preparing config")
    try:
        with open("swtemplate.j2", "r") as f:
            template = jinja2.Template(f.read())
        config_to_send = template.render(device=param).split("\n")
    except:
        with print_lock:
            print(f"{param['hostname']} : Failed to prepare config")

    with print_lock:
        print(f"{param['hostname']} : Sending config")

    try:
        # I have found that console messages can upset netmiko,
        # so turn them off with a timed command
        c.send_command_timing("enable", netmiko_delay)
        c.send_command_timing("conf t", netmiko_delay)
        c.send_command_timing("no logging console", netmiko_delay)
        c.send_command_timing("end", netmiko_delay)
        time.sleep(1)
        c.write_channel("\r\n")
        c.find_prompt()
        c.send_config_set(config_to_send)
        with print_lock:
            print(f"{param['hostname']} : Config sent")

    except Exception as e:
        with print_lock:
            print(f"{param['hostname']} : Error, send config failed. {e}")
Exemple #21
0
def show_to_txt(namepass, command):
    b = len(namepass)
    d = len(command)

    jumpserver = {
        "device_type": "terminal_server",  ##1
        "ip": "192.168.32.10",  ##2
        "username": "******",  ##3
        "password": "******",  ##4
        "secret": "f**k"  ##4
    }

    net_connect = ConnectHandler(**jumpserver)
    # Manually handle interaction in the Terminal Server (fictional example, but
    # hopefully you see the pattern)
    time.sleep(3)
    net_connect.write_channel("\n")
    time.sleep(1)
    output = net_connect.read_channel()
    # Should hopefully see the terminal server prompt
    #print(output)

    for j in range(1, b):
        print('Now is checking ' + namepass[j][1] + ',the ip address is ' +
              namepass[j][6])

        # Login to end device from terminal server
        net_connect.write_channel("telnet " + namepass[j][6] + "\n")
        time.sleep(3)

        # Manually handle the Username and Password
        max_loops = 5
        i = 1
        while i <= max_loops:
            output = net_connect.read_channel()

            if 'sername:' in output:
                net_connect.write_channel(namepass[j][7] + '\n')
                time.sleep(1)
                output = net_connect.read_channel()

            # Search for password pattern / send password
            if 'assword:' in output:
                net_connect.write_channel(namepass[j][8] + '\n')
                time.sleep(1)
                output = net_connect.read_channel()
                # Did we successfully login

            if '>' in output:
                net_connect.write_channel('enable\n')
                time.sleep(1)
                output = net_connect.read_channel()
                if 'assword:' in output:
                    net_connect.write_channel(namepass[j][9] + '\n')
                    time.sleep(1)
                    output = net_connect.read_channel()
                if '#' in output:
                    break
            elif '#' in output:
                break

            net_connect.write_channel('\n')
            time.sleep(1)
            i += 1

        # We are now logged into the end device
        # Dynamically reset the class back to the proper Netmiko class
        redispatch(net_connect, device_type='cisco_ios')  #
        #net_connect.send_command('show version')

        write_file = open(namepass[j][1] + '_' + date + '.txt', 'w')  #模式为追加

        for n in range(0, d):
            print(command[n][1], file=write_file)
            print("\n", file=write_file)

            output = net_connect.send_command(command[n][1])

            print(output, file=write_file)
            print("\n=============================================\n",
                  file=write_file)
        write_file.close()
        """
        net_connect.write_channel("ssh [email protected]\n")    #连接远程机器,必须得带回车
        time.sleep(3)                                                 #必须得等待几秒,否则读取不到返回
        result = net_connect.read_channel()                    #读取返回结果
        if 'assword' in result:
            net_connect.write_channel("password\n")     #输入密码
            time.sleep(5)
        """

    net_connect.disconnect()
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
Exemple #23
0
    )
    output += net_connect.send_command_timing(
        password, strip_prompt=False, strip_command=False
    )
    if debug:
        print(">>>>")
        print(output)
        print(">>>>")

    prompt = net_connect.find_prompt()
    if "arista4" not in prompt:
        raise ValueError(f"Expecting 'arista4' in prompt: {prompt}")

    # Use redispatch to switch the Netmiko class
    print("\nUse redispatch to switch the class.")
    redispatch(net_connect, device_type="arista_eos")
    print(f"Current class: {str(net_connect)}")

    if "AristaSSH" not in str(net_connect):
        raise ValueError(f"Expecting AristaSSH class at this point: {str(net_connect)}")

    # Exit Arista device
    print("\nExit from 'arista4'")
    output = net_connect.send_command_timing("exit\n")

    prompt = net_connect.find_prompt()
    if debug:
        print(f"\nCurrent prompt: {prompt}")
    if "cisco3" not in prompt:
        raise ValueError(f"Expecting 'cisco3' in prompt: {prompt}")
Exemple #24
0
# 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')
        time.sleep(1)
        output = net_connect.read_channel()

    # Search for password pattern / send password
    if 'Password' in output:
        net_connect.write_channel(net_connect.password + '\r\n')
        time.sleep(.5)
        output = net_connect.read_channel()
        # Did we successfully login
        if '>' in output or '#' in output:
            break

    net_connect.write_channel('\r\n')
    time.sleep(.5)
    i += 1

# We are now logged into the end device 
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')

# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")
Exemple #25
0
def Packet_Loss():
    if DeviceType == 'f5':
        try:
            redispatch(net_connect, device_type='f5')
            hostname = net_connect.read_channel()
            if '(tmos)' not in hostname:
                net_connect.send_command('tmsh', delay_factor=5, max_loops=1000)
            # hostname = net_connect.send_command('show run | i hostname')
            devicename = re.findall('@\(([A-Za-z0-9]+)\)',str(hostname))
            Clock = net_connect.send_command("show sys clock", delay_factor=5, max_loops=1000)
            Uptime = net_connect.send_command("run /util bash -c uptime", delay_factor=5, max_loops=1000)
            Last_Config = net_connect.send_command("show run | in Last configuration change", delay_factor=5,max_loops=1000)
            CPU_LOAD = net_connect.send_command("show process cpu | i utilization", delay_factor=5, max_loops=10)
            Memory_Util = net_connect.send_command("show memory statistics", delay_factor=5, max_loops=10)
            uptime_list = re.findall('([0-9]+)', str(Uptime))
            print(uptime_list)
            if int(uptime_list[0]) == 0 and int(uptime_list[1]) == 0 and int(uptime_list[2]) == 0 :
                Uptime_Status = 'NotNormal'
            else:
                Uptime_Status = 'Normal'
            Last_Config_details = re.findall('at ([0-9:A-Za-z ]+) by', str(Last_Config))
            print(Last_Config_details)
            date_time_obj_time = datetime.datetime.strptime(str(Last_Config_details[0]), '%H:%M:%S %Z %a %b %d %Y')
            date_time_obj_time1 = datetime.datetime.strptime(str(Clock), '%H:%M:%S.%f %Z %a %b %d %Y')
            date_time_last_config = date_time_obj_time1-date_time_obj_time
            date_time_last_config_main = str(date_time_last_config).split(' ')
            if int(date_time_last_config_main[0]) >0:
                Last_Config_change = 'Normal'
            else:
                Last_Config_change = 'NotNormal'
            CPU_Load = re.findall('seconds: ([0-9]+)', str(CPU_LOAD))
            Load = int(CPU_Load[0])
            if Load >= 70:
                print('Utilization is high')
                CPU_Status = 'NotNormal'
            else:
                CPU_Status = 'Normal'
            print(CPU_Status)
            Processor = re.findall('Processor +[0-9A-Za-z]+ +([0-9]+) +([0-9]+)', str(Memory_Util))
            Processor_percentage = int(Processor[0][1]) * 100 / int(Processor[0][0])
            Status = ''
            print(Processor_percentage)
            if Processor_percentage >= 70:
                Memory_Load = 'NotNormal'
            else:
                Memory_Load = 'Normal'
            print(Memory_Load)
            # Uptime_Status = 'n'
            if Uptime_Status == 'Normal' and Last_Config_change == 'Normal' and CPU_Status == 'Normal' and Memory_Load == 'Normal':
                # net_connect.send_command("clear counters", expect_string="\[confirm\]", delay_factor=5, max_loops=1000)
                # net_connect.send_command('\n', expect_string="#", delay_factor=5, max_loops=1000)
                # time.sleep(5)
                Interface_Details = '\n\nInterface details:\n' + '~' * 100 + '\n'
                Interface_Details += net_connect.send_command('show interfaces | inc reliability| errors| line| drops', delay_factor=5, max_loops=1000)
                value = Interface_Details.split('resets')
                # print(value)
                interface = []
                utilization = []
                Reliability = []
                errors = []
                CRC = []
                drops1 = []
                frame = []
                collisions = []
                for i in value:
                    if 'administratively down' not in str(i) and 'notconnect' not in str(i) and 'disabled' not in str(i) and len(i) >= 100:
                        line_status = re.findall('is ([a-zA-Z]+)', str(i))
                        drops = re.findall('Input queue: \d\/\d+\/([\d])+', str(i))
                        frames = re.findall('([0-9]+) frame', str(i))
                        crc = re.findall('([0-9]+) CRC', str(i))
                        colli = re.findall('([0-9]+) collisions', str(i))
                        for j in line_status:
                            if 'down' in str(j):
                                val = i.split(('\n'))
                                val = str(val[2])
                                interface.append(val.split(' ')[0])
                                print(i.split('\n'))
                                print(interface)
                        txload = re.findall('txload ([0-9]+)', str(i))
                        rxload = re.findall('rxload ([0-9]+)', str(i))
                        print(txload)
                        print(rxload)
                        time.sleep(2)
                        print(len(i))
                        txload_percentage = int(txload[0]) * 100 / int(255)
                        rxload_percentage = int(rxload[0]) * 100 / int(255)
                        if txload_percentage >= 70 or rxload_percentage >= 70:
                            # print('Processor_percentage is high which is ' + str(Processor_percentage) + ' ')
                            utilization.append(i.split(' ')[0])
                        input_errors = re.findall('([0-9]+) input', str(i))
                        output_errors = re.findall('([0-9]+) output', str(i))
                        if int(input_errors[0]) > 0 or int(output_errors[0]) > 0:
                            print(i)
                            val = i.split(('\n'))
                            val = str(val[2])
                            errors.append(val.split(' ')[0])
                        # print(len(colli))
                        if int(frames[0]) > 0:
                            val = i.split(('\n'))
                            val = str(val[2])
                            frame.append(val.split(' ')[0])
                        if int(crc[0]) > 0:
                            val = i.split(('\n'))
                            val = str(val[2])
                            CRC.append(val.split(' ')[0])
                        # print(len(colli))
                        if len(colli) != 0:
                            if int(colli[0]) > 0:
                                val = i.split(('\n'))
                                val = str(val[2])
                                collisions.append(val.split(' ')[0])
                        if int(drops[0]) > 1:
                            val = i.split(('\n'))
                            val = str(val[2])
                            drops1.append(val.split(' ')[0])
                if len(interface) != 0 or len(utilization) != 0 or len(Reliability) != 0 or len(errors) != 0 or len(CRC) != 0 or len(frame) != 0 or len(collisions) != 0 or len(drops1) != 0:
                    print('packet loss happening')
                    issue = 'Manual Action Required'
                else:
                    print('packet loss not happening')
                    issue = 'Device is working fine'
                response_content = issue +'\nDevice name: ' + str(devicename) + ' , IP: ' + str(ip) + '\n Device Current Time: \n' +str(Clock)+ '\nUptime: \n'+ str(Uptime) +'\n Last Config Changed: \n'+str(Last_Config)+'\nCPU Load: \n'+str(CPU_LOAD)+'\nMemory Utilization: \n'+str(Memory_Util)+'\nInterface Details: \n'+str(Interface_Details)
            else:
                response_content = 'Device name: ' + str(devicename) + ' , IP: ' + str(ip) + '\n Device Current Time: \n' + str(Clock) + '\nUptime: \n' + str(Uptime) + '\n Last Config Changed: \n' + str(Last_Config) + '\nCPU Load: \n' + str(CPU_LOAD) + '\nMemory Utilization: \n' + str(Memory_Util)
        except Exception :
            response_content = 'Manual Action Required'
        return response_content
Exemple #26
0
	print(net_connect.find_prompt())
	print(f"\n{'*'*10}Connected to the Jump host{'*'*10}")
	print(f"\n{'~'*50}\n2. Connecting to the Dest Router\n{'~'*50}")
	print(net_connect.find_prompt(),end='')
	net_connect.write_channel(f'ssh -l {router_user} {router_ip}\n')
	time.sleep(2)
	output = net_connect.read_channel()
	print(output)
	if 'Password' in output:
		print("**Received Password Prompt, Entering password**")
		net_connect.write_channel(router_password+'\n')
		time.sleep(2)

		print(f"\n{'~'*50}\nDestination Device Prompt\n{'~'*50}\n")
		print(net_connect.find_prompt())
		cmds = ['show ip int brie','show ip route','show users']

		redispatch(net_connect,device_type='cisco_ios')
		for cmd in cmds:
			print(f"\n{'~'*50}\nIn {net_connect.find_prompt()} Executing the Command: {cmd}\n{'~'*50}")
			router_output = net_connect.send_command(cmd)
			print(router_output)
	else:
		print("Unable to get output from the End Device")

except ssh_exception.AuthenticationException:
	print("Jump host Auth failed")
except ssh_exception.NetmikoTimeoutException:
	print("Jump Host not reachable")

print(f"\n{'#'*50}\nFinished Executing Script\n{'#'*50}")
jumperbox = {
    "device_type": "linux",
    'host': '192.168.1.1',
    'username': '******',
    'password': '******',
}

net_connect = netmiko.ConnectHandler(**jumperbox)
print("SSH prompt: {}".format(net_connect.find_prompt()))
net_connect.write_channel("ssh -l admin 10.2.2.2\n")  #### or a ssh 10.30.1.11
time.sleep(6)
output = net_connect.read_channel()
print(output)
if 'ssword' in output:
    net_connect.write_channel('admin\n')
output = net_connect.read_channel()

# Verify you logged in successfully
print(output)
time.sleep(1)
netmiko.redispatch(net_connect, device_type="huawei")
output2 = net_connect.send_command('dis ver')
print(output2)
config_commands = [
    'interface 10GE1/0/36',
    'description netmiki_test',
    'commit',
]
output3 = net_connect.send_config_set(config_commands)
print(output3)
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