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!")
class TelnetBehavior: __metaclass__ = ABCMeta telnet_username = None telnet_password = None exscript_driver = None def __init__(self, host_address, port=23): self.host_address = host_address self.port = port 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 def __exit__(self, exc_type, exc_val, exc_tb): self.conn.send('exit\r') self.conn.close(force=True) def execute(self, command): self.conn.execute(command) return self.conn.response
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!")
class JuniperTelnetBehavior(object): def __init__(self, host_address): self.host_address = host_address 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 def __exit__(self, exc_type, exc_val, exc_tb): self.conn.send('exit\r') self.conn.close(force=True) def execute(self, command): self.conn.execute(command) return self.conn.response
if mac in line: line = line.split() macOUI = line[1] macOUI = macOUI[0:4]+macOUI[5:9]+macOUI[10:14] API_CALL = urllib2.urlopen(maclookup_url+macOUI).read() API_CALL = API_CALL.split(",") Vendor_result = API_CALL[4] Vendor = Vendor_result[10: ] port = str(line[3]) conn.execute("show run int " + port) port_config = conn.response print print print "===========================" print "MAC %s" % line[1] print "Vendor %s" % Vendor print port_config = port_config.splitlines() del port_config[0:5] del port_config[-3: ] for line in port_config: print line print "===========================" os.remove("~ARP-Output-tmp.txt") os.remove("~MAC-Output-tmp.txt") conn.send('exit\r') conn.close()
def main(): args = args_parser() print_banner() host = args.host port = args.port username = args.username password = args.password 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: password = getpass.getpass('set password' + BLUE + ' > ' + ENDC) # Create account account = Account(username, password) # 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'
class BeagleDriver(object): """ Base Class for driver Classes. Attributes: 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 username_prompt: REGEX to match the login prompt as defined by Exscript password_prompt REGEX to match the login prompt as defined by Exscript findreplace: List of findreplace dictionaries. See sub() for more details error_re: List of REGEXes to match errors on the device timeout: Timeout for the command in seconds """ def __init__(self, **kwargs): """ Init method of the Class. 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 findreplace: List of findreplace dictionaries. See sub() for more details error_re: List of REGEXes to match errors on the device timeout: Timeout for the command in seconds """ self.hostname = kwargs.get('hostname', None) self.username = kwargs.get('username', None) self.password = kwargs.get('password', None) self.drivername = kwargs.get('drivername', None) self.username_prompt = kwargs.get('username_prompt', '[Uu]sername.*:') self.password_prompt = kwargs.get('password_prompt', '[Pp]assword.*:') self.findreplace = kwargs.get('findreplace', []) self.error_re = kwargs.get('error_re', None) self.timeout = kwargs.get('timeout', None) self.transport = kwargs.get('transport', None) self.incremental_buffer = kwargs.get('incremental_buffer', StringIO()) self.device = None def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_value, exc_traceback): self.close() def sub(self, text, findreplace=None): """ Returns the string obtained by replacing the occurrences of find in text with replace. Args: text: Text to be transformed findreplace: List od dicts with the following keys: find: is regular expression that can contain named \ group identified by (?P<name>...) replace: is a string and supports printf() format. \ Group names can be used as a reference Returns: str: Transformed text """ if findreplace: self.findreplace = findreplace if not self.findreplace: return text result = list() for line in text.splitlines(): for item in self.findreplace: try: regex = re.compile(r'%s' % item['find']) except re.error: continue matches = [ # start, end, dictionary with matches [_.start(), _.end(), _.groupdict()] for _ in regex.finditer(line) ] if matches: end = 0 oldend = 0 _ = list() for start, end, groupdict, in matches: # append from oldend (at first run equals to 0) up to the matched dict _.append(line[oldend:start]) # replaces matches from groupdict with "replace" # we have to replace boolean False matches (like None) with empty strings _.append(item['replace'] % {k: (v or "") for k, v in groupdict.items()}) # oldend is equal to end oldend = end _.append(line[end:]) line = ''.join(_) result.append(line) return '\n'.join(result) 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 def close(self): """ Disconnects from the device Returns: bool: Always returns True """ try: self.device.send('exit\n') self.device.send('exit\n') except Exception: pass self.device.close(force=True) return True def run(self, command, **kwargs): """ Executes command on the device. Args: command: String of the command to be executed 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: str: Output of the command after sub() has been applied """ if not self.device or not self.device.proto_authenticated: self.open(**kwargs) def event_handler(arg): self.incremental_buffer.write(arg) try: # Connect a data event listener self.device.data_received_event.connect(event_handler) self.device.execute(command) result = self.device.response # Disconnect data event listener self.device.data_received_event.disconnect(event_handler) except InvalidCommandException: raise CommandError(self.hostname, self.device.response) return self.sub(result) def ping(self, address, vrf='global', afi=1, safi=1, loopback=False): """ Placeholder for the actual ping method. Args: address: IP address or hostname to ping vrf: VRF for IP route lookup afi: BGP AFI identifier safi: BGP SAFI identifier loopback: Name of the loopback interface Returns: Always raises error. Actual function will return output of the ping command modified by sub() """ raise RuntimeError('Not implemented yet') def traceroute(self, address, vrf='global', afi=1, safi=1, loopback=False): """ Placeholder for the actual traceroute method. Args: address: IP address or hostname to traceroute vrf: VRF for IP route lookup afi: BGP AFI identifier safi: BGP SAFI identifier loopback: Name of the loopback interface Returns: Always raises error. Actual function will return output of the traceroute command modified by sub() """ raise RuntimeError('Not implemented yet') def show_route(self, address, vrf='global', afi=1, safi=1): """ Placeholder for the actual show route method. Args: address: IP address to lookup the route vrf: VRF for route lookup afi: BGP AFI identifier safi: BGP SAFI identifier loopback: Name of the loopback interface Returns: Always raises error. Actual function will return output of the show route command modified by sub() """ raise RuntimeError('Not implemented yet') def show_bgp(self, address, vrf='global', afi=1, safi=1): """ Placeholder for the actual show BGP route method. Args: address: IP address to lookup the BGP route vrf: VRF for BGP route lookup afi: BGP AFI identifier safi: BGP SAFI identifier loopback: Name of the loopback interface Returns: Always raises error. Actual function will return output of the show BGP route command modified by sub() """ raise RuntimeError('Not implemented yet') def show_bgp_neighbors(self, address, vrf='global', afi=1, safi=1): """ Placeholder for the actual show bgp neighbor method. Args: address: Address of the neighbor vrf: VRF of the neighor afi: BGP AFI identifier safi: BGP SAFI identifier Returns: Always raises error. Actual function will return output of the show bgp neighbor command modified by sub() """ raise RuntimeError('Not implemented yet') def show_bgp_summary(self, vrf='global', afi=1, safi=1): """ Placeholder for the actual show bgp summary method. Args: vrf: VRF for the summary afi: BGP AFI identifier safi: BGP SAFI identifier Returns: Always raises error. Actual function will return output of the show bgp summary command modified by sub() """ raise RuntimeError('Not implemented yet')
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'