Ejemplo n.º 1
0
def connect():
    """ Here we will user connArgs gathered from get_conn_args \n""" \
    """ and establish connection to WLC                        \n"""
    global conn
    global connArgs
    global savedCredentials
    global connIsAlive
    attempts = 0
    expPrompt = False
    while connIsAlive is False:
        try:
            connArgs = get_conn_args()
            conn = ConnectHandler(ip=connArgs["ip"],
                                  username=connArgs["user"],
                                  password=connArgs["pass"],
                                  device_type="cisco_ios",
                                  session_log="ssh_session_logfile.txt",
                                  session_log_file_mode="write",
                                  session_log_record_writes="True")
        except nm.NetMikoTimeoutException:
            print("-------------------------------------------\n" \
                  "Error: Timeout Error Occured Attempting to \n" \
                  "connect. Check IP/Hostname and try Again   \n" \
                  "-------------------------------------------\n")
        except nm.NetMikoAuthenticationException:
            print("-------------------------------------------\n" \
                  "Error: Authentication Error Occured.       \n" \
                  "Check Credentials and try Again            \n" \
                  "-------------------------------------------\n")
    ##    except:
    ##        print("Unexpected error:", sys.exc_info()[0])
    ##        raise
        else:
            connIsAlive = conn.is_alive()
            if connIsAlive is True:
                print("Connection Successful!")
                getPrompt = conn.find_prompt()
                print("-------------------------------------------\n" \
                      "CONNECTED via SSH- \n" \
                      f"Device returned : {getPrompt}               \n" \
                      "-------------------------------------------\n")
                while expPrompt is False:
                    choice = 0
                    choice = int(input("Is the above CLI prompt the prompt you were\n" \
                                       "expecting from the correct WLC in exec mode? \n" \
                                       "1= Yes | 2=No or Ctrl-C to quit :  "))
                    if choice == 1:
                        conn.disable_paging()
                        expPrompt = True
                        return conn
                    elif choice == 2:
                        savedCredentials = False
                        print(f"Disconnecting Current SSH Session...")
                        conn.disconnect()
                        connIsAlive = conn.is_alive()
                        main2()
            else:
                print("Failure: Unknown Error. Sorry")
Ejemplo n.º 2
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     for host in self.connected_devices:
         alive_session = ConnectHandler(**host)
         if alive_session.is_alive():
             backup_logger.info(f"disconnecting from {host['host']}")
             try:
                 alive_session.disconnect()
                 self.connected_devices.remove(host)
             except Exception as e:
                 backup_logger.exception(f"Exception '{e}' occurred. disconnect is unsuccessful for device {host}. "
                                         f"Skipping back up")
Ejemplo n.º 3
0
    def find_password(self, host, ID):

        for password in self.passwords:
            try:
                session = ConnectHandler(device_type='cisco_ios',
                                         ip=host,
                                         username='******',
                                         password=password,
                                         secret=password)
                if session.is_alive():
                    ID['Password'] = password
                    return session
                    break
            except NetMikoAuthenticationException:
                continue
Ejemplo n.º 4
0
 def conectar(self):
     try:
         tunnel = ConnectHandler(device_type="cisco_xr",
                                 ip=self.ip,
                                 password=self.password,
                                 port=self.port,
                                 username=self.username,
                                 timeout=self.timeout)
         if tunnel.is_alive() == True:
             return tunnel
         else:
             pass
     except Exception as e:
         fecha = time.strftime("%d/%m/%Y - %H:%M:%S")
         Genericos.save_to_file("ERROR", fecha + " " + self.ip, str(e))
         print(str(e))
Ejemplo n.º 5
0
class CiscoIosSSH:
    def __init__(self, user, password, enable, ip_address):
        self.username = user
        self.host = ip_address
        self.ssh = ConnectHandler(username=user,
                                  password=password,
                                  secret=enable,
                                  ip=ip_address,
                                  device_type='cisco_ios')
        self.ssh.enable()

    def get_config(self):
        if self.ssh.is_alive():
            config = self.ssh.send_command('sh run')
            return config
        else:
            raise ValueError('Сессия закрыта')
