from servicebase import ServiceBase import paramiko import datetime import re class ServiceDelegate(ServiceBase) : _connections = None def get_arguments(cls) : """Returns an array of information used to construct an argumentparser argument.""" return ['-r', '--vpn','store_true','Return VPN information about the subject (openvpn)'] def startup(self) : for requirement in ['hosts','username','key'] : if requirement not in self._config or (requirement in self._config and self._config[requirement] == ''): self._error.append('Missing required config option ' + requirement) rself._error self.hosts = self._config['hosts'] self.debug('Logging into OpenVPN servers...',1) connections = {} for host in self._config['hosts'] : try : sshclient = paramiko.SSHClient() sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshclient.connect(host,22,username=self._config['username'],password=self._config['key']) connections.update({host:sshclient}) except Exception as exception : self._error.append('Unable to ssh into ' + host + ': ' + str(exception)) self._connections = connections def shutdown(self) : for connection in self._connections.values() : connection.close() def lookup(self,subject) : search_command = 'sudo -S cat /var/log/openvpn/openvpn.log | grep \'primary virtual IP for\' | grep -i \'' + subject + '\' | tail -n 1' final_dictionary = {} for host,connection in self._connections.items() : try: stdin,stdout,stderr=connection.exec_command(search_command) stdin.write(self._config['key'] + '\n') stdin.flush() result = stdout.readlines() if len(result) > 0 : self.debug('Retrieved line from ssh session: \n' + result[0].strip(),2) result = result[0] else : result = '' items = {'nat_address': r'.*\ ([0-9a-fA-F\.\:]*)$', 'source_address': r'.*/([0-9a-fA-F\.]*)\:.*', 'user_name': r'.*primary\ virtual\ IP\ for\ ([a-zA-Z0-9\.]*)/.*', 'timestamp': r'^([a-zA-Z]{3}\ +[0-9]{1,2}\ [0-9:]*)\ .*'} return_dictionary = {} for item in items.keys() : matches = re.match(items[item],result) if matches and len(matches.groups()) and matches[1] : return_dictionary.update({item: matches[1]}) if len(return_dictionary) > 0 : return_dictionary.update({'host':host}) epoch = None if 'timestamp' in final_dictionary.keys() and 'timestamp' in return_dictionary.keys() : epoch = int(datetime.datetime.strptime(return_dictionary['timestamp'] + ' ' + str(datetime.datetime.now().year), '%b %d %H:%M:%S %Y').strftime('%s')) if len(return_dictionary) > 0 : if epoch : if epoch > int(datetime.datetime.strptime(final_dictionary['timestamp'] + ' ' + str(datetime.datetime.now().year), '%b %d %H:%M:%S %Y').strftime('%s')) : final_dictionary = {} final_dictionary.update(return_dictionary) else : final_dictionary = return_dictionary else : self.debug('No results for ' + subject + ' on host ' + host,2) except Exception as exception : raise exception self._error.append('Unable to get results from ssh: ' + str(exception)) if len(final_dictionary) > 0 : return final_dictionary else : return None