Beispiel #1
0
def get_result():
    try:
        data = request.get_json(True)
        address = data['host']
        account = Account(name=data['user'], password=data['passwd'])

        if data['conntype'] == 'SSH':
            from Exscript.protocols import SSH2
            conn = SSH2()
        elif data['conntype'] == 'Telnet':
            from Exscript.protocols import Telnet
            conn = Telnet()
        else:
            raise (Exception('Unsupport connection type'))
        conn.connect(address)
        conn.login(account)
        conn.execute(data['command'])

        response = to_plain(str(conn.response))

        conn.send('exit\n')
        conn.close()
        return jsonify(success=True, response=response)
    except Exception as e:
        return jsonify(
            success=False,
            response="Opus! Some guy poisoned my coffee last night!")
Beispiel #2
0
def get_configs(proto, account, host, t_out=30):
	try:
		if proto == "ssh":
			if t_out == 30:
				conn = SSH2()
			else:
				conn = SSH2(timeout=t_out)
		elif proto == "telnet":
			conn = Telnet()
		conn.set_driver('ios')
		conn.connect(host)
		conn.login(account)
		conn.execute('term length 0')
		conn.execute('term width 0')
		conn.send('enable\r')
		conn.app_authorize(account)
		conn.execute('show version')
		showver = conn.response.split('\r\n')
		conn.execute('show startup-config')
		showstart = conn.response.split('\r\n')
		conn.execute('show running-config all')
		showrun = conn.response.split('\r\n')
		showrun.pop()
		showstart.pop()
		showver.pop()
		outputbuffer = {'version':showver,
				'startup-config':showstart,
				'running-config':showrun,
				'error': None}
		return outputbuffer

	except Exception:
		outputbuffer = {'version': "", 'startup-config': "", 'running-config':"", 'error': True}
		return outputbuffer
Beispiel #3
0
 def __enter__(self):
     self.account = Account(JUNIPER_ROUTER_TELNET_USER,
                            password=JUNIPER_ROUTER_TELNET_PASS)
     self.conn = Telnet(debug=TELNET_DEBUG_LEVEL, connect_timeout=None)
     self.conn.connect(self.host_address)
     self.conn.set_driver(JunOSDriver())
     self.conn.login(self.account)
     return self
Beispiel #4
0
 def __enter__(self):
     self.account = Account(self.telnet_username,
                            password=self.telnet_password)
     self.conn = Telnet(debug=TELNET_DEBUG_LEVEL,
                        connect_timeout=PYCURL_TIMEOUT)
     self.conn.connect(self.host_address, port=self.port)
     self.conn.set_driver(self.exscript_driver())
     self.conn.login(self.account)
     return self
Beispiel #5
0
def ConnectEx(server, consoleport):
    #account = read_login()     # Prompt the user for his name and password
    conn = Telnet()
    #conn.debug=5               # Uncomment this if you have problems with connecting to the device
    conn.connect(server, consoleport)
    print "Trying to wake up the console"
    conn.execute("\r\n\r\n")  #
    conn.execute("enable")  #
    #conn.login(account)        # Authenticate on the remote host
    return conn
Beispiel #6
0
 def connect_to_target(self, username, password):
     self.username = username
     self.password = password
     timeout = self.timeout
     try:
         self.connection = Telnet(timeout=timeout)
         self.connection.connect(hostname=self.target_ip, port=self.target_port)
         self.connection.login(Account(self.username, self.password))
         self.get_device_port_info()
     except Exception:
         raise Exception('Fail to set up connection')
Beispiel #7
0
    def remote_connect(self, credentials, host=None, resolve=True):

        connection = Telnet()

        host = host or self._hostname
        ip = self._ip

        logging.debug("host %s..." % (host))
        logging.debug("ip %s..." % (ip))
        logging.debug(self._opsys)

        if resolve:
            target = host
        else:
            target = ip
        logging.debug("enter target %s..." % (target))

        try:
            connection.connect(target)
            connection.set_driver(self._opsys)
            logging.debug("DONE")
        except Exception, err:
            logging.debug("1. FAILED CONNECTION")
            return False
Beispiel #8
0
 def createProtocol(self):
     self.protocol = Telnet()
Beispiel #9
0
 def _create_client(self):
     return Telnet()