Ejemplo n.º 6
0
class CiscoASA :
    def __init__(self, device_ip ="",port = 22, username = "", password = "",enable = "" ):
        self.net_connect = {
        "ip":device_ip,
        "port": port,
        "username":username,
        "password":password,
        "secret": enable,
        "device_type":"cisco_asa"
        }
        self.Device_name="UNKNOW"
        self.isContext = False
        self.ContextCount = 0;
        self.DEBUG = False
        self.ssh_conn = None
        self.ContextList = list()
        self.Datenow = datetime.datetime.now().strftime('%Y.%m.%d %H:%M:%S')
        self.Status = "UNKNOW"
        self.StatusINT = 1
        self.Dir=""

    def Discovery_host(self):
        # Производим изучение устройства проверяем на наличие контекстов
        if self.SetConnection() == False :
            return False
        self.GetDeviceName()
        self.isContext = self.CheckContext()
        #self.DEBUG = True
        if (self.isContext):
            if self.FindAllContext() != True:
                self.CreateSystemContext()
        else:
            self.CreateSystemContext()
        return True
    def SetConnection(self):
        # Устанавливаем коннект к устройству, если не удачно возвращаем None
        self.DebbugOutput ("INFORMATIONAL: Connecting to : {}".format(self.net_connect["ip"]))
        try:
            self.ssh_conn = ConnectHandler(**self.net_connect)
        except  SSHException():
            self.DebbugOutput("ERROR: Incompatible version SSH (1.5 instead of 2.0)")
            self.Status = "SSH ERROR,  Version 1"
            self.StatusINT = 7
        except socket.error:
            self.DebbugOutput("ERROR: ip Address not Correct : {} ".format(self.net_connect["ip"]))
            self.Status = 'IP incorrect'
            self.StatusINT = 5
        except:
            print ("ERROR:  not connected to IP {}".format(self.net_connect["ip"]))
            self.StatusINT = 2
            self.Status = "TIMEOUT"
        if self.ssh_conn == None :
            self.DebbugOutput ("ERROR: Connection to : {} ".format(self.net_connect["ip"]))
            return False
        else:
            self.DebbugOutput("OK: Connection Established to: {} ".format(self.net_connect["ip"]))
            return True
    def GetDeviceName(self):
        # Получаем имя устройства к нему будем добовлять название контекстов при наличии.
        new_prompt = self.SendCommand("show hostname")
        if (new_prompt == None ):
            self.DebbugOutput("ERROR: Not finde Device name : ".format(self.Device_name))
            return False
        self.DebbugOutput("OK: Device promt {}".format(new_prompt))
        self.Device_name = new_prompt.strip()
        self.Dir = self.Device_name
        self.Dir = self.ssh_conn.base_prompt.strip("#")
        self.DebbugOutput("OK: Device name {}".format(self.Device_name))
        return True
    def CheckContext(self):
        cmd_check_context = "show context count"
        o_ = self.SendCommand(cmd_check_context)
        if (len (o_) <=0 ):
            self.DebbugOutput("ERROR:  Command \"{}\"  return : {} " .format(cmd_check_context,o_))
            return False
        self.DebbugOutput("OK:  Command \"{}\"  return : {} ".format(cmd_check_context,o_))
        for line in o_.split("\n"):
            m_ = re.search("Total.*:\s*\d*",line)
            if m_ != None :
                self.DebbugOutput("OK:  Faind context \"{}\" ".format(m_[0]))
                n_,c_ = m_[0].split(":")
                try :
                    self.ContextCount = int (c_)
                except:
                    self.DebbugOutput("ERROR:  Can't convert count context to Int  \"{}\" ".format(c_))
                    return False
                else :
                    self.DebbugOutput("OK: Context count  \"{}\" type {}".format(self.ContextCount,type(self.ContextCount)))
                    return True
        return False
    def SendCommand(self,cmd):
        o_=""
        if self.ssh_conn is None :
            self.SetConnection()
        if self.ssh_conn.is_alive() == False :
            if self.SetConnection() == False :
                return None
        try :
            o_ = self.ssh_conn.send_command(cmd)
        except:
            print ("Could not Execute commanfd {}".format(cmd))
            return None
        else:
            self.DebbugOutput("OK: Command : \"{}\" run succsesfuuly".format(cmd))
            self.DebbugOutput("OK: Command Return : \"{}\"".format(o_))
            #print (o_)
            return o_
    def ChangeContext(self):
        cmd_chahge_context = "change system"
        if (self.ssh_conn == None ) :
            return None
        if self.ssh_conn.is_alive() == False :
            if self.SetConnection() == False :
                return None
        try :
            o_ =  self.ssh_conn.send_command(cmd_chahge_context, expect_string=self.Dir.split("/",1)[0])
        except:
            self.DebbugOutput("ERROR : Could not Execute commanfd {}".format(cmd_chahge_context))
            return None
        else:
            if ("error" in o_.lower()):
                self.DebbugOutput("INFORMATION: Context not use")
                self.StatusINT = "6"
                self.Status = "CONTEXT ERROR"
            self.DebbugOutput("OK: Command : \"{}\" run succsesfuuly".format(cmd_chahge_context))
            self.ssh_conn.base_prompt = self.ssh_conn.find_prompt()
            #self.Device_name = self.ssh_conn.base_prompt
            self.Dir = self.ssh_conn.base_prompt.strip("#")
            return o_
    def DebbugOutput(self,str):
        if (self.DEBUG):
            print ("DATE {}".format(self.Datenow))
            print (str)
    def FindAllContext(self):
        # Переключаемся в системный контекст и собираем информацию по всем имеющися контекстам заполняем поле имя и congigUrl
        cmd_show_context = "show context detail"
        o_ = self.ChangeContext()
        if o_ == None :
            self.DebbugOutput("ERROR: Cant switch to System context : {}".format(self.net_connect["ip"]))
        o_ = self.SendCommand(cmd_show_context)
        curent_context = None
        if (len(o_)<=0) :
            return False
        for line_ in o_.split("\n"):
            #print (line_)
            m_ = re.search(r"^Context\s+\"(.*)\".*$",line_)#"(.+)".+Config URL\s?:\s?.+$',o_)
            if m_ != None :
                if curent_context != None:
                    self.ContextList.append(curent_context)
                    self.DebbugOutput("Faind Context : {}".format(curent_context))
                curent_context = ASAContext(name=m_[1])
            m_ = re.search(r"^.+Config URL:\s+(.*)$",line_)
            if (m_ != None):
                if ("startup-config" in m_[1]):
                    curent_context.SetMethod("run")
                curent_context.SetUrl(m_[1])
        self.ContextList.append(curent_context)
        self.DebbugOutput("Not Context{}".format(self.ContextList))
        return True
    def CreateSystemContext(self):
        # создаем системный окнтекст для устройств где контексты не включены
        self.ContextList.append(ASAContext(name="system",method="run"))
        self.DebbugOutput("Not Context{}".format(self.ContextList))
        return True
    def GetConfig(self,context_ = None):
        # получаем конфиг контекста
        if context_ == None :
            return False
        if "run" in context_.GetMethod():
            cmd = "show running-config"
        else:
            cmd = "more " +context_.GetUrl()
        #self.DEBUG = True
        self.DebbugOutput("Send command : \"{}\" for context \"{}\" ".format(cmd, context_))
        o_ = self.SendCommand(cmd)
        return o_
    def GetCheksumm(self):
        cmd = "show checksum"
        o_ = self.SendCommand(cmd)
        if o_ != None :
            if ("error" in o_.lower()):
                return None
            else:
                return o_.split()[-1]

    def CloseSSH(self):
        if not self.ssh_conn == None:
            self.ssh_conn.disconnect()
    def SaveConfig(self,config_dir):
        # Сохраняем конфигурационный файлф, на вход подаем директорию куда сохранять
        bytes = 0
        self.ChangeContext()
        for i in range(0, len(self.ContextList)):
            if not (self.ContextList[i].isNameNull()):
                config_context = self.GetConfig(self.ContextList[i])
                if (len(config_context) > 0):
                    self.StatusINT = 0
                    self.Status = "OK"
                    bytes += len(config_context)
                    file_dir = config_dir+"/" +  dev_.ContextList[i].name+""
                    if (not os.path.exists(file_dir)):
                        os.makedirs(file_dir)
                    file_name = file_dir+"/" + "{}-{}.conf".format(dev_.Device_name, dev_.ContextList[i].name)
                    # print (file_name)
                    # file_name = "{}-{}.conf".format(dev_.Device_name,dev_.ContextList[i].name)
                with open(file_name, "w") as F:
                    print(config_context, file=F)
        return bytes
