def ros_api_connect(self, username, password, host, port, use_ssl): # connect to routeros api conn_status = {"connection": {"username": username, "hostname": host, "port": port, "ssl": use_ssl, "status": "Connected"}} try: if use_ssl is True: if not port: port = 8729 conn_status["connection"]["port"] = port ctx = ssl.create_default_context() ctx.check_hostname = False ctx.set_ciphers('ADH:@SECLEVEL=0') api = connect(username=username, password=password, host=host, ssl_wrapper=ctx.wrap_socket, port=port) else: if not port: port = 8728 conn_status["connection"]["port"] = port api = connect(username=username, password=password, host=host, port=port) except Exception as e: conn_status["connection"]["status"] = "error: %s" % e self.module.fail_json(msg=to_native([conn_status])) return api
def test_connect_raises_when_failed_login(transport_mock): failed = Mock(name='failed', side_effect=TrapError(message='failed to login')) with pytest.raises(TrapError): connect(host='127.0.0.1', username='******', password='', login_method=failed)
def ros_api_connect(self, username, password, host, port, use_tls, validate_certs, validate_cert_hostname, ca_path): # connect to routeros api conn_status = { "connection": { "username": username, "hostname": host, "port": port, "ssl": use_tls, "status": "Connected" } } try: if use_tls: if not port: port = 8729 conn_status["connection"]["port"] = port ctx = ssl.create_default_context(cafile=ca_path) wrap_context = ctx.wrap_socket if not validate_certs: ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE elif not validate_cert_hostname: ctx.check_hostname = False else: # Since librouteros doesn't pass server_hostname, # we have to do this ourselves: def wrap_context(*args, **kwargs): kwargs.pop('server_hostname', None) return ctx.wrap_socket(*args, server_hostname=host, **kwargs) api = connect(username=username, password=password, host=host, ssl_wrapper=wrap_context, port=port) else: if not port: port = 8728 conn_status["connection"]["port"] = port api = connect(username=username, password=password, host=host, port=port) except Exception as e: conn_status["connection"]["status"] = "error: %s" % e self.module.fail_json(msg=to_native([conn_status])) return api
def get_data_from_api(user, password, ip, method_type): try: api = '' mikrotik = '' identity = '' group = '' version = '' model = '' del api del mikrotik api = connect(username=user, password=password, host=ip, login_method=method_type) mikrotik = api.path('system', 'identity') for row in mikrotik: identity = row.get('name') del api del mikrotik api = connect(username=user, password=password, host=ip, login_method=method_type) mikrotik = api.path('user').select('name', 'group').where(Key('name') == user) for row in mikrotik: group = row.get('group') del api del mikrotik api = connect(username=user, password=password, host=ip, login_method=method_type) mikrotik = api.path('system', 'resource') for row in mikrotik: version = row.get('version') del api del mikrotik api = connect(username=user, password=password, host=ip, login_method=method_type) mikrotik = api.path('system', 'routerboard') for row in mikrotik: model = row.get('model') if group != '' and group != 'full': to_MySQL((ip, user, password, group_ssh, identity_ssh, version_ssh, modelo_ssh, '8728'), puertos) result = (ip, user, password, identity, group, version, model, '8728') return result except: print_error(sys.exc_info()[0]) return 'error'
def getdata(): val_data = get_validation_data() ROUTEROS_IP = val_data["ROUTEROS_IP"] ROUTEROS_PORT = int(val_data["ROUTEROS_PORT"]) ROUTEROS_USERNAME = val_data["ROUTEROS_USERNAME"] ROUTEROS_PASSWORD = val_data["ROUTEROS_PASSWORD"] logging.info("run: using routeros device %s on port %s using username ", ROUTEROS_IP, ROUTEROS_PORT, ROUTEROS_USERNAME) routeros = connect(username=ROUTEROS_USERNAME, password=ROUTEROS_PASSWORD, host=ROUTEROS_IP) mikdata = routeros('/system/resource/print') perfdata = { "time": datetime.datetime.now().isoformat(), "cpupct": mikdata[0]["cpu-load"], "fmem": mikdata[0]["free-memory"], "fhdd": mikdata[0]["free-hdd-space"], } json_perfdata = json.dumps(perfdata) print json_perfdata
def connect_to_device(self): """Connect to Mikrotik method.""" import librouteros try: self.client = librouteros.connect(self.host, self.username, self.password, port=int(self.port), encoding='utf-8') try: routerboard_info = self.client( cmd='/system/routerboard/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): routerboard_info = None raise if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True try: self.capsman_exist = self.client( cmd='/caps-man/interface/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.capsman_exist = False if not self.capsman_exist: _LOGGER.info( 'Mikrotik %s: Not a CAPSman controller. Trying ' 'local interfaces ', self.host) try: self.wireless_exist = self.client( cmd='/interface/wireless/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.wireless_exist = False if not self.wireless_exist: _LOGGER.info( 'Mikrotik %s: Wireless adapters not found. Try to ' 'use DHCP lease table as presence tracker source. ' 'Please decrease lease time as much as possible.', self.host) except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def connect_to_device(self): """Connect to Mikrotik method.""" # pylint: disable=import-error import librouteros try: self.client = librouteros.connect(self.host, self.username, self.password, port=int(self.port)) routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True self.wireless_exist = self.client( cmd='/interface/wireless/getall') if not self.wireless_exist: _LOGGER.info( 'Mikrotik %s: Wireless adapters not found. Try to ' 'use DHCP lease table as presence tracker source. ' 'Please decrease lease time as much as possible.', self.host) except (librouteros.exceptions.TrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def connect_to_device(self): """Connect to Mikrotik method.""" # pylint: disable=import-error import librouteros try: self.client = librouteros.connect( self.host, self.username, self.password, port=int(self.port) ) routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True self.wireless_exist = self.client( cmd='/interface/wireless/getall' ) if not self.wireless_exist: _LOGGER.info( 'Mikrotik %s: Wireless adapters not found. Try to ' 'use DHCP lease table as presence tracker source. ' 'Please decrease lease time as much as possible.', self.host ) except (librouteros.exceptions.TrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def get_leases(self, username, password): ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE method = plain api = connect( username=username, password=password, host=self.ipaddress, ssl_wrapper=ctx.wrap_socket, port=self.port, login_method=method ) ipaddress = Key('active-address') macaddress = Key('mac-address') hostname = Key('host-name') status = Key('status') data = api.path('/ip/dhcp-server/lease').select( ipaddress, macaddress, hostname).where(status == 'bound') leases = ( (l['mac-address'], l['active-address'], l['host-name']) if 'host-name' in l.keys() else ( l['mac-address'], l['active-address'], '') for l in data) return leases
def main(): home = os.path.dirname(os.path.abspath(__file__)) os.chdir(home) config = ConfigParser.RawConfigParser() config.read('application.conf') out_dir = config.get('application', 'out_dir') timeout = float(config.get('application', 'timeout')) boxes = json.loads(config.get('application', 'boxes_json')) logging.config.fileConfig('logging.conf') setup_encoding() for box in boxes: host = box['host'] username = box['username'] password = box['password'] try: logging.info('Processing %s', host) api = connect(host=host, username=username, password=password, timeout=timeout) entries = api(cmd='/ip/arp/print') api.close() data = set([(entry['mac-address'], entry['interface']) for entry in entries if 'mac-address' in entry]) file_name = datetime.now().strftime('%Y%m%d%H%M%S') + '-' + host + '.gz' file_path = os.path.join(out_dir, file_name) with gzip.open(file_path, 'wb') as file: for obj in data: file.write(' '.join(obj) + '\n') logging.info('%s done', host) except: _, exc_value, _ = sys.exc_info() logging.error(exc_value)
def connect_to_device(self): """Connect to Mikrotik method.""" # pylint: disable=import-error import librouteros try: self.client = librouteros.connect( self.host, self.username, self.password, port=int(self.port) ) routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True except (librouteros.exceptions.TrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def connect_to_device(self): """Connect to Mikrotik device.""" self._connected = False _LOGGER.debug("[%s] Connecting to Mikrotik device", self._host) kwargs = { "encoding": self._encoding, "login_methods": self._login_method, "port": self._port, } if self._use_ssl: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE kwargs["ssl_wrapper"] = ssl_context.wrap_socket try: self._client = librouteros.connect(self._host, self._user, self._password, **kwargs) self._connected = True except ( librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError, ) as api_error: _LOGGER.error("Mikrotik %s: %s", self._host, api_error) self._client = None return False self.hostname = self.get_hostname() _LOGGER.info("Mikrotik Connected to %s (%s)", self.hostname, self._host) return self._connected
def getdata(): val_data = get_validation_data() ROUTEROS_IP = val_data["ROUTEROS_IP"] ROUTEROS_PORT = int(val_data["ROUTEROS_PORT"]) ROUTEROS_USERNAME = val_data["ROUTEROS_USERNAME"] ROUTEROS_PASSWORD = val_data["ROUTEROS_PASSWORD"] logging.info("run: using routeros device %s on port %s using username ", ROUTEROS_IP, ROUTEROS_PORT, ROUTEROS_USERNAME) routeros = connect(username=ROUTEROS_USERNAME, password=ROUTEROS_PASSWORD, host=ROUTEROS_IP) mikdata = routeros('/system/resource/print') perfdata = { "time": datetime.datetime.now().isoformat(), "uptime": mikdata[0]["uptime"], "architecture-name": mikdata[0]["architecture-name"], "version": mikdata[0]["version"], "cpu-frequency": mikdata[0]["cpu-frequency"], "total-memory": mikdata[0]["total-memory"], "total-hdd-space": mikdata[0]["total-hdd-space"], "architecture-name": mikdata[0]["architecture-name"], "board-name": mikdata[0]["board-name"] } json_perfdata = json.dumps(perfdata) print(json_perfdata)
def get_api(hass, entry): """Connect to Mikrotik hub.""" _LOGGER.debug("Connecting to Mikrotik hub [%s]", entry[CONF_HOST]) _login_method = (login_plain, login_token) kwargs = {"login_methods": _login_method, "port": entry["port"]} if entry[CONF_VERIFY_SSL]: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE _ssl_wrapper = ssl_context.wrap_socket kwargs["ssl_wrapper"] = _ssl_wrapper try: api = librouteros.connect( entry[CONF_HOST], entry[CONF_USERNAME], entry[CONF_PASSWORD], **kwargs, ) _LOGGER.debug("Connected to %s successfully", entry[CONF_HOST]) return api except ( librouteros.exceptions.LibRouterosError, socket.error, socket.timeout, ) as api_error: _LOGGER.error("Mikrotik %s error: %s", entry[CONF_HOST], api_error) if "invalid user name or password" in str(api_error): raise LoginError raise CannotConnect
def api_connect(self, username, password, port=8728): try: # version >= 6.43 self.__api = librouteros.connect(host=self.__host, username=username, password=password, login_method=librouteros.plain) except: try: # version < 6.43 self.__api = librouteros.connect( host=self.__host, username=username, password=password, login_method=librouteros.token) except: raise ConnectionError('Connection error')
def reconnect(self): from librouteros import connect from librouteros.login import login_plain self._api = connect(host=self._host, port=self._port, username=self._username, password=self._password, login_methods=(login_plain, ))
def auth(host, username, password): method = (plain, ) try: api = connect(username=username, password=password, host=host, login_methods=method) except: return False return api
def open(self): try: self.api = connect(host=self.hostname, username=self.username, password=self.password, timeout=self.timeout) except (TrapError, FatalError, ConnectionError, MultiTrapError) as exc: raise ConnectionException( 'Could not connect to {}:{} - [{!r}]'.format( self.hostname, self.port, exc))
def login(username, password, device): try: api = connect(username=username, password=password, host=device, login_methods=method) return api except ConnectionError: print('Connection has either been refused, or the host is unreachable. Check if API is exposed on device.') return None except Exception as unknown_error: print('Error has occured: {}'.format(unknown_error)) return None
def testAuth(ip, password): try: api = connect(username='******', password=password, host=ip) api(cmd='/ip/service/print') try: api(cmd='/quit') except librouteros.exceptions.FatalError: pass except (librouteros.exceptions.ConnectionError, socket.gaierror): pass
def api_session(): for x in range(10): try: return librouteros.connect(host='127.0.0.1', port=8728, username='******', password='') except (librouteros.ConnectionError, socket.error, socket.timeout): sleep(1) else: raise librouteros.ConnectionError('could not connect to device')
def get_api(): try: api = connect( host=host, username=username, password=password, port=port) _LOGGER.info("Connected to %s:%u", host, port) return api except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", str(api_error))
def connect(self): try: self.api = connect(host=self.host, username=self.username, password=self.password, port=self.port, login_methods=plain) self.path = self.api.path("") self.last_activity = time() self.is_connected = True except Exception as e: self.error = e
def open(self): try: self.api = connect( host=self.hostname, username=self.username, password=self.password, timeout=self.timeout ) except (TrapError, FatalError, ConnectionError, MultiTrapError) as exc: raise ConnectionException( 'Could not connect to {}:{} - [{!r}]'.format(self.hostname, self.port, exc) )
def __init__(self, module): self._module = module username = self._module.params['username'] password = self._module.params['password'] host = self._module.params['host'] port = self._module.params['port'] timeout = self._module.params['timeout'] use_ssl = self._module.params['use_ssl'] if not HAS_LIB: self._module.fail_json( msg="RouterOS API support requires `librouteros` " + "Python package - pip install librouteros") else: if use_ssl: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE ctx.check_hostname = False ctx.set_ciphers('ADH') self._api = librouteros.connect( host=host, port=port, username=username, password=password, timeout=timeout, ssl_wrapper=ctx.wrap_socket, ) else: self._api = librouteros.connect( host=host, port=port, username=username, password=password, timeout=timeout, )
def upload_and_update(firewall_file_name): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(mikrotik_host, username=mikrotik_user, password=mikrotik_pass, allow_agent=False, look_for_keys=False) with ssh.open_sftp() as sftp: sftp.put(firewall_file_name, '/{}'.format(firewall_file_name)) ssh.close() api = ros.connect(host=mikrotik_host, username=mikrotik_user, password=mikrotik_pass) params = {'file-name': firewall_file_name} api(cmd='/import', **params) api.close()
def main(): Dict1 = {} Dict2 = {} Flag = 1 Count = 0 #router loopback IP to be checked from a file #file should have only router loopback IP perline nothing else try: RouterID = [line.rstrip('\n') \ for line in open('RouterID.txt')] except Exception: e = sys.exc_info()[0] log(e) sys.exit(1) ## Defining the API Connection for x in RouterID: try: api = connect(username='******', password='', host=x) ## Command run on each router bgp_peers = api(cmd='/routing/bgp/peer/print') for i in bgp_peers: if str(i['disabled']) == 'False': Dict1.update({ i['remote-address']: { 'router_id': x, 'state': i['state'] } }) api.close() except Exception: e = sys.exc_info()[0] log(e) #Finding Number of Down Peers. for Key, Value in Dict1.items(): if Dict1[Key]['state'] != "established": Dict2.update({Key: Value}) Flag = 0 Count += 1 if Flag == 0: print("%s peer_down" % (Count), end=': ') for Key, Value in Dict2.items(): print("neighbor '%s' of router '%s' is down" % (Key, Value['router_id']), end=': ') else: print(1)
def login(username, password, device): # manages connection process. try: api = connect(username=username, password=password, host=device, login_methods=method) return api except ConnectionError as connectError: print('Connection has either been refused, or the host is unreachable. Check if API is exposed on device.') with open('log-{}.txt'.format(currentDate), 'a') as file: file.write('Error has occured: {}\n'.format(connectError)) return None except Exception as unknown_error: print('Error has occured: {}'.format(unknown_error)) with open('log-{}.txt'.format(currentDate), 'a') as file: file.write('Error has occured: {}\n'.format(unknown_error)) return None
def api_session(port): last_exc = None for _ in range(30): try: return connect( host='127.0.0.1', port=port, username='******', password='', ) except (LibRouterosError, socket.error, socket.timeout) as exc: last_exc = exc sleep(1) raise RuntimeError('Could not connect to device. Last exception {}'.format(last_exc))
def connect(self): conf = get_conf() try: ssl_layer = ssl.create_default_context() ssl_layer.check_hostname = False ssl_layer.set_ciphers('ADH:@SECLEVEL=0') mkapi = librouteros.connect(username=conf['mk_admin_user'], password=conf['mk_admin_pw'], host=self.ip, ssl_wrapper=ssl_layer.wrap_socket, port=8729) except Exception as err: print('Problem connecting to ' + self.device_name + '. Error was: ' + str(err)) return err return mkapi
def open(self): method = self.optional_args.get('login_method', 'plain') method = getattr(librouteros.login, method) try: self.api = connect( host=self.hostname, username=self.username, password=self.password, port=self.port, timeout=self.timeout, login_method=method, ssl_wrapper=self.ssl_wrapper, ) except (TrapError, FatalError, socket.timeout, socket.error, MultiTrapError) as exc: # pylint: disable=raise-missing-from raise ConnectionException(f"Could not connect to {self.hostname}:{self.port} - [{exc!r}]")
def connect_to_device(self): import librouteros try: self.client = librouteros.connect( self.host, self.user, self.password, port=int(self.port), encoding='utf-8', timeout=3, ) try: routerboard = self.client(cmd='/system/routerboard/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): routerboard = None if routerboard: logger.info('Connected to Mikrotik {}'.format( routerboard[0].get('model', 'Router'))) try: self.capsman_exist = self.client( cmd='/caps-man/interface/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.capsman_exist = False try: self.wireless_exist = self.client( cmd='/interface/wireless/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.wireless_exist = False except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError) as api_error: logger.error('Connection error: {}'.format(api_error)) return False return True
def main(): pw = getpass.getpass() try: api = connect(args.host, args.user, pw, logger=mainlog) except (TrapError, ConnectionError) as err: exit(err) except KeyboardInterrupt: pass else: try: selectloop(api) except KeyboardInterrupt: pass except (ConnectionError, FatalError) as e: print(e) finally: api.close()
def main(): pw = getpass.getpass() try: api = connect(args.host, args.user, pw, logger=mainlog) except (TrapError, ConnectionError) as err: exit(err) except KeyboardInterrupt: pass else: try: selectloop(api) except KeyboardInterrupt: pass except (ConnectionError, FatalError) as e: print(e) finally: api.close()
def main(): home = os.path.dirname(os.path.abspath(__file__)) os.chdir(home) config = ConfigParser.RawConfigParser() config.read('application.conf') timeout = float(config.get('application', 'timeout')) additional_usernames = filter(None, config.get('application', 'additional_usernames').split(',')) additional_passwords = config.get('application', 'additional_passwords').split(',') boxes_csv = config.get('application', 'boxes_csv') success_out = config.get('application', 'success_out') unable_to_login_out = config.get('application', 'unable_to_login_out') logging.config.fileConfig('logging.conf') boxes = [] with open(boxes_csv, 'rb') as f: reader = csv.DictReader(f) fieldnames = reader.fieldnames for r in reader: boxes.append({fieldnames[i]: r[fieldnames[i]] for i in range(len(fieldnames))}) logging.info('%d box(es) will be checked', len(boxes)) WRITE_BUFFER_SIZE = 0 with open(success_out, 'wb', WRITE_BUFFER_SIZE) as success_out_f, open(unable_to_login_out, 'wb', WRITE_BUFFER_SIZE) as unable_to_login_out_f: success_out_writer = csv.writer(success_out_f) unable_to_login_out_writer = csv.writer(unable_to_login_out_f) processed = 0 for box in boxes: host = box['host'] username = box['username'] password = box['password'] usernames = [username] + additional_usernames passwords = [password] + additional_passwords logging.info('Processing %s', host) for u in usernames: for p in passwords: try: api = connect(host=host, username=u, password=p, timeout=timeout) identity = api(cmd='/system/identity/print')[0]['name'] api.close() success_out_writer.writerow((host, u, p, identity)) logging.info("Success") break except: _, exc_value, _ = sys.exc_info() logging.error(exc_value) if (str(exc_value) != "cannot log in"): break else: continue break else: unable_to_login_out_writer.writerow([host]) logging.info('%s done', host) processed += 1 if (processed % 50 == 0): logging.info('%d boxes processed', processed) logging.info('Total %d box(es) processed', processed)
def connect_to_device(self): """Connect to Mikrotik method.""" import librouteros try: self.client = librouteros.connect( self.host, self.username, self.password, port=int(self.port), encoding='utf-8' ) try: routerboard_info = self.client( cmd='/system/routerboard/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): routerboard_info = None raise if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True try: self.capsman_exist = self.client( cmd='/caps-man/interface/getall' ) except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.capsman_exist = False if not self.capsman_exist: _LOGGER.info( 'Mikrotik %s: Not a CAPSman controller. Trying ' 'local interfaces ', self.host ) try: self.wireless_exist = self.client( cmd='/interface/wireless/getall' ) except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.wireless_exist = False if not self.wireless_exist: _LOGGER.info( 'Mikrotik %s: Wireless adapters not found. Try to ' 'use DHCP lease table as presence tracker source. ' 'Please decrease lease time as much as possible.', self.host ) except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def connect_to_device(self): """Connect to Mikrotik method.""" import librouteros try: kwargs = { 'port': self.port, 'encoding': self.encoding } if self.ssl: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE kwargs['ssl_wrapper'] = ssl_context.wrap_socket self.client = librouteros.connect( self.host, self.username, self.password, **kwargs ) try: routerboard_info = self.client( cmd='/system/routerboard/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): routerboard_info = None raise if routerboard_info: _LOGGER.info( "Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True try: self.capsman_exist = self.client( cmd='/caps-man/interface/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.capsman_exist = False if not self.capsman_exist: _LOGGER.info( "Mikrotik %s: Not a CAPSman controller. Trying " "local interfaces", self.host) try: self.wireless_exist = self.client( cmd='/interface/wireless/getall') except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError): self.wireless_exist = False if not self.wireless_exist and not self.capsman_exist \ or self.method == 'ip': _LOGGER.info( "Mikrotik %s: Wireless adapters not found. Try to " "use DHCP lease table as presence tracker source. " "Please decrease lease time as much as possible", self.host) if self.method: _LOGGER.info( "Mikrotik %s: Manually selected polling method %s", self.host, self.method) except (librouteros.exceptions.TrapError, librouteros.exceptions.MultiTrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected
def main(): if (len(sys.argv)) != 2: print('Usage: {0} /path/to/script'.format(sys.argv[0])) sys.exit(1) script_path = sys.argv[1] if (not os.path.isfile(script_path)): print('File {0} does not exist'.format(sys.argv[1])) sys.exit(1) home = os.path.dirname(os.path.abspath(__file__)) os.chdir(home) config = ConfigParser.RawConfigParser() config.read('application.conf') timeout = float(config.get('application', 'timeout')) boxes_csv = config.get('application', 'boxes_csv') results_out = config.get('application', 'results_out') logging.config.fileConfig('logging.conf') setup_encoding() boxes = [] with open(boxes_csv, 'rb') as f: reader = csv.DictReader(f) fieldnames = reader.fieldnames for r in reader: boxes.append({fieldnames[i]: r[fieldnames[i]] for i in range(len(fieldnames))}) logging.info('%d box(es) will be processed', len(boxes)) script = '' with open(script_path) as f: script = f.read().splitlines() WRITE_BUFFER_SIZE = 0 with open(results_out, 'wb', WRITE_BUFFER_SIZE) as results_out_f: processed = 0 for box in boxes: host = box['host'] username = box['username'] password = box['password'] print('# -----[ {0} ]-----'.format(host), file=results_out_f) try: logging.info('Processing %s', host) api = connect(host=host, username=username, password=password, timeout=timeout) for line in script: cmd = line.strip() if (len(cmd) > 0 and not line.startswith('#')): print('# {0}'.format(cmd), file=results_out_f) splitted = cmd.split(' ', 1) command = splitted[0] arguments = dict() if (len(splitted) == 2): arguments = json.loads(splitted[1]) result = api(cmd=command, **arguments) print(json.dumps(result), file=results_out_f) api.close() logging.info('%s done', host) except: _, exc_value, _ = sys.exc_info() logging.error(exc_value) processed += 1 if (processed % 50 == 0): logging.info('%d boxes processed', processed) logging.info('Total %d box(es) processed', processed)