Beispiel #10
0
    def __init__(self,
                 address,
                 port,
                 protocol,
                 username='',
                 password='',
                 logger=None,
                 prompt_list=None):
        """Connect to device with selected protocol

        :param address: address of the target host
        :param port: communication port
        :param protocol: SSH or Telnet
        :param username:
        :param password:
        :param logger: cloudshell.core.logger.qs_logger object
        :param prompt_list: optional custom list of prompt patterns used to match commnad prompt on receive
        :return:
        """

        self.account = Exscript.Account(username, password)
        self.default_prompt_list = prompt_list

        if logger:
            self.logger = logger
        else:
            self.logger = None

        self._write_log('Initializing: address=' + address + ';port=' +
                        str(port) + ';protocol=' + protocol + 'prompt_list=' +
                        str(self.default_prompt_list))
        if protocol.lower() == 'telnet':
            try:

                self.handler = Telnet()
                self._write_log('Got Telnet handler object')
                if not self.default_prompt_list:
                    self.default_prompt_list = self.handler.get_prompt()
                    self._write_log('Setting promp list to library default: ' +
                                    str(self.default_prompt_list))
                self.handler.set_prompt(self.default_prompt_list)
                self.handler.connect(address, port)
                self._write_log('Connected')

            except:
                self._write_log('Unable to connect to target', 'error')
                self._write_log(sys.exc_info()[0], 'error')
                raise

        elif protocol.lower() == 'ssh':
            try:
                self.handler = SSH2()
                self._write_log('Got SSH handler object')
                if not self.default_prompt_list:
                    self.default_prompt_list = self.handler.get_prompt()
                    self._write_log('Setting promp list to library default: ' +
                                    str(self.default_prompt_list))
                self.handler.set_prompt(self.default_prompt_list)
                self.handler.connect(address, port)
                self._write_log('Connected')
            except:
                self._write_log('Unable to connect to target', 'error')
                self._write_log(sys.exc_info()[0], 'error')
                raise

        else:
            self._write_log('invalid protocol: ' + protocol, 'error')
            raise AttributeError('invalid protocol')
Beispiel #11
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False):
    """
    Deploy code in a safe way o a Cisco IOS device.
    """

    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        account = read_login()

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Aclname ([^ ]+)
Value Required Direction ([^ ]+)
Value Required Interface (.*)