Ejemplo n.º 7
0
    print "\n\n\ninput hostname, username, pwd, and device type\n\n"

    print sys.argv

    args = sys.argv

    if len(args) == 5:
        print "hostname", args[1]
        print "username", args[2]
        print "pwd", args[3]
        print "device type", args[4]
    else:
        print "invalid input with args - should have 4 inputs"

    ipaddr = args[1]
    device_type = args[4]
    username = args[2]
    password = args[3]
    cmd = "show version"

    csr1 = ConnectHandler(ip=ipaddr,
                          username=username,
                          password=password,
                          device_type=device_type)
    print("Connected to CSR1")
    csr1_device_check = csr1.is_alive()
    print "Connected to device is verified " + str(csr1_device_check)
    csr1.send_command("term len 0")
    print "sending command"
    print csr1.send_command(cmd)
Ejemplo n.º 8
0
def connect():
    """ Here we will user connArgs gathered from get_conn_args \n""" \
    """ and establish connection to WLC                        \n"""
    global conn
    global connArgs
    global savedCredentials
    global connIsAlive
    attempts = 0
    expPrompt = False
    while connIsAlive is False:
        try:
            connArgs = get_conn_args()
            conn = ConnectHandler(ip=connArgs["ip"],
                                  username=connArgs["user"],
                                  password=connArgs["pass"],
                                  device_type="cisco_ios",
                                  session_log="ssh_session_logfile.txt",
                                  session_log_file_mode="write",
                                  session_log_record_writes="True")
        except nm.NetMikoTimeoutException:
            print("*********************************************************\n" \
                  "* Error: Timeout Error Occured Attempting to            *\n" \
                  "* connect. Check IP/Hostname and try Again              *\n" \
                  "*********************************************************\n")
        except nm.NetMikoAuthenticationException:
            print("*********************************************************\n" \
                  "* Error: Authentication Error Occured.                  *\n" \
                  "* Check Credentials and try Again                       *\n" \
                  "*********************************************************\n")
    ##    except:
    ##        print("Unexpected error:", sys.exc_info()[0])
    ##        raise
        else:
            connIsAlive = conn.is_alive()
            if connIsAlive is True:
                print(
                    "*********************************************************"
                )
                print(
                    "* Dino | SSH ConneX                                     *"
                )
                print(
                    "*********************************************************"
                )
                print(
                    "* SSH Connection Successful!                            *"
                )
                getPrompt = conn.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:
                        conn.disable_paging()
                        expPrompt = True
                        return conn
                    elif choice == 2:
                        savedCredentials = False
                        print(f"Disconnecting Current SSH Session...")
                        conn.disconnect()
                        connIsAlive = conn.is_alive()
                        main2()
            else:
                print("Failure: Unknown Error. Sorry")
