示例#1
0
    async def initialize_connection(cls, device_id, conf_access_id):
        self = SSHConnectionHandler()
        self.device_model = await sync_to_async(
            DeviceModel.objects.get, thread_sensitive=True)(id=device_id)
        self.conf_model = await sync_to_async(
            ConfigParameters.objects.get,
            thread_sensitive=True)(id=conf_access_id)

        login_params = dict(ip=self.device_model.hostname,
                            username=self.conf_model.login_username,
                            password=self.conf_model.login_password,
                            secret=self.conf_model.login_password)

        try:
            self.connection = netmiko.BaseConnection(**login_params)
            self.connection.set_terminal_width('511')
            self.connection.write_channel('terminal length 0\n')

            logging.warning(
                f'Successfully opened SSH session with {self.device_model.hostname}:22.'
            )

            return self
        except Exception as e:
            logging.warning(e)
示例#2
0
def connex(WLCclass):
    try:
        conn = nm.BaseConnection(ip=wlcClass.device_host_ip,
                                 username=wlcClass.device_user,
                                 password=wlcClass.device_pass,
                                 session_log=f"ssh_session_logfile.txt",
                                 session_log_file_mode="write",
                                 session_log_record_writes="True")
    except nm.NetMikoTimeoutException as err:
        print("*********************************************************\n")
        print("* ERROR: Connection to {} timed-out.     \n".format('wlc'))
        print("* Skipping this entry for now...                              ")
        print("*********************************************************\n")
    else:
        connIsAlive = conn.is_alive()
        return conn
示例#3
0
def send_renameCmds(cli_commands):
    """ Here we send the contents of the cli_commands \n""" \
    """ list to the WLC via Netmiko active connection \n""" \
    """ If conn is dead, we will open a new one.      \n"""
    global conn
    global connArgs
    global savedCredentials
    is_connActive = False
    is_connActive = conn.is_alive()
    while is_connActive is False:
        print("The SSH session to the WLC has closed. \n")
        if savedCredentials is True:
            print(connArgs)
            print("Reopeneing connection using saved info above...")
            conn = nm.BaseConnection(ip=connArgs["ip"],
                                     username=connArgs["user"],
                                     password=connArgs["pass"])
            getPrompt = conn.find_prompt()
            is_connActive = conn.is_alive()
        else:
            print("Error")
    conn.send_config_set(config_commands=cli_commands,
                         enter_config_mode=False,
                         cmd_verify=False,
                         exit_config_mode=False)
    conn.disconnect()
    print("-------------------------------------------\n" \
          "Commands sent and logfile is printed below \n" \
          "The logfile is also save locally in the    \n" \
          "current dir as ssh_session_logfile.txt     \n" \
          "-------------------------------------------\n")
    with open("ssh_session_logfile.txt") as log:
        read = log.readlines()
        for line in read:
            print(line)
    close = input("-------------------------------------------\n" \
          "Script Complete. SSH session closed and    \n" \
          "The logfile is also saved locally in the   \n" \
          "current dir as ssh_session_logfile.txt     \n" \
          "---------Press Ctrl-C to Exit--------------\n")
示例#4
0
def api_connex(connArgs, conn_info):
    import netmiko as nm
    import time
    attempts = 0
    expPrompt = False
    start1 = time.perf_counter()
    try:
        net_connect = nm.BaseConnection(
            ip=conn_info[0],
            username=connArgs["user"],
            password=connArgs["pass"],
            session_log="ssh_session_logfile{}.txt".format(conn_info[2]),
            session_log_file_mode="write",
            session_log_record_writes="True")
    except nm.NetMikoTimeoutException:
        print("*********************************************************\n")
        print("* ERROR: Connection to {} timed-out.     \n".format(
            conn_info[0]))
        print("* Skipping this entry for now...                              ")
        print("*********************************************************\n")
        #continue
    except nm.NetMikoAuthenticationException:
        print("*********************************************************\n")
        print("* ERROR: Authentication Error Occured on {} using {}\n".format(
            conn_info[0], connArgs["user"]))
        print("* Skipping this entry for now...\n")
        print("*********************************************************\n")
        #continue
    else:
        connIsAlive = net_connect.is_alive()
        stop1 = time.perf_counter()
        print("Elapsed time for connection(secs): ", stop1 - start1)
        if connIsAlive is True:
            print("*********************************************************")
            print(
                "* Dino | SSH ConneX Success                                     *"
            )
            print("*********************************************************")
            print("*                                                       *")
            getPrompt = net_connect.find_prompt()
            print("* We need to validate if this is the intended device    *")
            print("*                                                       *")
            print(f"* Device CLI prompt : {getPrompt}                     \n")
            print("*                                                       *")
        while expPrompt is False:
            choice = 0
            print("*         [1] Yes | [2] No or Ctrl-C to quit            *")
            print("*********************************************************")
            choice = int(input(" Is the above CLI prompt the prompt you were           *\n" \
                       " expecting from the correct WLC in PRIV EXEC mode? : \n"))
            if choice == 1:
                net_connect.disable_paging()
                expPrompt = True
                print(
                    f"Dino - ConneX now sending commands to {conn_info[0]}. Standby...\n\n"
                )
                start2 = time.perf_counter()
                output = net_connect.send_config_set(
                    config_commands=conn_info[1],
                    enter_config_mode=False,
                    cmd_verify=False,
                    exit_config_mode=False)
                print(
                    "Commands sent OK, now cleaning up. Logfile ssh_session_logfile{}.txt created\n\n"
                    .format(conn_info[2]))
                print(
                    "*********************************************************"
                )
                print(
                    f"* Dino | ConneX Disconnecting SSH to {conn_info[0]}      "
                )
                print(
                    "*********************************************************"
                )
                net_connect.disconnect()
                stop2 = time.perf_counter()
                conn_status = "Session Success"
                print("Elapsed time to send and cleanup(secs): ",
                      stop2 - start2)
                return conn_status
            elif choice == 2:
                print(
                    "*********************************************************"
                )
                print(
                    f"* Dino | ConneX Disconnecting SSH to {conn_info[0]}     "
                )
                print(
                    "*********************************************************"
                )
                net_connect.disconnect()
                connIsAlive = net_connect.is_alive()
                conn_status = "User Interupt - Expected prompt mismatch"
                return conn_status
            elif choice != int:
                print(
                    "*********************************************************"
                )
                print(
                    "* Dino | ConneX ERROR                                   *"
                )
                print(
                    "*********************************************************"
                )
                print(
                    "*                                                       *"
                )
                print(
                    f"* Say What?! Expecting Integer and recieved {choice}   *"
                )
                print(
                    "* Try again                                             *"
                )
                continue
        else:
            print("Failure: Unknown Error. Sorry")