Start
  ^access-group ${Aclname} ${Direction} interface ${Interface} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        conn.execute('show run | include ^access-group')
        map_acl_int = {}
        for aclname, direction, interface in table.ParseText(conn.response):
            if aclname in map_acl_int.keys():
                map_acl_int[aclname].append({"dir": direction,
                                             "int": interface})
            else:
                map_acl_int[aclname] = [{"dir": direction, "int": interface}]

        return map_acl_int

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s" %
              transport)
        sys.exit(2)
    conn.set_driver('ios')
    conn.connect(hostname)
    try:
        conn.login(account)
    except LoginFailure:
        print("ERROR: Username or Password incorrect for %s" % hostname)
        print("HINT: verify authentication details in your .netrc file")
        sys.exit(2)
    s(conn, "terminal pager 0")

    map_pol_int = collect_interfaces(conn)
    pprint(map_pol_int)

    def lock_step(lock, pol):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure terminal')
        if afi == 4:
            try:
                s(conn, "clear configure access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "clear configure ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            for line in policy.split('\n'):
                if lock:
                    line = line.replace("access-list %s " % name,
                                        "access-list %s%s " % (lock, name))
                s(conn, line)
        s(conn, "end")

        # then replace ACL on all interfaces / VTYs
        if name in map_pol_int:
            for entry in map_pol_int[name]:
                print("INFO: lockstepping policy %s afi %s" % (name, afi))
                s(conn, "configure terminal")
                s(conn, "access-group %s%s %s interface %s"
                  % (lock, name, entry['dir'], entry['int']))
                s(conn, "end")

    for policy in acls:
        for lock in ["LOCKSTEP-", ""]:
            lock_step(lock, policy)
        # cleanup
        s(conn, "configure terminal")
        if acls[policy]['afi'] == 4:
            s(conn, "clear configure access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        if acls[policy]['afi'] == 6:
            s(conn, "clear configure ipv6 access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        s(conn, "end")
    if save_config == True:
        s(conn, "write")
Beispiel #12
0
def deploy(hostname=None, acls=None, transport='ssh', save_config=False,
           timeout=60):
    """
    Deploy code in a safe way o a Cisco IOS device.
    """
    try:
        username, enable_pass, password = \
            netrc.netrc().authenticators(hostname)
        account = Account(name=username, password=password,
                          password2=enable_pass)
    except:
        print("ERROR: could not find device in ~/.netrc file")
        print("HINT: either update .netrc or enter username + pass now.")
        try:
            account = read_login()
        except EOFError:
            print("ERROR: could not find proper username + pass")
            print("HINT: set username & pass in ~/.netrc for device %s"
                  % hostname)
            import sys
            sys.exit(2)

    def s(conn, line):
        print("   %s" % line)
        conn.execute(line)

    def collect_interfaces(conn):
        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Outgoing access list is ${Outbound}
  ^  Inbound  access list is ${Inbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ip int | inc ine pro|list is')
        interface_acl_v4 = table.ParseText(conn.response)

        template = """# textfsm
Value Required Interface ([^ ]+)
Value Inbound (.*)
Value Outbound (.*)

Start
  ^${Interface} is up
  ^  Inbound access list ${Inbound}
  ^  Outgoing access list ${Outbound} -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show ipv6 int  | i ine pro|access list')
        interface_acl_v6 = table.ParseText(conn.response)
        template = """# textfsm
Value Required Vty (\d+\s\d+)
Value Inbound4 ([^ ]+)
Value Outbound4 ([^ ]+)
Value Inbound6 ([^ ]+)
Value Outbound6 ([^ ]+)

Start
  ^line vty ${Vty}
  ^ access-class ${Inbound4} in
  ^ access-class ${Outbound4} out
  ^ ipv6 access-class ${Inbound6} in
  ^ ipv6 access-class ${Outbound6} out -> Record Start

"""
        template_file = StringIO(template)
        table = textfsm.TextFSM(template_file)
        s(conn, 'show run | begin ^line vty')
        interface_acl_vty = table.ParseText(conn.response)

        results = {4: interface_acl_v4, 6: interface_acl_v6}
        # add vty lines
        for vty in interface_acl_vty:
            # v4 inbound
            v4_inbound = vty[1] if vty[1] else "not set"
            v4_outbound = vty[2] if vty[1] else "not set"
            v6_inbound = vty[3] if vty[1] else "not set"
            v6_outbound = vty[4] if vty[1] else "not set"
            results[4].append(["vty %s" % vty[0], v4_inbound, v4_outbound])
            results[6].append(["vty %s" % vty[0], v6_inbound, v6_outbound])
        return results

    # main flow of the program starts here
    if transport == 'ssh':
        conn = SSH2(verify_fingerprint=False, debug=0, timeout=timeout)
    elif transport == 'telnet':
        conn = Telnet(debug=0)
    else:
        print("ERROR: Unknown transport mechanism: %s"
              % transport)
        sys.exit(2)
    conn.set_driver('ios')
    conn.connect(hostname)
    conn.login(account)
    conn.execute('terminal length 0')
    conn.auto_app_authorize(account)
    capabilities = {}
    s(conn, "show ipv6 cef")
    capabilities['ipv6'] = False if "%IPv6 CEF not running" in conn.response else True
    if capabilities['ipv6']:
        print("INFO: IPv6 support detected")
    else:
        print("INFO: NO IPv6 support detected, skipping IPv6 ACLs")
    # map into structure:
    # policyname { (int, afi, direction) }
    map_pol_int = {}
    interfaces_overview = collect_interfaces(conn)
    for afi in interfaces_overview:
        for interface, inbound, outbound in interfaces_overview[afi]:
            # add inbound rules to map
            if inbound not in map_pol_int.keys():
                map_pol_int[inbound] = [{"int": interface,
                                        "afi": afi,
                                        "dir": "in"}]
            else:
                map_pol_int[inbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "in"})
            # add outbound
            if outbound not in map_pol_int.keys():
                map_pol_int[outbound] = [{"int": interface,
                                          "afi": afi,
                                          "dir": "in"}]
            else:
                map_pol_int[outbound].append({"int": interface,
                                             "afi": afi,
                                             "dir": "out"})
    print("INFO: interface / policy mapping:")
    pprint(map_pol_int)

    def lock_step(lock, pol, capabilities):
        name = acls[pol]['name']
        afi = acls[pol]['afi']
        if afi == 6 and not capabilities['ipv6']:
            return
        policy = acls[pol]['policy']
        print("INFO: uploading name: %s, afi: %s" % (name, afi))
        s(conn, 'configure terminal')
        if afi == 4:
            try:
                s(conn, "no ip access-list extended %s%s" % (lock, name))
            except:
                pass
            s(conn, "ip access-list extended %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        if afi == 6:
            try:
                s(conn, "no ipv6 access-list %s%s" % (lock, name))
            except:
                pass
            s(conn, "ipv6 access-list %s%s" % (lock, name))
            for line in policy.split('\n'):
                s(conn, line)
        s(conn, "end")

        # then replace ACL on all interfaces / VTYs
        if name in map_pol_int:
            for entry in map_pol_int[name]:
                if not entry['afi'] == afi:
                    continue
                print("INFO: lockstepping policy %s afi %s" % (name, afi))
                s(conn, "configure terminal")
                if entry['int'].startswith('vty '):
                    s(conn, "line %s" % entry['int'])
                    if afi == 4:
                        s(conn, "access-class %s%s %s"
                          % (lock, name, entry['dir']))
                    if afi == 6:
                        s(conn, "ipv6 access-class %s%s %s"
                          % (lock, name, entry['dir']))
                else:
                    s(conn, "interface %s" % entry['int'])
                    if afi == 4:
                        s(conn, "ip access-group %s%s %s"
                          % (lock, name, entry['dir']))
                    if afi == 6:
                        s(conn, "ipv6 traffic-filter %s%s %s"
                          % (lock, name, entry['dir']))
                s(conn, "end")

    for policy in acls:
        for lock in ["LOCKSTEP-", ""]:
            lock_step(lock, policy, capabilities)
        # cleanup
        s(conn, "configure terminal")
        if acls[policy]['afi'] == 4:
            s(conn, "no ip access-list extended LOCKSTEP-%s"
              % acls[policy]['name'])
        if acls[policy]['afi'] == 6 and capabilities['ipv6']:
            s(conn, "no ipv6 access-list LOCKSTEP-%s"
              % acls[policy]['name'])
        s(conn, "end")

    if save_config == True:
        s(conn, "write")
Beispiel #13
0
    def open(self, **kwargs):
        """
        Connect to and login into the device.

        Args:
            hostname: Hostname of the device
            username: Uername to login onto the device
            password: Password to login onto the device
            drivername: Name of the Exscript protocol driver for the device
            username_prompt: REGEX to match the login prompt as defined by Exscript
            password_prompt REGEX to match the login prompt as defined by Exscript

        Returns:
            obj: The device object
        """
        hostname = kwargs.get('hostname', self.hostname)
        username = kwargs.get('username', self.username)
        password = kwargs.get('password', self.password)
        drivername = kwargs.get('drivername', self.drivername)
        username_prompt = kwargs.get('username_prompt', self.username_prompt)
        password_prompt = kwargs.get('password_prompt', self.password_prompt)
        transport = kwargs.get('transport', self.transport)
        incremental_buffer = kwargs.get('incremental_buffer', self.incremental_buffer)

        self.drivername = drivername
        self.hostname = hostname
        self.username = username
        self.password = password
        self.username_prompt = username_prompt
        self.password_prompt = password_prompt
        self.transport = transport
        self.incremental_buffer = incremental_buffer

        transport = str(transport).lower()
        if transport == "ssh":
            self.device = SSH2()
        elif transport == 'telnet':
            self.device = Telnet()
        else:
            raise RuntimeError('Unrecognized transport protocol: %s' % self.transport)

        self.device.set_driver(drivername)
        self.device.set_username_prompt(username_prompt)
        self.device.set_password_prompt(password_prompt)
        if self.error_re:
            self.device.set_error_prompt(self.error_re)
        else:
            self.error_re = self.device.get_error_prompt()

        if self.timeout:
            self.device.set_timeout(self.timeout)
        else:
            self.device.get_timeout()

        # Connect
        try:
            self.device.connect(hostname)
        except:
            raise ConnectionError(hostname)

        # Authenticate
        try:
            self.device.login(Account(self.username, self.password))
        except:
            raise LoginError(hostname)

        # Init terminal length and width
        self.device.autoinit()

        return self.device
Beispiel #14
0
def main():

    args = args_parser()
    print_banner()

    host = args.host
    port = args.port
    username = args.username
    password = args.password
    privatekey = args.privatekey
    passphrase = args.passphrase
    keytype = args.keytype
    ssh = args.ssh
    telnet = args.telnet
    category = args.category
    plugin = args.plugin

    if plugin and (category == None):
        sys.exit(RED + '\n[!] No category\n' + ENDC)

    # Set host
    if host == None:
        host = raw_input('set host' + BLUE + ' > ' + ENDC)

    # Set service
    if (ssh == False) and (telnet == False):
        service = raw_input('set service [ssh|telnet]' + BLUE + ' > ' + ENDC)
        if service.lower() == 'ssh':
            ssh = True
        elif service.lower() == 'telnet':
            telnet = True
    if ssh:
        conn = SSH2()
    elif telnet:
        conn = Telnet()
    else:
        sys.exit(RED + '\n[!] Bad service type. Options: [ssh|telnet]\n' + ENDC)

    # Set username
    if username == None:
        username = raw_input('set username' + BLUE + ' > ' + ENDC)

    # Set password
    if (password == None) and (privatekey == None):
        password = getpass.getpass('set password (leave blank to enter a private key)' + BLUE + ' > ' + ENDC)

    #set privatekey
    if (password == None):

        #set privatekey
        if (privatekey == None):
          privatekey = getpass.getpass('set private key path' + BLUE + ' > ' + ENDC)

        #set passphrase
        if (passphrase == None):
          passphrase = getpass.getpass('set private key passphrase (optional)' + BLUE + ' > ' + ENDC)

        #set keytype
        if (keytype == None):
            keytype = raw_input('set keytype (optional)' + BLUE + ' > ' + ENDC)

        if (keytype != "") and (passphrase != ""):
            key = PrivateKey.from_file(privatekey, password=passphrase, keytype=keytype)
        elif (keytype != ""):
            key = PrivateKey.from_file(privatekey, password=passphrase)
        else:
            key = PrivateKey.from_file(privatekey)

    else:
        key = None

    # Create account
    account = Account(username, password, key = key)
    # Connect and login
    conn.connect(host, port)
    conn.login(account)

    # Try to disable history for current shell session
    conn.execute('unset HISTFILE')

    # Print info about used Exscript driver
    driver = conn.get_driver()
    print BLUE + '\n[i] Using driver: ' + ENDC + driver.name

    # Set logs directory
    logs_path = LOGS_PATH + '/' + host + '-' + str(int(time.time()))

    if category:
        print BLUE + '\n[i] Plugins category: ' + ENDC + category + '\n'
        dict_categories = {}
        dict_plugins = {}

        # Run single plugin
        if plugin:
            try:
                eval_file(conn, INSTALL_PATH + '/plugins/' + category + '/' + plugin)
                dict_plugins[plugin] = conn.response

                print '  %-20s' % (plugin) + '[' + GREEN + 'ok' + ENDC + ']'
            except:
                print '  %-20s' % (plugin) + '[' + RED + 'ko' + ENDC + ']'
                pass

            dict_categories[category] = dict_plugins

        # Run plugins by single category
        else:
            for plugin in sorted(os.listdir(INSTALL_PATH + '/plugins/' + category)):
                try:
                    eval_file(conn, INSTALL_PATH + '/plugins/' + category + '/' + plugin)
                    dict_plugins[plugin] = conn.response

                    print '  %-20s' % (plugin) + '[' + GREEN + 'ok' + ENDC + ']'
                except:
                    print '  %-20s' % (plugin) + '[' + RED + 'ko' + ENDC + ']'
                    pass

            dict_categories[category] = dict_plugins

    # Run all plugins by category
    if (category == None) and (plugin == None):
        dict_categories = {}

        for category in sorted(os.listdir(INSTALL_PATH + '/plugins')):
            print BLUE + '\n[i] Plugins category: ' + ENDC + category + '\n'
            dict_plugins = {}

            for plugin in sorted(os.listdir(INSTALL_PATH + '/plugins/' + category)):
                try:
                    eval_file(conn, INSTALL_PATH + '/plugins/' + category + '/' + plugin)
                    dict_plugins[plugin] = conn.response

                    print '  %-20s' % (plugin) + '[' + GREEN + 'ok' + ENDC + ']'
                except:
                    print '  %-20s' % (plugin) + '[' + RED + 'ko' + ENDC + ']'
                    pass

            dict_categories[category] = dict_plugins

    # Exit and close remote connection
    conn.send('exit\r')
    conn.close()

    # Generate report
    html_report(dict_categories, logs_path)
    print BLUE + '\n[i] Report saved to: ' + ENDC + logs_path + '/index.html\n'
Beispiel #15
0
 def createProtocol(self):
     self.protocol = Telnet(timeout=1)
Beispiel #16
0
 def connect(self, acc, ip):
     acc = Account(*acc)
     self.con = Telnet(driver=driver)
     self.con.connect(ip)
     self.con.login(acc)
     self.con.debug = 1