from netmiko import ConnectHandler
import os

username = "******"
password = "******"
ip = "10.73.1.105"
commands = ["show version", "show ip interface brief"]

switch = {
    'device_type': 'arista_eos',
    'host': ip,
    'username': username,
    'password': password,
    'port': '22',
    'timeout': 180
}
connection = ConnectHandler(**switch)
connection.is_alive()
for command in commands:
    cmd_output = connection.send_command(command)
    f = open(command + ".txt", "w")
    f.write(cmd_output)
    f.close

connection.disconnect()
Ejemplo n.º 10
0
class DeviceConnector(object):
    def __init__(self, device, username, password, vendor="autodetect"):
        self.device = device
        self.vendor = vendor
        self.username = username
        self.password = password
        self.device_data = {
            "device_type": self.vendor,
            "host": self.device,
            "username": self.username,
            "password": self.password,
        }

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(3))
    def __enter__(self):
        try:
            self.get_vendor()
            with yaspin(
                text=f"Connecting: {self.device}",
                color="yellow",
            ) as spinner:
                self.connection = ConnectHandler(**self.device_data)
                if self.connection.is_alive():
                    logger.info(f"Connected to {self.device}")
                    spinner.text = f"{self.device}"
                    spinner.color = "green"
                    spinner.ok("Connected:")
            return self
        except Exception:
            message.fail("Connection Failed")
            logger.critical(f"{self.device} connection failed")
            pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            if self.connection:
                with yaspin(
                    text=f"Disconnecting: {self.device}", color="red"
                ) as spinner:
                    self.connection.disconnect()
                    if not self.connection.is_alive():
                        spinner.text = f"{self.device}"
                        spinner.ok("Disconnected:")
        except Exception:
            None

    def send_command(self, command, use_fsm_file=""):
        message.info(f"Sending Command: {command}")
        logger.info(f"Sending Command: {command}")
        command_output = self.connection.send_command_timing(command)
        if use_fsm_file:
            return scrub_data_with_fsm(
                command_output,
                use_fsm_file,
            )
        return command_output

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(3))
    def get_vendor(self):
        if self.device_data["device_type"] == "autodetect":
            message.info(f"Finding the vendor for the host: {self.device}")
            self.vendor = SSHDetect(**self.device_data).autodetect()
        message.success(f"Identified {self.device} as {self.vendor}")
        self.device_data["device_type"] = self.vendor
