def main(): args = parse_args() status = parse_status(args.input_log.read()) if args.subcommand == "client": table = create_client_table(status.client_list) elif args.subcommand == "routing": table = create_routing_table(status.routing_table) print("{} last update: {}".format(args.input_log.name, status.updated_at)) default_sorts = ['Connected Since', 'Last Ref'] if args.sort in default_sorts: table = table.get_string( sortby=args.sort, reversesort=True ) else: table = table.get_string( sortby=args.sort, reversesort=False ) print(table)
def _get_openvpn_routing_info(self, host, port=7505, password=None): try: raw_info = self._get_raw_management_info(host, port, password) except ConnectionRefusedError: logger.error('Unable to establish telnet connection to ' f'{host} on {port}. Skipping!') return {} except (OSError, TimeoutError) as error: logger.error( f'Error encountered while connecting to {host}:{port}: {error}. ' 'Skipping!') return {} except Exception: logger.exception( f'Error encountered while connecting to {host}:{port}. Skipping!' ) return {} try: parsed_info = openvpn_status.parse_status(raw_info) return parsed_info.routing_table except openvpn_status.ParsingError as error: logger.error( 'Unable to parse information received from ' f'{host}. ParsingError: {error}. Skipping!', ) return {}
def get_status(self): """Get current status from VPN. Uses openvpn-status library to parse status output: https://pypi.org/project/openvpn-status/ """ raw = self.send_command("status 1") return openvpn_status.parse_status(raw)
def to_python(self, data): if not data: return None try: return parse_status(data) except (AttributeError, ParsingError) as e: msg = 'OpenVPN parsing error: {0}'.format(str(e)) raise ConversionException(msg, data=data)
def to_python(self, data): if not data: return None try: return parse_status(data) except (AttributeError, ParsingError) as e: msg = 'something went wront: {0}'.format(str(e)) print(msg)
def run(self, config): ''' OpenVPN monitoring, needs access to openvpn-status.log file. pip install openvpn-status or pip3 install openvpn-status In /etc/nixstats.ini to enable put: [openvpn] enabled = yes status_path = /etc/openvpn/openvpn-status.log test the plugin by running: sudo -u nixstats nixstatsagent test OpenVPN If you are having permission issues try to run the agent as root user: https://help.nixstats.com/en/article/running-the-monitoring-agent-as-root-user-m0ylxw/ ''' openvpn_clients = {} last_value = {} prev_cache = self.get_agent_cache() # Get absolute values from previous check try: with open(config.get('openvpn', 'status_path')) as logfile: status = parse_status(logfile.read()) except Exception as e: return e try: openvpn_clients['containers'] = len(status.client_list.items()) for key, client in status.client_list.items(): client.common_name = client.common_name.replace('.', '-') openvpn_clients[client.common_name] = {} bytes_out = int(client.bytes_sent) bytes_in = int(client.bytes_received) openvpn_clients[client.common_name]['net_out_bytes'] = self.absolute_to_per_second('%s_%s' % (client.common_name, 'net_out_bytes'), bytes_out, prev_cache) openvpn_clients[client.common_name]['net_in_bytes'] = self.absolute_to_per_second('%s_%s' % (client.common_name, 'net_in_bytes'), bytes_in, prev_cache) last_value['%s_%s' % (client.common_name, 'net_in_bytes')] = bytes_in last_value['%s_%s' % (client.common_name, 'net_out_bytes')] = bytes_out except Exception as e: return e last_value['ts'] = time.time() self.set_agent_cache(last_value) return openvpn_clients
def main(): parser = create_cli() if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() try: status = parse_status(args.file.read()) except: print('Error parsing openvpn status file') sys.exit() if args.lld: lld = {'data': []} for key, value in status.client_list.items(): lld['data'].append({'{#CLIENT_ID}': value.common_name}) print(json.dumps(lld)) elif args.metric: for key, value in status.client_list.items(): if value.common_name == args.id: args.id = key if args.id in status.client_list: peer_bytes_received = status.client_list[args.id].bytes_received peer_bytes_sent = status.client_list[args.id].bytes_sent peer_connected_since = status.client_list[args.id].connected_since metric = { 'bytes_received': peer_bytes_received, 'bytes_sent': peer_bytes_sent, 'connected_since': int(time.mktime(peer_connected_since.timetuple())) } print(json.dumps(metric)) else: print('Peer with ID {} not found'.format(args.id)) sys.exit()
#!/usr/bin/env python from openvpn_status import parse_status from pprint import pprint from requests import get from json import loads with open('/etc/openvpn/openvpn-status.log') as logfile: status = parse_status(logfile.read()) # print(status.updated_at) # datetime.datetime(2015, 6, 18, 8, 12, 15) print( '<table class="table"><thead><tr><th>name</th><th>VPN IP</th><th>real IP</th><th>connected since</th><th>location</th><th>Mb received / sent</th></thead>' ) #for k in status.client_list: # print k # c = status.client_list[k] # print('%s: %s (since: %s)' % (c.common_name, c.real_address, c.connected_since)) for k in sorted(status.routing_table): c = status.routing_table[k] cl = status.client_list[str(c.real_address)] try: url = 'http://api.ipstack.com/' + str(c.real_address).split( ':')[0] + '?access_key=da89982343c6599b8eedf0cbb7e4b9bd' geoip = get(url).json() city = geoip['city'] latitude = geoip['latitude'] longitude = geoip['longitude'] except: city = ''
def test_shortcut(): with raises(openvpn_status.ParsingError): openvpn_status.parse_status('') with raises(openvpn_status.ParsingError): openvpn_status.parse_status(b'')
def get_stats(self): with open(self.openvpn_status_log_file, 'r') as logfile: return parse_status(logfile.read())
def to_python(self, data): return parse_status(data)
def to_python(self, data): try: return parse_status(data) except (AttributeError, ParsingError): return None
def get_user(self): status = parse_status(self.logfile.read()) return status.client_list
def test_shortcut(): with raises(openvpn_status.ParsingError): openvpn_status.parse_status(u'') with raises(openvpn_status.ParsingError): openvpn_status.parse_status(b'')