Ejemplo n.º 11
0
class Device():
    _hostname = None
    _ios = None
    _type = None
    _is_npe = None
    _cdp_enabled = None
    _net_connect = None

    _conn_cred = list()
   
    #
    # Device constructor, argument - connection info
    # 
    def __init__(self, host_info):
        if DEBUG: print("Device::__init__")
        #TODO: add connection info check
        self._conn_cred = host_info

    #
    # Connect or reconnect to device or reuse connection if it`s still alive
    #
    def _connect(self):
	#don`t reconnect if connection already active 
        if self._net_connect is not None  and  self._net_connect.is_alive():
            if DEBUG: print("Connection to host " + self._conn_cred['host'] +" is alive")
            return self._net_connect.is_alive()

        try:
            if DEBUG: print("Device::connect to host " + self._conn_cred['host'])
            self._net_connect = ConnectHandler(**self._conn_cred)
            return self._net_connect.is_alive()
        except Exception as e:
            print('Catched exception in Device::_connect:' + str(e))

    def disconnect(self):
       if DEBUG: print("Device:disconnect")
       self._net_connect.disconnect()

    #
    # Send commands to device and return response
    # 
    def _send_cmd(self, cmd):
        if DEBUG: print("Device::_send_cmd:" + cmd)
        if self._connect():
            return self._net_connect.send_command(cmd)

    #
    # get as much information as possible from show version
    #
    def _parse_show_version(self):
        out = self._send_cmd("sh version | in System image file is | Software | bytes of memory")

        #looking for information about IOS version
        m = re.search('Software .* Version (.+),.*', out, re.MULTILINE)
        if m:
             self._ios = m.group(1)
             if DEBUG: print("IOS:", self._ios)

        #looking for device type
        m = re.search('cisco (.*) .* processor .* bytes of memory', out, re.MULTILINE)
        if m:
             self._type = m.group(1)
             if DEBUG: print("Type:", self._type)

        #looking for NPE mark in IOS version
        m = re.search('image file is .*_npe', out, re.MULTILINE)
        if m:
             self._is_npe = True
        else:
             self._is_npe = False

        if DEBUG: print("Is NPE:", self._is_npe)

    def send_config(self, commands):
        if DEBUG: print("Device::send_config:", commands)
        try:
            out = self._net_connect.send_config_set(commands)
            if DEBUG: print(out)
        except Exception as e:
            print('Catched exception in send_config: ',self.get_hostname(), str(e))

    def get_config(self):
        if DEBUG: print("Deivce::get_config")
        return self._send_cmd("show running-config")

    def get_ios_version(self):
        if DEBUG: print("Deivce::get_ios_version")
        if self._ios is None:
            self._parse_show_version()
        return self._ios

    def get_type(self):
        if DEBUG: print("Deivce::get_type")
        if self._type is None:
            self._parse_show_version()
        return self._type

    #
    # check host availability from device using ping
    #
    def is_host_available(self, host):
        if DEBUG: print("Device::is_host_available for ", host)
        out = self._send_cmd("ping " + host)
        if DEBUG: print(out)
        m = re.search('Success rate is 100 percent', out, re.MULTILINE)
        if m:
            if DEBUG: print("Host is available:", host)
            return True
        else:
            if DEBUG: print("Host is unavailable:", host)
            return False

    def is_npe(self):
        if DEBUG: print("Deivce::is_npe")
        if self._is_npe is  None:
            self._parse_show_version()
        return self._is_npe

    def is_cdp_enabled(self):
        if DEBUG: print("Deivce::is_cdp_enabled")
        if self._cdp_enabled is not None:
           return self._cdp_enabled
        out = self._send_cmd("show cdp | in enabled")

        m = re.search('is.*not.* enabled', out, re.MULTILINE)
        if m:
             self._cdp_enabled = False
        else:
             self._cdp_enabled = True

        return self._cdp_enabled

    def get_cdp_peer_num(self):
        if DEBUG: print("Deivce::get_cdp_peer_num")
        if self.is_cdp_enabled() is False:
            return None
        out = self._send_cmd("show cdp neighbor detail | in Device ID").splitlines()
        if DEBUG: print("Num of CDP neighbors:", len(out))
        return len(out)       

    #
    # Check NTP status, return true if synchronized, else return false
    #
    def is_ntp_synchronized(self):
        if DEBUG: print("Deivce::is_ntp_synchronized")
        out = self._send_cmd("sh ntp status | in Clock is")

        m = re.search('Clock is synchronized', out, re.MULTILINE)
        if m:
             return True
        else:
             return False


    def get_hostname(self):
        if DEBUG: print("Device::get_hostname")
        
        if self._hostname is not None:
             return self._hostname

        out = self._send_cmd("show running-config | in ^hostname .*$")
        #strip all before hostname
        m = re.search('^hostname (.+)$', out)
        if m:
             self._hostname = m.group(1)
        return self._hostname
Ejemplo n.º 12
0
class UnlRouter:
    def __init__(self, name, unl_ip, port, param_dict, config_folder):
        self.unl_ip = unl_ip
        self.port = port
        self.params = param_dict.copy()
        self.params.update(dict(ip=self.unl_ip, port=self.port))
        self.conn = None
        self.config_folder = config_folder
        self.name = name

    def connect(self):
        self.conn = ConnectHandler(**self.params)

    def disconnect(self):
        if self.conn:
            self.conn.disconnect()

    def verify_connect(self):
        if self.conn:
            if not self.conn.is_alive():
                self.connect()
        else:
            self.connect()

    def clear_config(self):
        logging.info(f'Trying to reboot {self.name}')
        self.verify_connect()
        self.conn.send_command('end',
                               auto_find_prompt=False,
                               expect_string='#|>')
        self.conn.send_command('end',
                               auto_find_prompt=False,
                               expect_string='#|>')
        r = self.conn.send_command('reload',
                                   auto_find_prompt=False,
                                   expect_string='.*Save?.*|.*reload.*',
                                   delay_factor=0.25)
        if 'Save?' in r:
            self.conn.send_command('no',
                                   auto_find_prompt=False,
                                   expect_string='.*Save?.*|.*reload.*',
                                   delay_factor=0.25)

        try:
            self.conn.send_command('\n\r',
                                   auto_find_prompt=False,
                                   expect_string='.*Save?.*|.*reload.*',
                                   delay_factor=0.25,
                                   max_loops=3)
        except OSError:
            logging.info(f'{self.name} gone to reboot')

    def configure(self, section):
        self.verify_connect()
        filename = self.config_folder + section + '/' + self.name + '.txt'
        logging.info(f'Configure {self.name} with {filename}')
        with open(filename, 'r') as f:
            for line in f:
                self.conn.send_command(line,
                                       delay_factor=0.05,
                                       strip_prompt=False,
                                       expect_string='#|>',
                                       auto_find_prompt=False)
        logging.info(f'{self.name} configured')

    def __repr__(self):
        return f'{self.name} {self.unl_ip} {self.port}'
Ejemplo n.º 13
0

for host in ip_add_file:
    host = host.strip()
    print(host)
    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password, secret=password)
    output = device.send_command('terminal length 0')
    print('##############################################################\n')
    print('...................COMMAND SHOW RUN OUTPUT......................\n')
    output = device.send_command('sh version')
    print(output)
    print('##############################################################\n')
    print('...................ENABLE......................\n')
    output = device.send_command('sh switch')
    print(2)
    print(output)
    print(device.enable(cmd='enable', pattern="ssword"))
    print(3)
    print('##############################################################\n')
    print('...................WRITE......................\n')

    print (device.check_enable_mode())
    print(device.is_alive())

    print(device.send_command('sho run inter vla 99', expect_string='exit', delay_factor=1, max_loops=500, auto_find_prompt=True, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, use_genie=False))
    #expected string seem important on Dell
    
    print('##############################################################\n')

#fd.close()
Ejemplo n.º 14
0
class Switch:
    def __init__(self,
                 host,
                 username,
                 password,
                 type="cisco_ios",
                 debug_on=False):
        self.host = host
        self.log = Logger(self.host, debug_on)
        self.username = username
        self.password = password
        self.type = type
        self.connect = None
        self.allfacts = {}
        self.flashinfo = []
        self.log.debug("[__init__] complete")

    def ssh(self):
        """Establishes an SSH connection"""
        self.log.debug("Executing [ssh]")
        if not self.connect:
            self.connect = ConnectHandler(
                ip=self.host,
                username=self.username,
                password=self.password,
                device_type=self.type,
            )
        if not self.connect.is_alive():
            self.connect = None
            self.connect = self.ssh()
        self.log.debug("[ssh] complete")
        return self.connect

    def facts(self):
        """Gathers basic facts by running show version on the switch"""
        self.log.debug("Executing [base_facts]")
        self.allfacts.update(self.ssh().send_command("show ver",
                                                     use_textfsm=True)[0])
        self.log.debug("[base_facts] complete")
        return self.allfacts

    def running_image(self):
        """returns the current running_image in a standard format"""
        self.log.debug("Executing [running_image]")
        if not self.allfacts.get("running_image"):
            self.facts()
        if "/" not in self.allfacts["running_image"]:
            self.allfacts[
                "running_image"] = f"/{self.allfacts['running_image']}"
        self.log.debug("[running_image] complete")
        return self.allfacts["running_image"]

    def next_boot_file(self):
        """returns the bootfile configuration from running config in a standard
        format. This may not be the current boot image, but will be the
        bootfile used when the switch is reloaded. Used to identify if an
        upgrade is in progress."""
        self.log.debug("Executing [next_boot_file]")
        if not self.allfacts.get("nbf"):
            self.allfacts["nbf"] = (
                self.ssh().send_command("show boot | i BOOT path-list").split(
                    " : ")[-1].strip("flash:"))
        if "/" not in self.allfacts["nbf"]:
            self.allfacts["nbf"] = f"/{self.allfacts['nbf']}"
        self.log.debug("[next_boot_file] complete")
        return self.allfacts["nbf"]

    def reload_pending(self):
        """Checks if a reload is pending on the switch by comparing the current
        bootfile with the next_boot_file"""
        self.log.debug("Executing [reload_pending]")
        if self.running_image() == self.next_boot_file():
            self.log.debug("[reload_pending] complete")
            return False
        else:
            self.log.debug("[reload_pending] complete")
            return True

    def stacked(self):
        """Identifies if a switch is stacked by checking the number of serial
        numbers provided"""
        self.log.debug("Executing [stacked]")
        if not self.allfacts.get("stacked"):
            if not self.allfacts.get("serial"):
                self.facts()
            if len(self.allfacts["serial"]) != 1:
                self.allfacts.update({"stacked": True})
            else:
                self.allfacts.update({"stacked": False})
        self.log.debug("[stacked] complete")
        return self.allfacts["stacked"]

    def ios_xe(self):
        """Checks if the current IOS bootfile is an IOS-XE version"""
        self.log.debug("Executing [ios_xe]")
        if not self.allfacts.get("ios_xe"):
            if "packages.conf" in self.running_image():
                self.allfacts.update({"ios_xe": True})
            else:
                self.allfacts.update({"ios_xe": False})
        self.log.debug("[ios_xe] complete")
        return self.allfacts["ios_xe"]

    def version(self):
        """Returns the switch IOS version"""
        self.log.debug("Executing [version]")
        if not self.allfacts.get("version"):
            self.facts()
        self.log.debug("[version] complete")
        return self.allfacts["version"]

    def featureset(self):
        """Returns the switch featureset"""
        self.log.debug("Executing [featureset]")
        if not self.allfacts.get("featureset"):
            if not self.allfacts.get("running_image"):
                self.facts()
            if "lanlite" in self.allfacts["running_image"]:
                featureset = "lanlite"
            elif "lanbase" in self.allfacts["running_image"]:
                featureset = "lanbase"
            elif "universal" in self.allfacts["running_image"]:
                featureset = "universal"
            self.allfacts.update({"featureset": featureset})
        self.log.debug("[featureset] complete")
        return self.allfacts["featureset"]

    def family(self):
        """Returns the switch family"""
        self.log.debug("Executing [family]")
        if not self.allfacts.get("family"):
            if not self.allfacts.get("hardware"):
                self.facts()
            family = self.allfacts["hardware"][0].split("-")[1]
            if "+" in family:
                family = family.partition("+")[0].rstrip() + "+"
            self.allfacts.update({"family": family})
        self.log.debug("[family] complete")
        return self.allfacts["family"]

    def flash(self):
        """Gets the current flash information"""
        self.log.debug("Executing [flash]")
        self.flashinfo = self.ssh().send_command("dir", use_textfsm=True)
        for item in self.flashinfo[:]:
            if "d" in item['permissions']:
                self.flashinfo.extend(self.ssh().send_command(
                    f"dir {item['name']}", use_textfsm=True))
        self.log.debug("[flash] complete")
        return self.flashinfo

    def file_on_flash(self, file):
        """Checks if the given file exists on Flash"""
        self.log.debug("Executing [file_on_flash]")
        if len(self.flashinfo) == 0:
            self.flash()
        for item in self.flashinfo:
            if "d" not in item["permissions"]:
                if file in item["name"]:
                    self.log.debug("[file_on_flash] complete")
                    return True
        self.log.debug("[file_on_flash] complete")
        return False

    def free_space(self):
        """Returns the available space on flash in bytes"""
        self.log.debug("Executing [free_space]")
        if len(self.flashinfo) == 0:
            self.flash()
        self.log.debug("[free_space] complete")
        return self.flashinfo[0]["total_free"]

    def save_config(self):
        """Saves the current running config"""
        self.log.debug("Executing [save_config]")
        self.ssh().send_command("wr mem")
        self.log.debug("[save_config] complete")
        return True

    def backup_config(self, path="../backups/"):
        """Takes a copy of the current running config and saves it to the
        backup directory"""
        self.log.debug("Executing [backup_config]")
        self.ssh().send_command("show run")
        timestamp = dt.datetime.fromtimestamp(
            time.time()).strftime("%d%m%Y-%H%M%S")
        print(
            self.ssh().send_command("show run"),
            file=open(f"{path}{self.host}-{timestamp}.ios", "a"),
        )
        self.log.debug("[backup_config] complete")
        return True

    def send_file(self, file, destination):
        """Transfers a given file to switch flash memory"""
        self.log.debug("Executing [send_file]")
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(
            hostname=self.host,
            username=self.username,
            password=self.password,
            allow_agent=False,
            look_for_keys=False,
        )
        scp = SCPClient(ssh.get_transport(), progress=_progress)
        scp.put(file, destination)
        scp.close()
        self.log.debug("[send_file] complete")
        return True

    def send_config(self, command):
        """Sends the given configuration command string to the switch"""
        self.log.debug("Executing [send_config]")
        if "% Invalid input" in self.ssh().send_config_set(command):
            raise InvalidConfigCommand(command)
        self.log.debug("[send_config] complete")
        return True

    def reload(self):
        """Reload the switch"""
        self.log.debug("Executing [reload]")
        connect = self.ssh()
        output = connect.send_command_timing("reload in 5")
        if "?" in output:
            output += connect.send_command_timing("y")
        self.log.debug("[reload] complete")
        return True
Ejemplo n.º 15
0
    'username': '******',
    'password': '******',
    #'port':2000
}

net_connect = ConnectHandler(**iosv_l2)
output = net_connect.send_command('ls')
#if("folder2" in output):
#    print("Command successful")
#else:
#    print("command did not succed")
print(output)

print(type(output))

res = net_connect.is_alive()
print(type(res))
print(res)

#print(type(output))
#print("abc\n def\n")
#commands = ['mkdir abc']
#output = net_connect.send_config_set(config_commands=commands, delay_factor=100)
#print(output)

#for n in range(2,22):
#    print("Creating vlan "+ str(n))
#    config_commands = ['vlan '+str(n), 'name Python_VLAN '+str(n)]
#    output = net_connect.send_config_set(config_commands)
#    print(output)
    'global_delay_factor': 0.5
}

net_connect = ConnectHandler(**cisco_881)
print("Connected !")
net_connect.enable()
config = [
    'int lo0', 'ip add 10.99.99.1 255.255.255.252', 'assaas', 'int lo1',
    'ip add 10.99.99.5 255.255.255.252', 'int lo0',
    'ip add 10.99.99.1 255.255.255.252', 'int lo1',
    'ip add 10.99.99.5 255.255.255.252', 'int lo0',
    'ip add 10.99.99.1 255.255.255.252', 'int lo1',
    'ip add 10.99.99.5 255.255.255.252'
]
time.sleep(1)
print(net_connect.is_alive())
# print("Starting...")
# s = time.time()
# out = net_connect.send_config_set(config)
# print(out)
# print("Usage time: {:.2f}".format(time.time() - s))

print("=" * 100)
time.sleep(1)
print("Starting...")
config_str = "\n".join(config)
s = time.time()
out = net_connect.send_config_set([config_str])
# print(out)
print("Usage time: {:.2f}".format(time.time() - s))
net_connect.exit_config_mode()
Ejemplo n.º 17
0
from netmiko import ConnectHandler

device_ip = '192.168.50.40'
device_username = '******'
device_password = '******'
device_type = 'cisco_xe'

router = ConnectHandler(host=device_ip,
                        username=device_username,
                        password=device_password,
                        device_type=device_type)

router.disconnect()

print(router.is_alive())
Ejemplo n.º 18
0
class CiscoRouter(Router):
    """ Device is a Cisco Router
    """
    def __init__(self, device_info, ssh_info, snmp_info):
        super(CiscoRouter, self).__init__(device_info, ssh_info, snmp_info)

        # self.ssh_info = {
        #     'device_type': 'cisco_ios',
        #     'ip':   ip,
        #     'username': ssh_info.get('username'),
        #     'password': ssh_info.get('password'),
        #     'port' : ssh_info.get('port'),
        #     'secret': ssh_info.get('secret'),
        #     'verbose': ssh_info.get('verbose', False),
        # }
        self.ssh_info['device_type'] = 'cisco_ios'

        self.net_connect = ConnectHandler(**ssh_info)

    def remote_command(self, command):
        """ Connect SSH to device
        """
        if not self.test_ssh_connect():
            return False
        self.net_connect.enable()
        output = self.net_connect.send_command(command)
        return output

    def test_ssh_connect(self):
        if self.net_connect is None or not self.net_connect.is_alive():
            try:
                logging.debug("ConnectHandler")
                self.net_connect = ConnectHandler(**self.ssh_info)
            except NetMikoTimeoutException:
                self.net_connect = None
                logging.info("Error: Can't SSH to device ip {}".format(
                    self.ip))
                return False
        # TEST
        retry = 0
        max_retry = 3
        while retry < max_retry:
            try:
                if retry > 0:
                    self.net_connect = ConnectHandler(**self.ssh_info)
                self.net_connect.enable()
                return True
            except (NetMikoTimeoutException, EOFError):
                retry += 1
        return False

    def send_config_set(self, config_command):
        if not self.test_ssh_connect():
            return False
        try:
            self.net_connect.enable()
            output = self.net_connect.send_config_set(config_command)
            return output
        except (NetMikoTimeoutException, EOFError):
            return False

    def update_flow(self, flow):
        """ apply action to device
        """

        # is_in_flow = False
        # for action in flow['action']:
        #     if action['device_ip'] == self.ip:
        #         is_in_flow = True

        # is_in_flow_pending = False
        my_action = None
        current_action = None
        for action in flow['action_pending']:
            if action['device_ip'] == self.ip:
                # is_in_flow_pending = True
                my_action = action
                break

        if my_action is None:
            if flow['is_pending'] == False:
                return True
        else:
            if my_action.get('rule') == 'remove':
                command = sdn_utils.generate_flow_remove_command(flow)
                logging.debug(command)
                if self.send_config_set(command) == False:
                    return False
                return True
            else:
                for action in flow['action']:
                    if action['device_ip'] == self.ip:
                        current_action = action
                        break

        # Apply interface policy
        # Todo

        # Grouping commands
        command = sdn_utils.generate_flow_command(flow, my_action,
                                                  current_action)
        logging.info(command)
        if self.send_config_set(command) == False:
            return False
        return True

    def get_serial_number(self):
        """ Get device serial Number
        """
        return self.remote_command("show version | inc Processor board ID")

    def get_route_map(self):
        """ Get current route map on device
        """
        # Todo Create function for this
        pass

    def get_acl_list(self):
        """ Get current access list on device
        """
        # Todo Create function for this
        pass