id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
18,300
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_command_attributes
def set_command_attributes(self, name, attributes): """ Sets the xml attributes of a specified command. """ if self.command_exists(name): command = self.commands.get(name) command['attributes'] = attributes
python
def set_command_attributes(self, name, attributes): if self.command_exists(name): command = self.commands.get(name) command['attributes'] = attributes
[ "def", "set_command_attributes", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "self", ".", "command_exists", "(", "name", ")", ":", "command", "=", "self", ".", "commands", ".", "get", "(", "name", ")", "command", "[", "'attributes'", "]"...
Sets the xml attributes of a specified command.
[ "Sets", "the", "xml", "attributes", "of", "a", "specified", "command", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L243-L247
18,301
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scanner_param
def add_scanner_param(self, name, scanner_param): """ Add a scanner parameter. """ assert name assert scanner_param self.scanner_params[name] = scanner_param command = self.commands.get('start_scan') command['elements'] = { 'scanner_params': {k: v['name'] for k, v in self.scanner_params.items()}}
python
def add_scanner_param(self, name, scanner_param): assert name assert scanner_param self.scanner_params[name] = scanner_param command = self.commands.get('start_scan') command['elements'] = { 'scanner_params': {k: v['name'] for k, v in self.scanner_params.items()}}
[ "def", "add_scanner_param", "(", "self", ",", "name", ",", "scanner_param", ")", ":", "assert", "name", "assert", "scanner_param", "self", ".", "scanner_params", "[", "name", "]", "=", "scanner_param", "command", "=", "self", ".", "commands", ".", "get", "("...
Add a scanner parameter.
[ "Add", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L249-L258
18,302
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_vt
def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None, custom=None, vt_creation_time=None, vt_modification_time=None, vt_dependencies=None, summary=None, impact=None, affected=None, insight=None, solution=None, solution_t=None, detection=None, qod_t=None, qod_v=None, severities=None): """ Add a vulnerability test information. Returns: The new number of stored VTs. -1 in case the VT ID was already present and thus the new VT was not considered. -2 in case the vt_id was invalid. """ if not vt_id: return -2 # no valid vt_id if self.vt_id_pattern.fullmatch(vt_id) is None: return -2 # no valid vt_id if vt_id in self.vts: return -1 # The VT was already in the list. if name is None: name = '' self.vts[vt_id] = {'name': name} if custom is not None: self.vts[vt_id]["custom"] = custom if vt_params is not None: self.vts[vt_id]["vt_params"] = vt_params if vt_refs is not None: self.vts[vt_id]["vt_refs"] = vt_refs if vt_dependencies is not None: self.vts[vt_id]["vt_dependencies"] = vt_dependencies if vt_creation_time is not None: self.vts[vt_id]["creation_time"] = vt_creation_time if vt_modification_time is not None: self.vts[vt_id]["modification_time"] = vt_modification_time if summary is not None: self.vts[vt_id]["summary"] = summary if impact is not None: self.vts[vt_id]["impact"] = impact if affected is not None: self.vts[vt_id]["affected"] = affected if insight is not None: self.vts[vt_id]["insight"] = insight if solution is not None: self.vts[vt_id]["solution"] = solution if solution_t is not None: self.vts[vt_id]["solution_type"] = solution_t if detection is not None: self.vts[vt_id]["detection"] = detection if qod_t is not None: self.vts[vt_id]["qod_type"] = qod_t elif qod_v is not None: self.vts[vt_id]["qod"] = qod_v if severities is not None: self.vts[vt_id]["severities"] = severities return len(self.vts)
python
def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None, custom=None, vt_creation_time=None, vt_modification_time=None, vt_dependencies=None, summary=None, impact=None, affected=None, insight=None, solution=None, solution_t=None, detection=None, qod_t=None, qod_v=None, severities=None): if not vt_id: return -2 # no valid vt_id if self.vt_id_pattern.fullmatch(vt_id) is None: return -2 # no valid vt_id if vt_id in self.vts: return -1 # The VT was already in the list. if name is None: name = '' self.vts[vt_id] = {'name': name} if custom is not None: self.vts[vt_id]["custom"] = custom if vt_params is not None: self.vts[vt_id]["vt_params"] = vt_params if vt_refs is not None: self.vts[vt_id]["vt_refs"] = vt_refs if vt_dependencies is not None: self.vts[vt_id]["vt_dependencies"] = vt_dependencies if vt_creation_time is not None: self.vts[vt_id]["creation_time"] = vt_creation_time if vt_modification_time is not None: self.vts[vt_id]["modification_time"] = vt_modification_time if summary is not None: self.vts[vt_id]["summary"] = summary if impact is not None: self.vts[vt_id]["impact"] = impact if affected is not None: self.vts[vt_id]["affected"] = affected if insight is not None: self.vts[vt_id]["insight"] = insight if solution is not None: self.vts[vt_id]["solution"] = solution if solution_t is not None: self.vts[vt_id]["solution_type"] = solution_t if detection is not None: self.vts[vt_id]["detection"] = detection if qod_t is not None: self.vts[vt_id]["qod_type"] = qod_t elif qod_v is not None: self.vts[vt_id]["qod"] = qod_v if severities is not None: self.vts[vt_id]["severities"] = severities return len(self.vts)
[ "def", "add_vt", "(", "self", ",", "vt_id", ",", "name", "=", "None", ",", "vt_params", "=", "None", ",", "vt_refs", "=", "None", ",", "custom", "=", "None", ",", "vt_creation_time", "=", "None", ",", "vt_modification_time", "=", "None", ",", "vt_depende...
Add a vulnerability test information. Returns: The new number of stored VTs. -1 in case the VT ID was already present and thus the new VT was not considered. -2 in case the vt_id was invalid.
[ "Add", "a", "vulnerability", "test", "information", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L260-L319
18,303
greenbone/ospd
ospd/ospd.py
OSPDaemon._preprocess_scan_params
def _preprocess_scan_params(self, xml_params): """ Processes the scan parameters. """ params = {} for param in xml_params: params[param.tag] = param.text or '' # Set default values. for key in self.scanner_params: if key not in params: params[key] = self.get_scanner_param_default(key) if self.get_scanner_param_type(key) == 'selection': params[key] = params[key].split('|')[0] # Validate values. for key in params: param_type = self.get_scanner_param_type(key) if not param_type: continue if param_type in ['integer', 'boolean']: try: params[key] = int(params[key]) except ValueError: raise OSPDError('Invalid %s value' % key, 'start_scan') if param_type == 'boolean': if params[key] not in [0, 1]: raise OSPDError('Invalid %s value' % key, 'start_scan') elif param_type == 'selection': selection = self.get_scanner_param_default(key).split('|') if params[key] not in selection: raise OSPDError('Invalid %s value' % key, 'start_scan') if self.get_scanner_param_mandatory(key) and params[key] == '': raise OSPDError('Mandatory %s value is missing' % key, 'start_scan') return params
python
def _preprocess_scan_params(self, xml_params): params = {} for param in xml_params: params[param.tag] = param.text or '' # Set default values. for key in self.scanner_params: if key not in params: params[key] = self.get_scanner_param_default(key) if self.get_scanner_param_type(key) == 'selection': params[key] = params[key].split('|')[0] # Validate values. for key in params: param_type = self.get_scanner_param_type(key) if not param_type: continue if param_type in ['integer', 'boolean']: try: params[key] = int(params[key]) except ValueError: raise OSPDError('Invalid %s value' % key, 'start_scan') if param_type == 'boolean': if params[key] not in [0, 1]: raise OSPDError('Invalid %s value' % key, 'start_scan') elif param_type == 'selection': selection = self.get_scanner_param_default(key).split('|') if params[key] not in selection: raise OSPDError('Invalid %s value' % key, 'start_scan') if self.get_scanner_param_mandatory(key) and params[key] == '': raise OSPDError('Mandatory %s value is missing' % key, 'start_scan') return params
[ "def", "_preprocess_scan_params", "(", "self", ",", "xml_params", ")", ":", "params", "=", "{", "}", "for", "param", "in", "xml_params", ":", "params", "[", "param", ".", "tag", "]", "=", "param", ".", "text", "or", "''", "# Set default values.", "for", ...
Processes the scan parameters.
[ "Processes", "the", "scan", "parameters", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L363-L394
18,304
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_vts_params
def process_vts_params(self, scanner_vts): """ Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: <vt_selection> <vt_single id='vt1' /> <vt_single id='vt2'> <vt_value id='param1'>value</vt_value> </vt_single> <vt_group filter='family=debian'/> <vt_group filter='family=general'/> </vt_selection> @return: Dictionary containing the vts attribute and subelements, like the VT's id and VT's parameters. Example form: {'vt1': {}, 'vt2': {'value_id': 'value'}, 'vt_groups': ['family=debian', 'family=general']} """ vt_selection = {} filters = list() for vt in scanner_vts: if vt.tag == 'vt_single': vt_id = vt.attrib.get('id') vt_selection[vt_id] = {} for vt_value in vt: if not vt_value.attrib.get('id'): raise OSPDError('Invalid VT preference. No attribute id', 'start_scan') vt_value_id = vt_value.attrib.get('id') vt_value_value = vt_value.text if vt_value.text else '' vt_selection[vt_id][vt_value_id] = vt_value_value if vt.tag == 'vt_group': vts_filter = vt.attrib.get('filter', None) if vts_filter is None: raise OSPDError('Invalid VT group. No filter given.', 'start_scan') filters.append(vts_filter) vt_selection['vt_groups'] = filters return vt_selection
python
def process_vts_params(self, scanner_vts): vt_selection = {} filters = list() for vt in scanner_vts: if vt.tag == 'vt_single': vt_id = vt.attrib.get('id') vt_selection[vt_id] = {} for vt_value in vt: if not vt_value.attrib.get('id'): raise OSPDError('Invalid VT preference. No attribute id', 'start_scan') vt_value_id = vt_value.attrib.get('id') vt_value_value = vt_value.text if vt_value.text else '' vt_selection[vt_id][vt_value_id] = vt_value_value if vt.tag == 'vt_group': vts_filter = vt.attrib.get('filter', None) if vts_filter is None: raise OSPDError('Invalid VT group. No filter given.', 'start_scan') filters.append(vts_filter) vt_selection['vt_groups'] = filters return vt_selection
[ "def", "process_vts_params", "(", "self", ",", "scanner_vts", ")", ":", "vt_selection", "=", "{", "}", "filters", "=", "list", "(", ")", "for", "vt", "in", "scanner_vts", ":", "if", "vt", ".", "tag", "==", "'vt_single'", ":", "vt_id", "=", "vt", ".", ...
Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: <vt_selection> <vt_single id='vt1' /> <vt_single id='vt2'> <vt_value id='param1'>value</vt_value> </vt_single> <vt_group filter='family=debian'/> <vt_group filter='family=general'/> </vt_selection> @return: Dictionary containing the vts attribute and subelements, like the VT's id and VT's parameters. Example form: {'vt1': {}, 'vt2': {'value_id': 'value'}, 'vt_groups': ['family=debian', 'family=general']}
[ "Receive", "an", "XML", "object", "with", "the", "Vulnerability", "Tests", "an", "their", "parameters", "to", "be", "use", "in", "a", "scan", "and", "return", "a", "dictionary", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L401-L445
18,305
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_credentials_elements
def process_credentials_elements(cred_tree): """ Receive an XML object with the credentials to run a scan against a given target. @param: <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> @return: Dictionary containing the credentials for a given target. Example form: {'ssh': {'type': type, 'port': port, 'username': username, 'password': pass, }, 'smb': {'type': type, 'username': username, 'password': pass, }, } """ credentials = {} for credential in cred_tree: service = credential.attrib.get('service') credentials[service] = {} credentials[service]['type'] = credential.attrib.get('type') if service == 'ssh': credentials[service]['port'] = credential.attrib.get('port') for param in credential: credentials[service][param.tag] = param.text return credentials
python
def process_credentials_elements(cred_tree): credentials = {} for credential in cred_tree: service = credential.attrib.get('service') credentials[service] = {} credentials[service]['type'] = credential.attrib.get('type') if service == 'ssh': credentials[service]['port'] = credential.attrib.get('port') for param in credential: credentials[service][param.tag] = param.text return credentials
[ "def", "process_credentials_elements", "(", "cred_tree", ")", ":", "credentials", "=", "{", "}", "for", "credential", "in", "cred_tree", ":", "service", "=", "credential", ".", "attrib", ".", "get", "(", "'service'", ")", "credentials", "[", "service", "]", ...
Receive an XML object with the credentials to run a scan against a given target. @param: <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> @return: Dictionary containing the credentials for a given target. Example form: {'ssh': {'type': type, 'port': port, 'username': username, 'password': pass, }, 'smb': {'type': type, 'username': username, 'password': pass, }, }
[ "Receive", "an", "XML", "object", "with", "the", "credentials", "to", "run", "a", "scan", "against", "a", "given", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L448-L487
18,306
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_targets_element
def process_targets_element(cls, scanner_target): """ Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a comma-separated host list or a network address. <ports> and <credentials> are optional. Therefore each ospd-scanner should check for a valid ones if needed. Example form: <targets> <target> <hosts>localhosts</hosts> <ports>80,443</ports> </target> <target> <hosts>192.168.0.0/24</hosts> <ports>22</ports> <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> </target> </targets> @return: A list of (hosts, port) tuples. Example form: [['localhost', '80,43'], ['192.168.0.0/24', '22', {'smb': {'type': type, 'port': port, 'username': username, 'password': pass, }}]] """ target_list = [] for target in scanner_target: ports = '' credentials = {} for child in target: if child.tag == 'hosts': hosts = child.text if child.tag == 'ports': ports = child.text if child.tag == 'credentials': credentials = cls.process_credentials_elements(child) if hosts: target_list.append([hosts, ports, credentials]) else: raise OSPDError('No target to scan', 'start_scan') return target_list
python
def process_targets_element(cls, scanner_target): target_list = [] for target in scanner_target: ports = '' credentials = {} for child in target: if child.tag == 'hosts': hosts = child.text if child.tag == 'ports': ports = child.text if child.tag == 'credentials': credentials = cls.process_credentials_elements(child) if hosts: target_list.append([hosts, ports, credentials]) else: raise OSPDError('No target to scan', 'start_scan') return target_list
[ "def", "process_targets_element", "(", "cls", ",", "scanner_target", ")", ":", "target_list", "=", "[", "]", "for", "target", "in", "scanner_target", ":", "ports", "=", "''", "credentials", "=", "{", "}", "for", "child", "in", "target", ":", "if", "child",...
Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a comma-separated host list or a network address. <ports> and <credentials> are optional. Therefore each ospd-scanner should check for a valid ones if needed. Example form: <targets> <target> <hosts>localhosts</hosts> <ports>80,443</ports> </target> <target> <hosts>192.168.0.0/24</hosts> <ports>22</ports> <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> </target> </targets> @return: A list of (hosts, port) tuples. Example form: [['localhost', '80,43'], ['192.168.0.0/24', '22', {'smb': {'type': type, 'port': port, 'username': username, 'password': pass, }}]]
[ "Receive", "an", "XML", "object", "with", "the", "target", "ports", "and", "credentials", "to", "run", "a", "scan", "against", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L490-L548
18,307
greenbone/ospd
ospd/ospd.py
OSPDaemon.finish_scan
def finish_scan(self, scan_id): """ Sets a scan as finished. """ self.set_scan_progress(scan_id, 100) self.set_scan_status(scan_id, ScanStatus.FINISHED) logger.info("%s: Scan finished.", scan_id)
python
def finish_scan(self, scan_id): self.set_scan_progress(scan_id, 100) self.set_scan_status(scan_id, ScanStatus.FINISHED) logger.info("%s: Scan finished.", scan_id)
[ "def", "finish_scan", "(", "self", ",", "scan_id", ")", ":", "self", ".", "set_scan_progress", "(", "scan_id", ",", "100", ")", "self", ".", "set_scan_status", "(", "scan_id", ",", "ScanStatus", ".", "FINISHED", ")", "logger", ".", "info", "(", "\"%s: Scan...
Sets a scan as finished.
[ "Sets", "a", "scan", "as", "finished", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L661-L665
18,308
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_type
def get_scanner_param_type(self, param): """ Returns type of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('type')
python
def get_scanner_param_type(self, param): assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('type')
[ "def", "get_scanner_param_type", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "None", "return"...
Returns type of a scanner parameter.
[ "Returns", "type", "of", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L675-L681
18,309
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_mandatory
def get_scanner_param_mandatory(self, param): """ Returns if a scanner parameter is mandatory. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get('mandatory')
python
def get_scanner_param_mandatory(self, param): assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get('mandatory')
[ "def", "get_scanner_param_mandatory", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "False", "r...
Returns if a scanner parameter is mandatory.
[ "Returns", "if", "a", "scanner", "parameter", "is", "mandatory", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L683-L689
18,310
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_default
def get_scanner_param_default(self, param): """ Returns default value of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('default')
python
def get_scanner_param_default(self, param): assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('default')
[ "def", "get_scanner_param_default", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "None", "retu...
Returns default value of a scanner parameter.
[ "Returns", "default", "value", "of", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L691-L697
18,311
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_params_xml
def get_scanner_params_xml(self): """ Returns the OSP Daemon's scanner params in xml format. """ scanner_params = Element('scanner_params') for param_id, param in self.scanner_params.items(): param_xml = SubElement(scanner_params, 'scanner_param') for name, value in [('id', param_id), ('type', param['type'])]: param_xml.set(name, value) for name, value in [('name', param['name']), ('description', param['description']), ('default', param['default']), ('mandatory', param['mandatory'])]: elem = SubElement(param_xml, name) elem.text = str(value) return scanner_params
python
def get_scanner_params_xml(self): scanner_params = Element('scanner_params') for param_id, param in self.scanner_params.items(): param_xml = SubElement(scanner_params, 'scanner_param') for name, value in [('id', param_id), ('type', param['type'])]: param_xml.set(name, value) for name, value in [('name', param['name']), ('description', param['description']), ('default', param['default']), ('mandatory', param['mandatory'])]: elem = SubElement(param_xml, name) elem.text = str(value) return scanner_params
[ "def", "get_scanner_params_xml", "(", "self", ")", ":", "scanner_params", "=", "Element", "(", "'scanner_params'", ")", "for", "param_id", ",", "param", "in", "self", ".", "scanner_params", ".", "items", "(", ")", ":", "param_xml", "=", "SubElement", "(", "s...
Returns the OSP Daemon's scanner params in xml format.
[ "Returns", "the", "OSP", "Daemon", "s", "scanner", "params", "in", "xml", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L699-L713
18,312
greenbone/ospd
ospd/ospd.py
OSPDaemon.new_client_stream
def new_client_stream(self, sock): """ Returns a new ssl client stream from bind_socket. """ assert sock newsocket, fromaddr = sock.accept() logger.debug("New connection from" " %s:%s", fromaddr[0], fromaddr[1]) # NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest # protocol version that both the client and server support. In modern # Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3 # being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for # PROTOCOL_TLS which should be used once compatibility with Python 3.4 # is no longer desired. try: ssl_socket = ssl.wrap_socket(newsocket, cert_reqs=ssl.CERT_REQUIRED, server_side=True, certfile=self.certs['cert_file'], keyfile=self.certs['key_file'], ca_certs=self.certs['ca_file'], ssl_version=ssl.PROTOCOL_SSLv23) except (ssl.SSLError, socket.error) as message: logger.error(message) return None return ssl_socket
python
def new_client_stream(self, sock): assert sock newsocket, fromaddr = sock.accept() logger.debug("New connection from" " %s:%s", fromaddr[0], fromaddr[1]) # NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest # protocol version that both the client and server support. In modern # Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3 # being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for # PROTOCOL_TLS which should be used once compatibility with Python 3.4 # is no longer desired. try: ssl_socket = ssl.wrap_socket(newsocket, cert_reqs=ssl.CERT_REQUIRED, server_side=True, certfile=self.certs['cert_file'], keyfile=self.certs['key_file'], ca_certs=self.certs['ca_file'], ssl_version=ssl.PROTOCOL_SSLv23) except (ssl.SSLError, socket.error) as message: logger.error(message) return None return ssl_socket
[ "def", "new_client_stream", "(", "self", ",", "sock", ")", ":", "assert", "sock", "newsocket", ",", "fromaddr", "=", "sock", ".", "accept", "(", ")", "logger", ".", "debug", "(", "\"New connection from\"", "\" %s:%s\"", ",", "fromaddr", "[", "0", "]", ",",...
Returns a new ssl client stream from bind_socket.
[ "Returns", "a", "new", "ssl", "client", "stream", "from", "bind_socket", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L715-L738
18,313
greenbone/ospd
ospd/ospd.py
OSPDaemon.write_to_stream
def write_to_stream(stream, response, block_len=1024): """ Send the response in blocks of the given len using the passed method dependending on the socket type. """ try: i_start = 0 i_end = block_len while True: if i_end > len(response): stream(response[i_start:]) break stream(response[i_start:i_end]) i_start = i_end i_end += block_len except (socket.timeout, socket.error) as exception: logger.debug('Error sending response to the client: %s', exception)
python
def write_to_stream(stream, response, block_len=1024): try: i_start = 0 i_end = block_len while True: if i_end > len(response): stream(response[i_start:]) break stream(response[i_start:i_end]) i_start = i_end i_end += block_len except (socket.timeout, socket.error) as exception: logger.debug('Error sending response to the client: %s', exception)
[ "def", "write_to_stream", "(", "stream", ",", "response", ",", "block_len", "=", "1024", ")", ":", "try", ":", "i_start", "=", "0", "i_end", "=", "block_len", "while", "True", ":", "if", "i_end", ">", "len", "(", "response", ")", ":", "stream", "(", ...
Send the response in blocks of the given len using the passed method dependending on the socket type.
[ "Send", "the", "response", "in", "blocks", "of", "the", "given", "len", "using", "the", "passed", "method", "dependending", "on", "the", "socket", "type", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L741-L757
18,314
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_client_stream
def handle_client_stream(self, stream, is_unix=False): """ Handles stream of data received from client. """ assert stream data = [] stream.settimeout(2) while True: try: if is_unix: buf = stream.recv(1024) else: buf = stream.read(1024) if not buf: break data.append(buf) except (AttributeError, ValueError) as message: logger.error(message) return except (ssl.SSLError) as exception: logger.debug('Error: %s', exception[0]) break except (socket.timeout) as exception: logger.debug('Error: %s', exception) break data = b''.join(data) if len(data) <= 0: logger.debug("Empty client stream") return try: response = self.handle_command(data) except OSPDError as exception: response = exception.as_xml() logger.debug('Command error: %s', exception.message) except Exception: logger.exception('While handling client command:') exception = OSPDError('Fatal error', 'error') response = exception.as_xml() if is_unix: send_method = stream.send else: send_method = stream.write self.write_to_stream(send_method, response)
python
def handle_client_stream(self, stream, is_unix=False): assert stream data = [] stream.settimeout(2) while True: try: if is_unix: buf = stream.recv(1024) else: buf = stream.read(1024) if not buf: break data.append(buf) except (AttributeError, ValueError) as message: logger.error(message) return except (ssl.SSLError) as exception: logger.debug('Error: %s', exception[0]) break except (socket.timeout) as exception: logger.debug('Error: %s', exception) break data = b''.join(data) if len(data) <= 0: logger.debug("Empty client stream") return try: response = self.handle_command(data) except OSPDError as exception: response = exception.as_xml() logger.debug('Command error: %s', exception.message) except Exception: logger.exception('While handling client command:') exception = OSPDError('Fatal error', 'error') response = exception.as_xml() if is_unix: send_method = stream.send else: send_method = stream.write self.write_to_stream(send_method, response)
[ "def", "handle_client_stream", "(", "self", ",", "stream", ",", "is_unix", "=", "False", ")", ":", "assert", "stream", "data", "=", "[", "]", "stream", ".", "settimeout", "(", "2", ")", "while", "True", ":", "try", ":", "if", "is_unix", ":", "buf", "...
Handles stream of data received from client.
[ "Handles", "stream", "of", "data", "received", "from", "client", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L759-L800
18,315
greenbone/ospd
ospd/ospd.py
OSPDaemon.parallel_scan
def parallel_scan(self, scan_id, target): """ Starts the scan with scan_id. """ try: ret = self.exec_scan(scan_id, target) if ret == 0: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='0') elif ret == 1: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='1') elif ret == 2: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='2') else: logger.debug('%s: No host status returned', target) except Exception as e: self.add_scan_error(scan_id, name='', host=target, value='Host process failure (%s).' % e) logger.exception('While scanning %s:', target) else: logger.info("%s: Host scan finished.", target)
python
def parallel_scan(self, scan_id, target): try: ret = self.exec_scan(scan_id, target) if ret == 0: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='0') elif ret == 1: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='1') elif ret == 2: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='2') else: logger.debug('%s: No host status returned', target) except Exception as e: self.add_scan_error(scan_id, name='', host=target, value='Host process failure (%s).' % e) logger.exception('While scanning %s:', target) else: logger.info("%s: Host scan finished.", target)
[ "def", "parallel_scan", "(", "self", ",", "scan_id", ",", "target", ")", ":", "try", ":", "ret", "=", "self", ".", "exec_scan", "(", "scan_id", ",", "target", ")", "if", "ret", "==", "0", ":", "self", ".", "add_scan_host_detail", "(", "scan_id", ",", ...
Starts the scan with scan_id.
[ "Starts", "the", "scan", "with", "scan_id", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L802-L822
18,316
greenbone/ospd
ospd/ospd.py
OSPDaemon.calculate_progress
def calculate_progress(self, scan_id): """ Calculate the total scan progress from the partial target progress. """ t_prog = dict() for target in self.get_scan_target(scan_id): t_prog[target] = self.get_scan_target_progress(scan_id, target) return sum(t_prog.values())/len(t_prog)
python
def calculate_progress(self, scan_id): t_prog = dict() for target in self.get_scan_target(scan_id): t_prog[target] = self.get_scan_target_progress(scan_id, target) return sum(t_prog.values())/len(t_prog)
[ "def", "calculate_progress", "(", "self", ",", "scan_id", ")", ":", "t_prog", "=", "dict", "(", ")", "for", "target", "in", "self", ".", "get_scan_target", "(", "scan_id", ")", ":", "t_prog", "[", "target", "]", "=", "self", ".", "get_scan_target_progress"...
Calculate the total scan progress from the partial target progress.
[ "Calculate", "the", "total", "scan", "progress", "from", "the", "partial", "target", "progress", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L848-L855
18,317
greenbone/ospd
ospd/ospd.py
OSPDaemon.start_scan
def start_scan(self, scan_id, targets, parallel=1): """ Handle N parallel scans if 'parallel' is greater than 1. """ os.setsid() multiscan_proc = [] logger.info("%s: Scan started.", scan_id) target_list = targets if target_list is None or not target_list: raise OSPDError('Erroneous targets list', 'start_scan') for index, target in enumerate(target_list): while len(multiscan_proc) >= parallel: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) time.sleep(1) #If the scan status is stopped, does not launch anymore target scans if self.get_scan_status(scan_id) == ScanStatus.STOPPED: return logger.info("%s: Host scan started on ports %s.", target[0], target[1]) scan_process = multiprocessing.Process(target=self.parallel_scan, args=(scan_id, target[0])) multiscan_proc.append((scan_process, target[0])) scan_process.start() self.set_scan_status(scan_id, ScanStatus.RUNNING) # Wait until all single target were scanned while multiscan_proc: multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) if multiscan_proc: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) time.sleep(1) # Only set the scan as finished if the scan was not stopped. if self.get_scan_status(scan_id) != ScanStatus.STOPPED: self.finish_scan(scan_id)
python
def start_scan(self, scan_id, targets, parallel=1): os.setsid() multiscan_proc = [] logger.info("%s: Scan started.", scan_id) target_list = targets if target_list is None or not target_list: raise OSPDError('Erroneous targets list', 'start_scan') for index, target in enumerate(target_list): while len(multiscan_proc) >= parallel: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) time.sleep(1) #If the scan status is stopped, does not launch anymore target scans if self.get_scan_status(scan_id) == ScanStatus.STOPPED: return logger.info("%s: Host scan started on ports %s.", target[0], target[1]) scan_process = multiprocessing.Process(target=self.parallel_scan, args=(scan_id, target[0])) multiscan_proc.append((scan_process, target[0])) scan_process.start() self.set_scan_status(scan_id, ScanStatus.RUNNING) # Wait until all single target were scanned while multiscan_proc: multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) if multiscan_proc: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) time.sleep(1) # Only set the scan as finished if the scan was not stopped. if self.get_scan_status(scan_id) != ScanStatus.STOPPED: self.finish_scan(scan_id)
[ "def", "start_scan", "(", "self", ",", "scan_id", ",", "targets", ",", "parallel", "=", "1", ")", ":", "os", ".", "setsid", "(", ")", "multiscan_proc", "=", "[", "]", "logger", ".", "info", "(", "\"%s: Scan started.\"", ",", "scan_id", ")", "target_list"...
Handle N parallel scans if 'parallel' is greater than 1.
[ "Handle", "N", "parallel", "scans", "if", "parallel", "is", "greater", "than", "1", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L857-L896
18,318
greenbone/ospd
ospd/ospd.py
OSPDaemon.dry_run_scan
def dry_run_scan(self, scan_id, targets): """ Dry runs a scan. """ os.setsid() for _, target in enumerate(targets): host = resolve_hostname(target[0]) if host is None: logger.info("Couldn't resolve %s.", target[0]) continue port = self.get_scan_ports(scan_id, target=target[0]) logger.info("%s:%s: Dry run mode.", host, port) self.add_scan_log(scan_id, name='', host=host, value='Dry run result') self.finish_scan(scan_id)
python
def dry_run_scan(self, scan_id, targets): os.setsid() for _, target in enumerate(targets): host = resolve_hostname(target[0]) if host is None: logger.info("Couldn't resolve %s.", target[0]) continue port = self.get_scan_ports(scan_id, target=target[0]) logger.info("%s:%s: Dry run mode.", host, port) self.add_scan_log(scan_id, name='', host=host, value='Dry run result') self.finish_scan(scan_id)
[ "def", "dry_run_scan", "(", "self", ",", "scan_id", ",", "targets", ")", ":", "os", ".", "setsid", "(", ")", "for", "_", ",", "target", "in", "enumerate", "(", "targets", ")", ":", "host", "=", "resolve_hostname", "(", "target", "[", "0", "]", ")", ...
Dry runs a scan.
[ "Dry", "runs", "a", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L898-L911
18,319
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_timeout
def handle_timeout(self, scan_id, host): """ Handles scanner reaching timeout error. """ self.add_scan_error(scan_id, host=host, name="Timeout", value="{0} exec timeout." .format(self.get_scanner_name()))
python
def handle_timeout(self, scan_id, host): self.add_scan_error(scan_id, host=host, name="Timeout", value="{0} exec timeout." .format(self.get_scanner_name()))
[ "def", "handle_timeout", "(", "self", ",", "scan_id", ",", "host", ")", ":", "self", ".", "add_scan_error", "(", "scan_id", ",", "host", "=", "host", ",", "name", "=", "\"Timeout\"", ",", "value", "=", "\"{0} exec timeout.\"", ".", "format", "(", "self", ...
Handles scanner reaching timeout error.
[ "Handles", "scanner", "reaching", "timeout", "error", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L913-L917
18,320
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_scan_target_progress
def set_scan_target_progress( self, scan_id, target, host, progress): """ Sets host's progress which is part of target. """ self.scan_collection.set_target_progress( scan_id, target, host, progress)
python
def set_scan_target_progress( self, scan_id, target, host, progress): self.scan_collection.set_target_progress( scan_id, target, host, progress)
[ "def", "set_scan_target_progress", "(", "self", ",", "scan_id", ",", "target", ",", "host", ",", "progress", ")", ":", "self", ".", "scan_collection", ".", "set_target_progress", "(", "scan_id", ",", "target", ",", "host", ",", "progress", ")" ]
Sets host's progress which is part of target.
[ "Sets", "host", "s", "progress", "which", "is", "part", "of", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L928-L932
18,321
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_help_text
def get_help_text(self): """ Returns the help output in plain text format.""" txt = str('\n') for name, info in self.commands.items(): command_txt = "\t{0: <22} {1}\n".format(name, info['description']) if info['attributes']: command_txt = ''.join([command_txt, "\t Attributes:\n"]) for attrname, attrdesc in info['attributes'].items(): attr_txt = "\t {0: <22} {1}\n".format(attrname, attrdesc) command_txt = ''.join([command_txt, attr_txt]) if info['elements']: command_txt = ''.join([command_txt, "\t Elements:\n", self.elements_as_text(info['elements'])]) txt = ''.join([txt, command_txt]) return txt
python
def get_help_text(self): txt = str('\n') for name, info in self.commands.items(): command_txt = "\t{0: <22} {1}\n".format(name, info['description']) if info['attributes']: command_txt = ''.join([command_txt, "\t Attributes:\n"]) for attrname, attrdesc in info['attributes'].items(): attr_txt = "\t {0: <22} {1}\n".format(attrname, attrdesc) command_txt = ''.join([command_txt, attr_txt]) if info['elements']: command_txt = ''.join([command_txt, "\t Elements:\n", self.elements_as_text(info['elements'])]) txt = ''.join([txt, command_txt]) return txt
[ "def", "get_help_text", "(", "self", ")", ":", "txt", "=", "str", "(", "'\\n'", ")", "for", "name", ",", "info", "in", "self", ".", "commands", ".", "items", "(", ")", ":", "command_txt", "=", "\"\\t{0: <22} {1}\\n\"", ".", "format", "(", "name", ",", ...
Returns the help output in plain text format.
[ "Returns", "the", "help", "output", "in", "plain", "text", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1023-L1038
18,322
greenbone/ospd
ospd/ospd.py
OSPDaemon.elements_as_text
def elements_as_text(self, elems, indent=2): """ Returns the elems dictionary as formatted plain text. """ assert elems text = "" for elename, eledesc in elems.items(): if isinstance(eledesc, dict): desc_txt = self.elements_as_text(eledesc, indent + 2) desc_txt = ''.join(['\n', desc_txt]) elif isinstance(eledesc, str): desc_txt = ''.join([eledesc, '\n']) else: assert False, "Only string or dictionary" ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename, desc_txt) text = ''.join([text, ele_txt]) return text
python
def elements_as_text(self, elems, indent=2): assert elems text = "" for elename, eledesc in elems.items(): if isinstance(eledesc, dict): desc_txt = self.elements_as_text(eledesc, indent + 2) desc_txt = ''.join(['\n', desc_txt]) elif isinstance(eledesc, str): desc_txt = ''.join([eledesc, '\n']) else: assert False, "Only string or dictionary" ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename, desc_txt) text = ''.join([text, ele_txt]) return text
[ "def", "elements_as_text", "(", "self", ",", "elems", ",", "indent", "=", "2", ")", ":", "assert", "elems", "text", "=", "\"\"", "for", "elename", ",", "eledesc", "in", "elems", ".", "items", "(", ")", ":", "if", "isinstance", "(", "eledesc", ",", "d...
Returns the elems dictionary as formatted plain text.
[ "Returns", "the", "elems", "dictionary", "as", "formatted", "plain", "text", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1040-L1055
18,323
greenbone/ospd
ospd/ospd.py
OSPDaemon.delete_scan
def delete_scan(self, scan_id): """ Deletes scan_id scan from collection. @return: 1 if scan deleted, 0 otherwise. """ if self.get_scan_status(scan_id) == ScanStatus.RUNNING: return 0 try: del self.scan_processes[scan_id] except KeyError: logger.debug('Scan process for %s not found', scan_id) return self.scan_collection.delete_scan(scan_id)
python
def delete_scan(self, scan_id): if self.get_scan_status(scan_id) == ScanStatus.RUNNING: return 0 try: del self.scan_processes[scan_id] except KeyError: logger.debug('Scan process for %s not found', scan_id) return self.scan_collection.delete_scan(scan_id)
[ "def", "delete_scan", "(", "self", ",", "scan_id", ")", ":", "if", "self", ".", "get_scan_status", "(", "scan_id", ")", "==", "ScanStatus", ".", "RUNNING", ":", "return", "0", "try", ":", "del", "self", ".", "scan_processes", "[", "scan_id", "]", "except...
Deletes scan_id scan from collection. @return: 1 if scan deleted, 0 otherwise.
[ "Deletes", "scan_id", "scan", "from", "collection", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1075-L1087
18,324
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scan_results_xml
def get_scan_results_xml(self, scan_id, pop_res): """ Gets scan_id scan's results in XML format. @return: String of scan results in xml. """ results = Element('results') for result in self.scan_collection.results_iterator(scan_id, pop_res): results.append(get_result_xml(result)) logger.info('Returning %d results', len(results)) return results
python
def get_scan_results_xml(self, scan_id, pop_res): results = Element('results') for result in self.scan_collection.results_iterator(scan_id, pop_res): results.append(get_result_xml(result)) logger.info('Returning %d results', len(results)) return results
[ "def", "get_scan_results_xml", "(", "self", ",", "scan_id", ",", "pop_res", ")", ":", "results", "=", "Element", "(", "'results'", ")", "for", "result", "in", "self", ".", "scan_collection", ".", "results_iterator", "(", "scan_id", ",", "pop_res", ")", ":", ...
Gets scan_id scan's results in XML format. @return: String of scan results in xml.
[ "Gets", "scan_id", "scan", "s", "results", "in", "XML", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1089-L1099
18,325
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_xml_str
def get_xml_str(self, data): """ Creates a string in XML Format using the provided data structure. @param: Dictionary of xml tags and their elements. @return: String of data in xml format. """ responses = [] for tag, value in data.items(): elem = Element(tag) if isinstance(value, dict): for value in self.get_xml_str(value): elem.append(value) elif isinstance(value, list): value = ', '.join([m for m in value]) elem.text = value else: elem.text = value responses.append(elem) return responses
python
def get_xml_str(self, data): responses = [] for tag, value in data.items(): elem = Element(tag) if isinstance(value, dict): for value in self.get_xml_str(value): elem.append(value) elif isinstance(value, list): value = ', '.join([m for m in value]) elem.text = value else: elem.text = value responses.append(elem) return responses
[ "def", "get_xml_str", "(", "self", ",", "data", ")", ":", "responses", "=", "[", "]", "for", "tag", ",", "value", "in", "data", ".", "items", "(", ")", ":", "elem", "=", "Element", "(", "tag", ")", "if", "isinstance", "(", "value", ",", "dict", "...
Creates a string in XML Format using the provided data structure. @param: Dictionary of xml tags and their elements. @return: String of data in xml format.
[ "Creates", "a", "string", "in", "XML", "Format", "using", "the", "provided", "data", "structure", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1101-L1121
18,326
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scan_xml
def get_scan_xml(self, scan_id, detailed=True, pop_res=False): """ Gets scan in XML format. @return: String of scan in XML format. """ if not scan_id: return Element('scan') target = ','.join(self.get_scan_target(scan_id)) progress = self.get_scan_progress(scan_id) status = self.get_scan_status(scan_id) start_time = self.get_scan_start_time(scan_id) end_time = self.get_scan_end_time(scan_id) response = Element('scan') for name, value in [('id', scan_id), ('target', target), ('progress', progress), ('status', status.name.lower()), ('start_time', start_time), ('end_time', end_time)]: response.set(name, str(value)) if detailed: response.append(self.get_scan_results_xml(scan_id, pop_res)) return response
python
def get_scan_xml(self, scan_id, detailed=True, pop_res=False): if not scan_id: return Element('scan') target = ','.join(self.get_scan_target(scan_id)) progress = self.get_scan_progress(scan_id) status = self.get_scan_status(scan_id) start_time = self.get_scan_start_time(scan_id) end_time = self.get_scan_end_time(scan_id) response = Element('scan') for name, value in [('id', scan_id), ('target', target), ('progress', progress), ('status', status.name.lower()), ('start_time', start_time), ('end_time', end_time)]: response.set(name, str(value)) if detailed: response.append(self.get_scan_results_xml(scan_id, pop_res)) return response
[ "def", "get_scan_xml", "(", "self", ",", "scan_id", ",", "detailed", "=", "True", ",", "pop_res", "=", "False", ")", ":", "if", "not", "scan_id", ":", "return", "Element", "(", "'scan'", ")", "target", "=", "','", ".", "join", "(", "self", ".", "get_...
Gets scan in XML format. @return: String of scan in XML format.
[ "Gets", "scan", "in", "XML", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1123-L1146
18,327
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_vts_xml
def get_vts_xml(self, vt_id=None, filtered_vts=None): """ Gets collection of vulnerability test information in XML format. If vt_id is specified, the collection will contain only this vt, if found. If no vt_id is specified, the collection will contain all vts or those passed in filtered_vts. Arguments: vt_id (vt_id, optional): ID of the vt to get. filtered_vts (dict, optional): Filtered VTs collection. Return: String of collection of vulnerability test information in XML format. """ vts_xml = Element('vts') if vt_id: vts_xml.append(self.get_vt_xml(vt_id)) elif filtered_vts: for vt_id in filtered_vts: vts_xml.append(self.get_vt_xml(vt_id)) else: for vt_id in self.vts: vts_xml.append(self.get_vt_xml(vt_id)) return vts_xml
python
def get_vts_xml(self, vt_id=None, filtered_vts=None): vts_xml = Element('vts') if vt_id: vts_xml.append(self.get_vt_xml(vt_id)) elif filtered_vts: for vt_id in filtered_vts: vts_xml.append(self.get_vt_xml(vt_id)) else: for vt_id in self.vts: vts_xml.append(self.get_vt_xml(vt_id)) return vts_xml
[ "def", "get_vts_xml", "(", "self", ",", "vt_id", "=", "None", ",", "filtered_vts", "=", "None", ")", ":", "vts_xml", "=", "Element", "(", "'vts'", ")", "if", "vt_id", ":", "vts_xml", ".", "append", "(", "self", ".", "get_vt_xml", "(", "vt_id", ")", "...
Gets collection of vulnerability test information in XML format. If vt_id is specified, the collection will contain only this vt, if found. If no vt_id is specified, the collection will contain all vts or those passed in filtered_vts. Arguments: vt_id (vt_id, optional): ID of the vt to get. filtered_vts (dict, optional): Filtered VTs collection. Return: String of collection of vulnerability test information in XML format.
[ "Gets", "collection", "of", "vulnerability", "test", "information", "in", "XML", "format", ".", "If", "vt_id", "is", "specified", "the", "collection", "will", "contain", "only", "this", "vt", "if", "found", ".", "If", "no", "vt_id", "is", "specified", "the",...
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1415-L1442
18,328
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_command
def handle_command(self, command): """ Handles an osp command in a string. @return: OSP Response to command. """ try: tree = secET.fromstring(command) except secET.ParseError: logger.debug("Erroneous client input: %s", command) raise OSPDError('Invalid data') if not self.command_exists(tree.tag) and tree.tag != "authenticate": raise OSPDError('Bogus command name') if tree.tag == "get_version": return self.handle_get_version_command() elif tree.tag == "start_scan": return self.handle_start_scan_command(tree) elif tree.tag == "stop_scan": return self.handle_stop_scan_command(tree) elif tree.tag == "get_scans": return self.handle_get_scans_command(tree) elif tree.tag == "get_vts": return self.handle_get_vts_command(tree) elif tree.tag == "delete_scan": return self.handle_delete_scan_command(tree) elif tree.tag == "help": return self.handle_help_command(tree) elif tree.tag == "get_scanner_details": return self.handle_get_scanner_details() else: assert False, "Unhandled command: {0}".format(tree.tag)
python
def handle_command(self, command): try: tree = secET.fromstring(command) except secET.ParseError: logger.debug("Erroneous client input: %s", command) raise OSPDError('Invalid data') if not self.command_exists(tree.tag) and tree.tag != "authenticate": raise OSPDError('Bogus command name') if tree.tag == "get_version": return self.handle_get_version_command() elif tree.tag == "start_scan": return self.handle_start_scan_command(tree) elif tree.tag == "stop_scan": return self.handle_stop_scan_command(tree) elif tree.tag == "get_scans": return self.handle_get_scans_command(tree) elif tree.tag == "get_vts": return self.handle_get_vts_command(tree) elif tree.tag == "delete_scan": return self.handle_delete_scan_command(tree) elif tree.tag == "help": return self.handle_help_command(tree) elif tree.tag == "get_scanner_details": return self.handle_get_scanner_details() else: assert False, "Unhandled command: {0}".format(tree.tag)
[ "def", "handle_command", "(", "self", ",", "command", ")", ":", "try", ":", "tree", "=", "secET", ".", "fromstring", "(", "command", ")", "except", "secET", ".", "ParseError", ":", "logger", ".", "debug", "(", "\"Erroneous client input: %s\"", ",", "command"...
Handles an osp command in a string. @return: OSP Response to command.
[ "Handles", "an", "osp", "command", "in", "a", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1487-L1518
18,329
greenbone/ospd
ospd/ospd.py
OSPDaemon.run
def run(self, address, port, unix_path): """ Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise. """ assert address or unix_path if unix_path: sock = bind_unix_socket(unix_path) else: sock = bind_socket(address, port) if sock is None: return False sock.setblocking(False) inputs = [sock] outputs = [] try: while True: readable, _, _ = select.select( inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD) for r_socket in readable: if unix_path and r_socket is sock: client_stream, _ = sock.accept() logger.debug("New connection from %s", unix_path) self.handle_client_stream(client_stream, True) else: client_stream = self.new_client_stream(sock) if client_stream is None: continue self.handle_client_stream(client_stream, False) close_client_stream(client_stream, unix_path) self.scheduler() except KeyboardInterrupt: logger.info("Received Ctrl-C shutting-down ...") finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
python
def run(self, address, port, unix_path): assert address or unix_path if unix_path: sock = bind_unix_socket(unix_path) else: sock = bind_socket(address, port) if sock is None: return False sock.setblocking(False) inputs = [sock] outputs = [] try: while True: readable, _, _ = select.select( inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD) for r_socket in readable: if unix_path and r_socket is sock: client_stream, _ = sock.accept() logger.debug("New connection from %s", unix_path) self.handle_client_stream(client_stream, True) else: client_stream = self.new_client_stream(sock) if client_stream is None: continue self.handle_client_stream(client_stream, False) close_client_stream(client_stream, unix_path) self.scheduler() except KeyboardInterrupt: logger.info("Received Ctrl-C shutting-down ...") finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
[ "def", "run", "(", "self", ",", "address", ",", "port", ",", "unix_path", ")", ":", "assert", "address", "or", "unix_path", "if", "unix_path", ":", "sock", "=", "bind_unix_socket", "(", "unix_path", ")", "else", ":", "sock", "=", "bind_socket", "(", "add...
Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise.
[ "Starts", "the", "Daemon", "handling", "commands", "until", "interrupted", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1524-L1560
18,330
greenbone/ospd
ospd/ospd.py
OSPDaemon.create_scan
def create_scan(self, scan_id, targets, options, vts): """ Creates a new scan. @target: Target to scan. @options: Miscellaneous scan options. @return: New scan's ID. """ if self.scan_exists(scan_id): logger.info("Scan %s exists. Resuming scan.", scan_id) return self.scan_collection.create_scan(scan_id, targets, options, vts)
python
def create_scan(self, scan_id, targets, options, vts): if self.scan_exists(scan_id): logger.info("Scan %s exists. Resuming scan.", scan_id) return self.scan_collection.create_scan(scan_id, targets, options, vts)
[ "def", "create_scan", "(", "self", ",", "scan_id", ",", "targets", ",", "options", ",", "vts", ")", ":", "if", "self", ".", "scan_exists", "(", "scan_id", ")", ":", "logger", ".", "info", "(", "\"Scan %s exists. Resuming scan.\"", ",", "scan_id", ")", "ret...
Creates a new scan. @target: Target to scan. @options: Miscellaneous scan options. @return: New scan's ID.
[ "Creates", "a", "new", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1566-L1577
18,331
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_scan_option
def set_scan_option(self, scan_id, name, value): """ Sets a scan's option to a provided value. """ return self.scan_collection.set_option(scan_id, name, value)
python
def set_scan_option(self, scan_id, name, value): return self.scan_collection.set_option(scan_id, name, value)
[ "def", "set_scan_option", "(", "self", ",", "scan_id", ",", "name", ",", "value", ")", ":", "return", "self", ".", "scan_collection", ".", "set_option", "(", "scan_id", ",", "name", ",", "value", ")" ]
Sets a scan's option to a provided value.
[ "Sets", "a", "scan", "s", "option", "to", "a", "provided", "value", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1583-L1585
18,332
greenbone/ospd
ospd/ospd.py
OSPDaemon.check_scan_process
def check_scan_process(self, scan_id): """ Check the scan's process, and terminate the scan if not alive. """ scan_process = self.scan_processes[scan_id] progress = self.get_scan_progress(scan_id) if progress < 100 and not scan_process.is_alive(): self.set_scan_status(scan_id, ScanStatus.STOPPED) self.add_scan_error(scan_id, name="", host="", value="Scan process failure.") logger.info("%s: Scan stopped with errors.", scan_id) elif progress == 100: scan_process.join()
python
def check_scan_process(self, scan_id): scan_process = self.scan_processes[scan_id] progress = self.get_scan_progress(scan_id) if progress < 100 and not scan_process.is_alive(): self.set_scan_status(scan_id, ScanStatus.STOPPED) self.add_scan_error(scan_id, name="", host="", value="Scan process failure.") logger.info("%s: Scan stopped with errors.", scan_id) elif progress == 100: scan_process.join()
[ "def", "check_scan_process", "(", "self", ",", "scan_id", ")", ":", "scan_process", "=", "self", ".", "scan_processes", "[", "scan_id", "]", "progress", "=", "self", ".", "get_scan_progress", "(", "scan_id", ")", "if", "progress", "<", "100", "and", "not", ...
Check the scan's process, and terminate the scan if not alive.
[ "Check", "the", "scan", "s", "process", "and", "terminate", "the", "scan", "if", "not", "alive", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1587-L1597
18,333
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_log
def add_scan_log(self, scan_id, host='', name='', value='', port='', test_id='', qod=''): """ Adds a log result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.LOG, host, name, value, port, test_id, 0.0, qod)
python
def add_scan_log(self, scan_id, host='', name='', value='', port='', test_id='', qod=''): self.scan_collection.add_result(scan_id, ResultType.LOG, host, name, value, port, test_id, 0.0, qod)
[ "def", "add_scan_log", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "qod", "=", "''", ")", ":", "self", ".", "scan_collection", ".", ...
Adds a log result to scan_id scan.
[ "Adds", "a", "log", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1632-L1636
18,334
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_error
def add_scan_error(self, scan_id, host='', name='', value='', port=''): """ Adds an error result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name, value, port)
python
def add_scan_error(self, scan_id, host='', name='', value='', port=''): self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name, value, port)
[ "def", "add_scan_error", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", "."...
Adds an error result to scan_id scan.
[ "Adds", "an", "error", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1638-L1641
18,335
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_host_detail
def add_scan_host_detail(self, scan_id, host='', name='', value=''): """ Adds a host detail result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host, name, value)
python
def add_scan_host_detail(self, scan_id, host='', name='', value=''): self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host, name, value)
[ "def", "add_scan_host_detail", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", ".", "HOST_DETAIL", ",", ...
Adds a host detail result to scan_id scan.
[ "Adds", "a", "host", "detail", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1643-L1646
18,336
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_alarm
def add_scan_alarm(self, scan_id, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Adds an alarm result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name, value, port, test_id, severity, qod)
python
def add_scan_alarm(self, scan_id, host='', name='', value='', port='', test_id='', severity='', qod=''): self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name, value, port, test_id, severity, qod)
[ "def", "add_scan_alarm", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "severity", "=", "''", ",", "qod", "=", "''", ")", ":", "self...
Adds an alarm result to scan_id scan.
[ "Adds", "an", "alarm", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1648-L1652
18,337
greenbone/ospd
ospd/vtfilter.py
VtsFilter.parse_filters
def parse_filters(self, vt_filter): """ Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator, value] """ filter_list = vt_filter.split(';') filters = list() for single_filter in filter_list: filter_aux = re.split('(\W)', single_filter, 1) if len(filter_aux) < 3: raise OSPDError("Invalid number of argument in the filter", "get_vts") _element, _oper, _val = filter_aux if _element not in self.allowed_filter: raise OSPDError("Invalid filter element", "get_vts") if _oper not in self.filter_operator: raise OSPDError("Invalid filter operator", "get_vts") filters.append(filter_aux) return filters
python
def parse_filters(self, vt_filter): filter_list = vt_filter.split(';') filters = list() for single_filter in filter_list: filter_aux = re.split('(\W)', single_filter, 1) if len(filter_aux) < 3: raise OSPDError("Invalid number of argument in the filter", "get_vts") _element, _oper, _val = filter_aux if _element not in self.allowed_filter: raise OSPDError("Invalid filter element", "get_vts") if _oper not in self.filter_operator: raise OSPDError("Invalid filter operator", "get_vts") filters.append(filter_aux) return filters
[ "def", "parse_filters", "(", "self", ",", "vt_filter", ")", ":", "filter_list", "=", "vt_filter", ".", "split", "(", "';'", ")", "filters", "=", "list", "(", ")", "for", "single_filter", "in", "filter_list", ":", "filter_aux", "=", "re", ".", "split", "(...
Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator, value]
[ "Parse", "a", "string", "containing", "one", "or", "more", "filters", "and", "return", "a", "list", "of", "filters" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L41-L67
18,338
greenbone/ospd
ospd/vtfilter.py
VtsFilter.format_filter_value
def format_filter_value(self, element, value): """ Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value. """ format_func = self.allowed_filter.get(element) return format_func(value)
python
def format_filter_value(self, element, value): format_func = self.allowed_filter.get(element) return format_func(value)
[ "def", "format_filter_value", "(", "self", ",", "element", ",", "value", ")", ":", "format_func", "=", "self", ".", "allowed_filter", ".", "get", "(", "element", ")", "return", "format_func", "(", "value", ")" ]
Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value.
[ "Calls", "the", "specific", "function", "to", "format", "value", "depending", "on", "the", "given", "element", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L81-L94
18,339
greenbone/ospd
ospd/vtfilter.py
VtsFilter.get_filtered_vts_list
def get_filtered_vts_list(self, vts, vt_filter): """ Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests. """ if not vt_filter: raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if not filters: return None _vts_aux = vts.copy() for _element, _oper, _filter_val in filters: for vt_id in _vts_aux.copy(): if not _vts_aux[vt_id].get(_element): _vts_aux.pop(vt_id) continue _elem_val = _vts_aux[vt_id].get(_element) _val = self.format_filter_value(_element, _elem_val) if self.filter_operator[_oper](_val, _filter_val): continue else: _vts_aux.pop(vt_id) return _vts_aux
python
def get_filtered_vts_list(self, vts, vt_filter): if not vt_filter: raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if not filters: return None _vts_aux = vts.copy() for _element, _oper, _filter_val in filters: for vt_id in _vts_aux.copy(): if not _vts_aux[vt_id].get(_element): _vts_aux.pop(vt_id) continue _elem_val = _vts_aux[vt_id].get(_element) _val = self.format_filter_value(_element, _elem_val) if self.filter_operator[_oper](_val, _filter_val): continue else: _vts_aux.pop(vt_id) return _vts_aux
[ "def", "get_filtered_vts_list", "(", "self", ",", "vts", ",", "vt_filter", ")", ":", "if", "not", "vt_filter", ":", "raise", "RequiredArgument", "(", "'vt_filter: A valid filter is required.'", ")", "filters", "=", "self", ".", "parse_filters", "(", "vt_filter", "...
Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests.
[ "Gets", "a", "collection", "of", "vulnerability", "test", "from", "the", "vts", "dictionary", "which", "match", "the", "filter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L96-L127
18,340
greenbone/ospd
ospd/misc.py
inet_pton
def inet_pton(address_family, ip_string): """ A platform independent version of inet_pton """ global __inet_pton if __inet_pton is None: if hasattr(socket, 'inet_pton'): __inet_pton = socket.inet_pton else: from ospd import win_socket __inet_pton = win_socket.inet_pton return __inet_pton(address_family, ip_string)
python
def inet_pton(address_family, ip_string): global __inet_pton if __inet_pton is None: if hasattr(socket, 'inet_pton'): __inet_pton = socket.inet_pton else: from ospd import win_socket __inet_pton = win_socket.inet_pton return __inet_pton(address_family, ip_string)
[ "def", "inet_pton", "(", "address_family", ",", "ip_string", ")", ":", "global", "__inet_pton", "if", "__inet_pton", "is", "None", ":", "if", "hasattr", "(", "socket", ",", "'inet_pton'", ")", ":", "__inet_pton", "=", "socket", ".", "inet_pton", "else", ":",...
A platform independent version of inet_pton
[ "A", "platform", "independent", "version", "of", "inet_pton" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L365-L375
18,341
greenbone/ospd
ospd/misc.py
inet_ntop
def inet_ntop(address_family, packed_ip): """ A platform independent version of inet_ntop """ global __inet_ntop if __inet_ntop is None: if hasattr(socket, 'inet_ntop'): __inet_ntop = socket.inet_ntop else: from ospd import win_socket __inet_ntop = win_socket.inet_ntop return __inet_ntop(address_family, packed_ip)
python
def inet_ntop(address_family, packed_ip): global __inet_ntop if __inet_ntop is None: if hasattr(socket, 'inet_ntop'): __inet_ntop = socket.inet_ntop else: from ospd import win_socket __inet_ntop = win_socket.inet_ntop return __inet_ntop(address_family, packed_ip)
[ "def", "inet_ntop", "(", "address_family", ",", "packed_ip", ")", ":", "global", "__inet_ntop", "if", "__inet_ntop", "is", "None", ":", "if", "hasattr", "(", "socket", ",", "'inet_ntop'", ")", ":", "__inet_ntop", "=", "socket", ".", "inet_ntop", "else", ":",...
A platform independent version of inet_ntop
[ "A", "platform", "independent", "version", "of", "inet_ntop" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L381-L391
18,342
greenbone/ospd
ospd/misc.py
ipv4_range_to_list
def ipv4_range_to_list(start_packed, end_packed): """ Return a list of IPv4 entries from start_packed to end_packed. """ new_list = list() start = struct.unpack('!L', start_packed)[0] end = struct.unpack('!L', end_packed)[0] for value in range(start, end + 1): new_ip = socket.inet_ntoa(struct.pack('!L', value)) new_list.append(new_ip) return new_list
python
def ipv4_range_to_list(start_packed, end_packed): new_list = list() start = struct.unpack('!L', start_packed)[0] end = struct.unpack('!L', end_packed)[0] for value in range(start, end + 1): new_ip = socket.inet_ntoa(struct.pack('!L', value)) new_list.append(new_ip) return new_list
[ "def", "ipv4_range_to_list", "(", "start_packed", ",", "end_packed", ")", ":", "new_list", "=", "list", "(", ")", "start", "=", "struct", ".", "unpack", "(", "'!L'", ",", "start_packed", ")", "[", "0", "]", "end", "=", "struct", ".", "unpack", "(", "'!...
Return a list of IPv4 entries from start_packed to end_packed.
[ "Return", "a", "list", "of", "IPv4", "entries", "from", "start_packed", "to", "end_packed", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L414-L423
18,343
greenbone/ospd
ospd/misc.py
target_to_ipv4_short
def target_to_ipv4_short(target): """ Attempt to return a IPv4 short range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_value = int(splitted[1]) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(bytes(start_packed[3])), 16) if end_value < 0 or end_value > 255 or end_value < start_value: return None end_packed = start_packed[0:3] + struct.pack('B', end_value) return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_short(target): splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_value = int(splitted[1]) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(bytes(start_packed[3])), 16) if end_value < 0 or end_value > 255 or end_value < start_value: return None end_packed = start_packed[0:3] + struct.pack('B', end_value) return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_short", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF...
Attempt to return a IPv4 short range list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "short", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L426-L441
18,344
greenbone/ospd
ospd/misc.py
target_to_ipv4_cidr
def target_to_ipv4_cidr(target): """ Attempt to return a IPv4 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 30: return None start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block) start_value = (start_value << (32 - block)) + 1 end_value = (start_value | (0xffffffff >> block)) - 1 start_packed = struct.pack('!I', start_value) end_packed = struct.pack('!I', end_value) return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_cidr(target): splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 30: return None start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block) start_value = (start_value << (32 - block)) + 1 end_value = (start_value | (0xffffffff >> block)) - 1 start_packed = struct.pack('!I', start_value) end_packed = struct.pack('!I', end_value) return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_cidr", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'/'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_...
Attempt to return a IPv4 CIDR list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "CIDR", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L444-L462
18,345
greenbone/ospd
ospd/misc.py
target_to_ipv6_cidr
def target_to_ipv6_cidr(target): """ Attempt to return a IPv6 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 126: return None start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block) start_value = (start_value << (128 - block)) + 1 end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1 high = start_value >> 64 low = start_value & ((1 << 64) - 1) start_packed = struct.pack('!QQ', high, low) high = end_value >> 64 low = end_value & ((1 << 64) - 1) end_packed = struct.pack('!QQ', high, low) return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_cidr(target): splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 126: return None start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block) start_value = (start_value << (128 - block)) + 1 end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1 high = start_value >> 64 low = start_value & ((1 << 64) - 1) start_packed = struct.pack('!QQ', high, low) high = end_value >> 64 low = end_value & ((1 << 64) - 1) end_packed = struct.pack('!QQ', high, low) return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_cidr", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'/'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_...
Attempt to return a IPv6 CIDR list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "CIDR", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L465-L487
18,346
greenbone/ospd
ospd/misc.py
target_to_ipv4_long
def target_to_ipv4_long(target): """ Attempt to return a IPv4 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_long(target): splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_long", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_...
Attempt to return a IPv4 long-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "long", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L490-L503
18,347
greenbone/ospd
ospd/misc.py
ipv6_range_to_list
def ipv6_range_to_list(start_packed, end_packed): """ Return a list of IPv6 entries from start_packed to end_packed. """ new_list = list() start = int(binascii.hexlify(start_packed), 16) end = int(binascii.hexlify(end_packed), 16) for value in range(start, end + 1): high = value >> 64 low = value & ((1 << 64) - 1) new_ip = inet_ntop(socket.AF_INET6, struct.pack('!2Q', high, low)) new_list.append(new_ip) return new_list
python
def ipv6_range_to_list(start_packed, end_packed): new_list = list() start = int(binascii.hexlify(start_packed), 16) end = int(binascii.hexlify(end_packed), 16) for value in range(start, end + 1): high = value >> 64 low = value & ((1 << 64) - 1) new_ip = inet_ntop(socket.AF_INET6, struct.pack('!2Q', high, low)) new_list.append(new_ip) return new_list
[ "def", "ipv6_range_to_list", "(", "start_packed", ",", "end_packed", ")", ":", "new_list", "=", "list", "(", ")", "start", "=", "int", "(", "binascii", ".", "hexlify", "(", "start_packed", ")", ",", "16", ")", "end", "=", "int", "(", "binascii", ".", "...
Return a list of IPv6 entries from start_packed to end_packed.
[ "Return", "a", "list", "of", "IPv6", "entries", "from", "start_packed", "to", "end_packed", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L506-L518
18,348
greenbone/ospd
ospd/misc.py
target_to_ipv6_short
def target_to_ipv6_short(target): """ Attempt to return a IPv6 short-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(start_packed[14:]), 16) if end_value < 0 or end_value > 0xffff or end_value < start_value: return None end_packed = start_packed[:14] + struct.pack('!H', end_value) return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_short(target): splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(start_packed[14:]), 16) if end_value < 0 or end_value > 0xffff or end_value < start_value: return None end_packed = start_packed[:14] + struct.pack('!H', end_value) return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_short", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF...
Attempt to return a IPv6 short-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "short", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L521-L536
18,349
greenbone/ospd
ospd/misc.py
target_to_ipv6_long
def target_to_ipv6_long(target): """ Attempt to return a IPv6 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_packed = inet_pton(socket.AF_INET6, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_long(target): splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_packed = inet_pton(socket.AF_INET6, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_long", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_...
Attempt to return a IPv6 long-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "long", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L539-L552
18,350
greenbone/ospd
ospd/misc.py
target_to_hostname
def target_to_hostname(target): """ Attempt to return a single hostname list from a target string. """ if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
python
def target_to_hostname(target): if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
[ "def", "target_to_hostname", "(", "target", ")", ":", "if", "len", "(", "target", ")", "==", "0", "or", "len", "(", "target", ")", ">", "255", ":", "return", "None", "if", "not", "re", ".", "match", "(", "r'^[\\w.-]+$'", ",", "target", ")", ":", "r...
Attempt to return a single hostname list from a target string.
[ "Attempt", "to", "return", "a", "single", "hostname", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L555-L562
18,351
greenbone/ospd
ospd/misc.py
target_to_list
def target_to_list(target): """ Attempt to return a list of single hosts from a target string. """ # Is it an IPv4 address ? new_list = target_to_ipv4(target) # Is it an IPv6 address ? if not new_list: new_list = target_to_ipv6(target) # Is it an IPv4 CIDR ? if not new_list: new_list = target_to_ipv4_cidr(target) # Is it an IPv6 CIDR ? if not new_list: new_list = target_to_ipv6_cidr(target) # Is it an IPv4 short-range ? if not new_list: new_list = target_to_ipv4_short(target) # Is it an IPv4 long-range ? if not new_list: new_list = target_to_ipv4_long(target) # Is it an IPv6 short-range ? if not new_list: new_list = target_to_ipv6_short(target) # Is it an IPv6 long-range ? if not new_list: new_list = target_to_ipv6_long(target) # Is it a hostname ? if not new_list: new_list = target_to_hostname(target) return new_list
python
def target_to_list(target): # Is it an IPv4 address ? new_list = target_to_ipv4(target) # Is it an IPv6 address ? if not new_list: new_list = target_to_ipv6(target) # Is it an IPv4 CIDR ? if not new_list: new_list = target_to_ipv4_cidr(target) # Is it an IPv6 CIDR ? if not new_list: new_list = target_to_ipv6_cidr(target) # Is it an IPv4 short-range ? if not new_list: new_list = target_to_ipv4_short(target) # Is it an IPv4 long-range ? if not new_list: new_list = target_to_ipv4_long(target) # Is it an IPv6 short-range ? if not new_list: new_list = target_to_ipv6_short(target) # Is it an IPv6 long-range ? if not new_list: new_list = target_to_ipv6_long(target) # Is it a hostname ? if not new_list: new_list = target_to_hostname(target) return new_list
[ "def", "target_to_list", "(", "target", ")", ":", "# Is it an IPv4 address ?", "new_list", "=", "target_to_ipv4", "(", "target", ")", "# Is it an IPv6 address ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv6", "(", "target", ")", "# Is it an IPv4 CID...
Attempt to return a list of single hosts from a target string.
[ "Attempt", "to", "return", "a", "list", "of", "single", "hosts", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L565-L594
18,352
greenbone/ospd
ospd/misc.py
target_str_to_list
def target_str_to_list(target_str): """ Parses a targets string into a list of individual targets. """ new_list = list() for target in target_str.split(','): target = target.strip() target_list = target_to_list(target) if target_list: new_list.extend(target_list) else: LOGGER.info("{0}: Invalid target value".format(target)) return None return list(collections.OrderedDict.fromkeys(new_list))
python
def target_str_to_list(target_str): new_list = list() for target in target_str.split(','): target = target.strip() target_list = target_to_list(target) if target_list: new_list.extend(target_list) else: LOGGER.info("{0}: Invalid target value".format(target)) return None return list(collections.OrderedDict.fromkeys(new_list))
[ "def", "target_str_to_list", "(", "target_str", ")", ":", "new_list", "=", "list", "(", ")", "for", "target", "in", "target_str", ".", "split", "(", "','", ")", ":", "target", "=", "target", ".", "strip", "(", ")", "target_list", "=", "target_to_list", "...
Parses a targets string into a list of individual targets.
[ "Parses", "a", "targets", "string", "into", "a", "list", "of", "individual", "targets", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L597-L608
18,353
greenbone/ospd
ospd/misc.py
port_range_expand
def port_range_expand(portrange): """ Receive a port range and expands it in individual ports. @input Port range. e.g. "4-8" @return List of integers. e.g. [4, 5, 6, 7, 8] """ if not portrange or '-' not in portrange: LOGGER.info("Invalid port range format") return None port_list = list() for single_port in range(int(portrange[:portrange.index('-')]), int(portrange[portrange.index('-') + 1:]) + 1): port_list.append(single_port) return port_list
python
def port_range_expand(portrange): if not portrange or '-' not in portrange: LOGGER.info("Invalid port range format") return None port_list = list() for single_port in range(int(portrange[:portrange.index('-')]), int(portrange[portrange.index('-') + 1:]) + 1): port_list.append(single_port) return port_list
[ "def", "port_range_expand", "(", "portrange", ")", ":", "if", "not", "portrange", "or", "'-'", "not", "in", "portrange", ":", "LOGGER", ".", "info", "(", "\"Invalid port range format\"", ")", "return", "None", "port_list", "=", "list", "(", ")", "for", "sing...
Receive a port range and expands it in individual ports. @input Port range. e.g. "4-8" @return List of integers. e.g. [4, 5, 6, 7, 8]
[ "Receive", "a", "port", "range", "and", "expands", "it", "in", "individual", "ports", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L621-L638
18,354
greenbone/ospd
ospd/misc.py
ports_str_check_failed
def ports_str_check_failed(port_str): """ Check if the port string is well formed. Return True if fail, False other case. """ pattern = r'[^TU:0-9, \-]' if ( re.search(pattern, port_str) or port_str.count('T') > 1 or port_str.count('U') > 1 or port_str.count(':') < (port_str.count('T') + port_str.count('U')) ): return True return False
python
def ports_str_check_failed(port_str): pattern = r'[^TU:0-9, \-]' if ( re.search(pattern, port_str) or port_str.count('T') > 1 or port_str.count('U') > 1 or port_str.count(':') < (port_str.count('T') + port_str.count('U')) ): return True return False
[ "def", "ports_str_check_failed", "(", "port_str", ")", ":", "pattern", "=", "r'[^TU:0-9, \\-]'", "if", "(", "re", ".", "search", "(", "pattern", ",", "port_str", ")", "or", "port_str", ".", "count", "(", "'T'", ")", ">", "1", "or", "port_str", ".", "coun...
Check if the port string is well formed. Return True if fail, False other case.
[ "Check", "if", "the", "port", "string", "is", "well", "formed", ".", "Return", "True", "if", "fail", "False", "other", "case", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L653-L667
18,355
greenbone/ospd
ospd/misc.py
ports_as_list
def ports_as_list(port_str): """ Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively. """ if not port_str: LOGGER.info("Invalid port value") return [None, None] if ports_str_check_failed(port_str): LOGGER.info("{0}: Port list malformed.") return [None, None] tcp_list = list() udp_list = list() ports = port_str.replace(' ', '') b_tcp = ports.find("T") b_udp = ports.find("U") if ports[b_tcp - 1] == ',': ports = ports[:b_tcp - 1] + ports[b_tcp:] if ports[b_udp - 1] == ',': ports = ports[:b_udp - 1] + ports[b_udp:] ports = port_str_arrange(ports) tports = '' uports = '' # TCP ports listed first, then UDP ports if b_udp != -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:ports.index('U:')] uports = ports[ports.index('U:') + 2:] # Only UDP ports elif b_tcp == -1 and b_udp != -1: uports = ports[ports.index('U:') + 2:] # Only TCP ports elif b_udp == -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:] else: tports = ports if tports: for port in tports.split(','): if '-' in port: tcp_list.extend(port_range_expand(port)) else: tcp_list.append(int(port)) tcp_list.sort() if uports: for port in uports.split(','): if '-' in port: udp_list.extend(port_range_expand(port)) else: udp_list.append(int(port)) udp_list.sort() return (tcp_list, udp_list)
python
def ports_as_list(port_str): if not port_str: LOGGER.info("Invalid port value") return [None, None] if ports_str_check_failed(port_str): LOGGER.info("{0}: Port list malformed.") return [None, None] tcp_list = list() udp_list = list() ports = port_str.replace(' ', '') b_tcp = ports.find("T") b_udp = ports.find("U") if ports[b_tcp - 1] == ',': ports = ports[:b_tcp - 1] + ports[b_tcp:] if ports[b_udp - 1] == ',': ports = ports[:b_udp - 1] + ports[b_udp:] ports = port_str_arrange(ports) tports = '' uports = '' # TCP ports listed first, then UDP ports if b_udp != -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:ports.index('U:')] uports = ports[ports.index('U:') + 2:] # Only UDP ports elif b_tcp == -1 and b_udp != -1: uports = ports[ports.index('U:') + 2:] # Only TCP ports elif b_udp == -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:] else: tports = ports if tports: for port in tports.split(','): if '-' in port: tcp_list.extend(port_range_expand(port)) else: tcp_list.append(int(port)) tcp_list.sort() if uports: for port in uports.split(','): if '-' in port: udp_list.extend(port_range_expand(port)) else: udp_list.append(int(port)) udp_list.sort() return (tcp_list, udp_list)
[ "def", "ports_as_list", "(", "port_str", ")", ":", "if", "not", "port_str", ":", "LOGGER", ".", "info", "(", "\"Invalid port value\"", ")", "return", "[", "None", ",", "None", "]", "if", "ports_str_check_failed", "(", "port_str", ")", ":", "LOGGER", ".", "...
Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively.
[ "Parses", "a", "ports", "string", "into", "two", "list", "of", "individual", "tcp", "and", "udp", "ports", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L670-L729
18,356
greenbone/ospd
ospd/misc.py
port_list_compress
def port_list_compress(port_list): """ Compress a port list and return a string. """ if not port_list or len(port_list) == 0: LOGGER.info("Invalid or empty port list.") return '' port_list = sorted(set(port_list)) compressed_list = [] for key, group in itertools.groupby(enumerate(port_list), lambda t: t[1] - t[0]): group = list(group) if group[0][1] == group[-1][1]: compressed_list.append(str(group[0][1])) else: compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1])) return ','.join(compressed_list)
python
def port_list_compress(port_list): if not port_list or len(port_list) == 0: LOGGER.info("Invalid or empty port list.") return '' port_list = sorted(set(port_list)) compressed_list = [] for key, group in itertools.groupby(enumerate(port_list), lambda t: t[1] - t[0]): group = list(group) if group[0][1] == group[-1][1]: compressed_list.append(str(group[0][1])) else: compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1])) return ','.join(compressed_list)
[ "def", "port_list_compress", "(", "port_list", ")", ":", "if", "not", "port_list", "or", "len", "(", "port_list", ")", "==", "0", ":", "LOGGER", ".", "info", "(", "\"Invalid or empty port list.\"", ")", "return", "''", "port_list", "=", "sorted", "(", "set",...
Compress a port list and return a string.
[ "Compress", "a", "port", "list", "and", "return", "a", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L742-L759
18,357
greenbone/ospd
ospd/misc.py
valid_uuid
def valid_uuid(value): """ Check if value is a valid UUID. """ try: uuid.UUID(value, version=4) return True except (TypeError, ValueError, AttributeError): return False
python
def valid_uuid(value): try: uuid.UUID(value, version=4) return True except (TypeError, ValueError, AttributeError): return False
[ "def", "valid_uuid", "(", "value", ")", ":", "try", ":", "uuid", ".", "UUID", "(", "value", ",", "version", "=", "4", ")", "return", "True", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "return", "False" ]
Check if value is a valid UUID.
[ "Check", "if", "value", "is", "a", "valid", "UUID", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L762-L769
18,358
greenbone/ospd
ospd/misc.py
create_args_parser
def create_args_parser(description): """ Create a command-line arguments parser for OSPD. """ parser = argparse.ArgumentParser(description=description) def network_port(string): """ Check if provided string is a valid network port. """ value = int(string) if not 0 < value <= 65535: raise argparse.ArgumentTypeError( 'port must be in ]0,65535] interval') return value def cacert_file(cacert): """ Check if provided file is a valid CA Certificate """ try: context = ssl.create_default_context(cafile=cacert) except AttributeError: # Python version < 2.7.9 return cacert except IOError: raise argparse.ArgumentTypeError('CA Certificate not found') try: not_after = context.get_ca_certs()[0]['notAfter'] not_after = ssl.cert_time_to_seconds(not_after) not_before = context.get_ca_certs()[0]['notBefore'] not_before = ssl.cert_time_to_seconds(not_before) except (KeyError, IndexError): raise argparse.ArgumentTypeError('CA Certificate is erroneous') if not_after < int(time.time()): raise argparse.ArgumentTypeError('CA Certificate expired') if not_before > int(time.time()): raise argparse.ArgumentTypeError('CA Certificate not active yet') return cacert def log_level(string): """ Check if provided string is a valid log level. """ value = getattr(logging, string.upper(), None) if not isinstance(value, int): raise argparse.ArgumentTypeError( 'log level must be one of {debug,info,warning,error,critical}') return value def filename(string): """ Check if provided string is a valid file path. """ if not os.path.isfile(string): raise argparse.ArgumentTypeError( '%s is not a valid file path' % string) return string parser.add_argument('-p', '--port', default=PORT, type=network_port, help='TCP Port to listen on. Default: {0}'.format(PORT)) parser.add_argument('-b', '--bind-address', default=ADDRESS, help='Address to listen on. Default: {0}' .format(ADDRESS)) parser.add_argument('-u', '--unix-socket', help='Unix file socket to listen on.') parser.add_argument('-k', '--key-file', type=filename, help='Server key file. Default: {0}'.format(KEY_FILE)) parser.add_argument('-c', '--cert-file', type=filename, help='Server cert file. Default: {0}'.format(CERT_FILE)) parser.add_argument('--ca-file', type=cacert_file, help='CA cert file. Default: {0}'.format(CA_FILE)) parser.add_argument('-L', '--log-level', default='warning', type=log_level, help='Wished level of logging. Default: WARNING') parser.add_argument('--foreground', action='store_true', help='Run in foreground and logs all messages to console.') parser.add_argument('-l', '--log-file', type=filename, help='Path to the logging file.') parser.add_argument('--version', action='store_true', help='Print version then exit.') return parser
python
def create_args_parser(description): parser = argparse.ArgumentParser(description=description) def network_port(string): """ Check if provided string is a valid network port. """ value = int(string) if not 0 < value <= 65535: raise argparse.ArgumentTypeError( 'port must be in ]0,65535] interval') return value def cacert_file(cacert): """ Check if provided file is a valid CA Certificate """ try: context = ssl.create_default_context(cafile=cacert) except AttributeError: # Python version < 2.7.9 return cacert except IOError: raise argparse.ArgumentTypeError('CA Certificate not found') try: not_after = context.get_ca_certs()[0]['notAfter'] not_after = ssl.cert_time_to_seconds(not_after) not_before = context.get_ca_certs()[0]['notBefore'] not_before = ssl.cert_time_to_seconds(not_before) except (KeyError, IndexError): raise argparse.ArgumentTypeError('CA Certificate is erroneous') if not_after < int(time.time()): raise argparse.ArgumentTypeError('CA Certificate expired') if not_before > int(time.time()): raise argparse.ArgumentTypeError('CA Certificate not active yet') return cacert def log_level(string): """ Check if provided string is a valid log level. """ value = getattr(logging, string.upper(), None) if not isinstance(value, int): raise argparse.ArgumentTypeError( 'log level must be one of {debug,info,warning,error,critical}') return value def filename(string): """ Check if provided string is a valid file path. """ if not os.path.isfile(string): raise argparse.ArgumentTypeError( '%s is not a valid file path' % string) return string parser.add_argument('-p', '--port', default=PORT, type=network_port, help='TCP Port to listen on. Default: {0}'.format(PORT)) parser.add_argument('-b', '--bind-address', default=ADDRESS, help='Address to listen on. Default: {0}' .format(ADDRESS)) parser.add_argument('-u', '--unix-socket', help='Unix file socket to listen on.') parser.add_argument('-k', '--key-file', type=filename, help='Server key file. Default: {0}'.format(KEY_FILE)) parser.add_argument('-c', '--cert-file', type=filename, help='Server cert file. Default: {0}'.format(CERT_FILE)) parser.add_argument('--ca-file', type=cacert_file, help='CA cert file. Default: {0}'.format(CA_FILE)) parser.add_argument('-L', '--log-level', default='warning', type=log_level, help='Wished level of logging. Default: WARNING') parser.add_argument('--foreground', action='store_true', help='Run in foreground and logs all messages to console.') parser.add_argument('-l', '--log-file', type=filename, help='Path to the logging file.') parser.add_argument('--version', action='store_true', help='Print version then exit.') return parser
[ "def", "create_args_parser", "(", "description", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "def", "network_port", "(", "string", ")", ":", "\"\"\" Check if provided string is a valid network port. \"\"\"", "...
Create a command-line arguments parser for OSPD.
[ "Create", "a", "command", "-", "line", "arguments", "parser", "for", "OSPD", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L772-L846
18,359
greenbone/ospd
ospd/misc.py
go_to_background
def go_to_background(): """ Daemonize the running process. """ try: if os.fork(): sys.exit() except OSError as errmsg: LOGGER.error('Fork failed: {0}'.format(errmsg)) sys.exit('Fork failed')
python
def go_to_background(): try: if os.fork(): sys.exit() except OSError as errmsg: LOGGER.error('Fork failed: {0}'.format(errmsg)) sys.exit('Fork failed')
[ "def", "go_to_background", "(", ")", ":", "try", ":", "if", "os", ".", "fork", "(", ")", ":", "sys", ".", "exit", "(", ")", "except", "OSError", "as", "errmsg", ":", "LOGGER", ".", "error", "(", "'Fork failed: {0}'", ".", "format", "(", "errmsg", ")"...
Daemonize the running process.
[ "Daemonize", "the", "running", "process", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L849-L856
18,360
greenbone/ospd
ospd/misc.py
get_common_args
def get_common_args(parser, args=None): """ Return list of OSPD common command-line arguments from parser, after validating provided values or setting default ones. """ options = parser.parse_args(args) # TCP Port to listen on. port = options.port # Network address to bind listener to address = options.bind_address # Unix file socket to listen on unix_socket = options.unix_socket # Debug level. log_level = options.log_level # Server key path. keyfile = options.key_file or KEY_FILE # Server cert path. certfile = options.cert_file or CERT_FILE # CA cert path. cafile = options.ca_file or CA_FILE common_args = dict() common_args['port'] = port common_args['address'] = address common_args['unix_socket'] = unix_socket common_args['keyfile'] = keyfile common_args['certfile'] = certfile common_args['cafile'] = cafile common_args['log_level'] = log_level common_args['foreground'] = options.foreground common_args['log_file'] = options.log_file common_args['version'] = options.version return common_args
python
def get_common_args(parser, args=None): options = parser.parse_args(args) # TCP Port to listen on. port = options.port # Network address to bind listener to address = options.bind_address # Unix file socket to listen on unix_socket = options.unix_socket # Debug level. log_level = options.log_level # Server key path. keyfile = options.key_file or KEY_FILE # Server cert path. certfile = options.cert_file or CERT_FILE # CA cert path. cafile = options.ca_file or CA_FILE common_args = dict() common_args['port'] = port common_args['address'] = address common_args['unix_socket'] = unix_socket common_args['keyfile'] = keyfile common_args['certfile'] = certfile common_args['cafile'] = cafile common_args['log_level'] = log_level common_args['foreground'] = options.foreground common_args['log_file'] = options.log_file common_args['version'] = options.version return common_args
[ "def", "get_common_args", "(", "parser", ",", "args", "=", "None", ")", ":", "options", "=", "parser", ".", "parse_args", "(", "args", ")", "# TCP Port to listen on.", "port", "=", "options", ".", "port", "# Network address to bind listener to", "address", "=", ...
Return list of OSPD common command-line arguments from parser, after validating provided values or setting default ones.
[ "Return", "list", "of", "OSPD", "common", "command", "-", "line", "arguments", "from", "parser", "after", "validating", "provided", "values", "or", "setting", "default", "ones", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L859-L899
18,361
greenbone/ospd
ospd/misc.py
print_version
def print_version(wrapper): """ Prints the server version and license information.""" scanner_name = wrapper.get_scanner_name() server_version = wrapper.get_server_version() print("OSP Server for {0} version {1}".format(scanner_name, server_version)) protocol_version = wrapper.get_protocol_version() print("OSP Version: {0}".format(protocol_version)) daemon_name = wrapper.get_daemon_name() daemon_version = wrapper.get_daemon_version() print("Using: {0} {1}".format(daemon_name, daemon_version)) print("Copyright (C) 2014, 2015 Greenbone Networks GmbH\n" "License GPLv2+: GNU GPL version 2 or later\n" "This is free software: you are free to change" " and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.")
python
def print_version(wrapper): scanner_name = wrapper.get_scanner_name() server_version = wrapper.get_server_version() print("OSP Server for {0} version {1}".format(scanner_name, server_version)) protocol_version = wrapper.get_protocol_version() print("OSP Version: {0}".format(protocol_version)) daemon_name = wrapper.get_daemon_name() daemon_version = wrapper.get_daemon_version() print("Using: {0} {1}".format(daemon_name, daemon_version)) print("Copyright (C) 2014, 2015 Greenbone Networks GmbH\n" "License GPLv2+: GNU GPL version 2 or later\n" "This is free software: you are free to change" " and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.")
[ "def", "print_version", "(", "wrapper", ")", ":", "scanner_name", "=", "wrapper", ".", "get_scanner_name", "(", ")", "server_version", "=", "wrapper", ".", "get_server_version", "(", ")", "print", "(", "\"OSP Server for {0} version {1}\"", ".", "format", "(", "sca...
Prints the server version and license information.
[ "Prints", "the", "server", "version", "and", "license", "information", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L902-L917
18,362
greenbone/ospd
ospd/misc.py
main
def main(name, klass): """ OSPD Main function. """ # Common args parser. parser = create_args_parser(name) # Common args cargs = get_common_args(parser) logging.getLogger().setLevel(cargs['log_level']) wrapper = klass(certfile=cargs['certfile'], keyfile=cargs['keyfile'], cafile=cargs['cafile']) if cargs['version']: print_version(wrapper) sys.exit() if cargs['foreground']: console = logging.StreamHandler() console.setFormatter( logging.Formatter( '%(asctime)s %(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(console) elif cargs['log_file']: logfile = logging.handlers.WatchedFileHandler(cargs['log_file']) logfile.setFormatter( logging.Formatter( '%(asctime)s %(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(logfile) go_to_background() else: syslog = logging.handlers.SysLogHandler('/dev/log') syslog.setFormatter( logging.Formatter('%(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(syslog) # Duplicate syslog's file descriptor to stout/stderr. syslog_fd = syslog.socket.fileno() os.dup2(syslog_fd, 1) os.dup2(syslog_fd, 2) go_to_background() if not wrapper.check(): return 1 return wrapper.run(cargs['address'], cargs['port'], cargs['unix_socket'])
python
def main(name, klass): # Common args parser. parser = create_args_parser(name) # Common args cargs = get_common_args(parser) logging.getLogger().setLevel(cargs['log_level']) wrapper = klass(certfile=cargs['certfile'], keyfile=cargs['keyfile'], cafile=cargs['cafile']) if cargs['version']: print_version(wrapper) sys.exit() if cargs['foreground']: console = logging.StreamHandler() console.setFormatter( logging.Formatter( '%(asctime)s %(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(console) elif cargs['log_file']: logfile = logging.handlers.WatchedFileHandler(cargs['log_file']) logfile.setFormatter( logging.Formatter( '%(asctime)s %(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(logfile) go_to_background() else: syslog = logging.handlers.SysLogHandler('/dev/log') syslog.setFormatter( logging.Formatter('%(name)s: %(levelname)s: %(message)s')) logging.getLogger().addHandler(syslog) # Duplicate syslog's file descriptor to stout/stderr. syslog_fd = syslog.socket.fileno() os.dup2(syslog_fd, 1) os.dup2(syslog_fd, 2) go_to_background() if not wrapper.check(): return 1 return wrapper.run(cargs['address'], cargs['port'], cargs['unix_socket'])
[ "def", "main", "(", "name", ",", "klass", ")", ":", "# Common args parser.", "parser", "=", "create_args_parser", "(", "name", ")", "# Common args", "cargs", "=", "get_common_args", "(", "parser", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", ...
OSPD Main function.
[ "OSPD", "Main", "function", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L920-L962
18,363
greenbone/ospd
ospd/misc.py
ScanCollection.add_result
def add_result(self, scan_id, result_type, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Add a result to a scan in the table. """ assert scan_id assert len(name) or len(value) result = dict() result['type'] = result_type result['name'] = name result['severity'] = severity result['test_id'] = test_id result['value'] = value result['host'] = host result['port'] = port result['qod'] = qod results = self.scans_table[scan_id]['results'] results.append(result) # Set scan_info's results to propagate results to parent process. self.scans_table[scan_id]['results'] = results
python
def add_result(self, scan_id, result_type, host='', name='', value='', port='', test_id='', severity='', qod=''): assert scan_id assert len(name) or len(value) result = dict() result['type'] = result_type result['name'] = name result['severity'] = severity result['test_id'] = test_id result['value'] = value result['host'] = host result['port'] = port result['qod'] = qod results = self.scans_table[scan_id]['results'] results.append(result) # Set scan_info's results to propagate results to parent process. self.scans_table[scan_id]['results'] = results
[ "def", "add_result", "(", "self", ",", "scan_id", ",", "result_type", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "severity", "=", "''", ",", "qod", "=", "''", ...
Add a result to a scan in the table.
[ "Add", "a", "result", "to", "a", "scan", "in", "the", "table", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L87-L105
18,364
greenbone/ospd
ospd/misc.py
ScanCollection.get_hosts_unfinished
def get_hosts_unfinished(self, scan_id): """ Get a list of finished hosts.""" unfinished_hosts = list() for target in self.scans_table[scan_id]['finished_hosts']: unfinished_hosts.extend(target_str_to_list(target)) for target in self.scans_table[scan_id]['finished_hosts']: for host in self.scans_table[scan_id]['finished_hosts'][target]: unfinished_hosts.remove(host) return unfinished_hosts
python
def get_hosts_unfinished(self, scan_id): unfinished_hosts = list() for target in self.scans_table[scan_id]['finished_hosts']: unfinished_hosts.extend(target_str_to_list(target)) for target in self.scans_table[scan_id]['finished_hosts']: for host in self.scans_table[scan_id]['finished_hosts'][target]: unfinished_hosts.remove(host) return unfinished_hosts
[ "def", "get_hosts_unfinished", "(", "self", ",", "scan_id", ")", ":", "unfinished_hosts", "=", "list", "(", ")", "for", "target", "in", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'finished_hosts'", "]", ":", "unfinished_hosts", ".", "extend", "("...
Get a list of finished hosts.
[ "Get", "a", "list", "of", "finished", "hosts", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L130-L140
18,365
greenbone/ospd
ospd/misc.py
ScanCollection.results_iterator
def results_iterator(self, scan_id, pop_res): """ Returns an iterator over scan_id scan's results. If pop_res is True, it removed the fetched results from the list. """ if pop_res: result_aux = self.scans_table[scan_id]['results'] self.scans_table[scan_id]['results'] = list() return iter(result_aux) return iter(self.scans_table[scan_id]['results'])
python
def results_iterator(self, scan_id, pop_res): if pop_res: result_aux = self.scans_table[scan_id]['results'] self.scans_table[scan_id]['results'] = list() return iter(result_aux) return iter(self.scans_table[scan_id]['results'])
[ "def", "results_iterator", "(", "self", ",", "scan_id", ",", "pop_res", ")", ":", "if", "pop_res", ":", "result_aux", "=", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'results'", "]", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'res...
Returns an iterator over scan_id scan's results. If pop_res is True, it removed the fetched results from the list.
[ "Returns", "an", "iterator", "over", "scan_id", "scan", "s", "results", ".", "If", "pop_res", "is", "True", "it", "removed", "the", "fetched", "results", "from", "the", "list", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L142-L151
18,366
greenbone/ospd
ospd/misc.py
ScanCollection.del_results_for_stopped_hosts
def del_results_for_stopped_hosts(self, scan_id): """ Remove results from the result table for those host """ unfinished_hosts = self.get_hosts_unfinished(scan_id) for result in self.results_iterator(scan_id, False): if result['host'] in unfinished_hosts: self.remove_single_result(scan_id, result)
python
def del_results_for_stopped_hosts(self, scan_id): unfinished_hosts = self.get_hosts_unfinished(scan_id) for result in self.results_iterator(scan_id, False): if result['host'] in unfinished_hosts: self.remove_single_result(scan_id, result)
[ "def", "del_results_for_stopped_hosts", "(", "self", ",", "scan_id", ")", ":", "unfinished_hosts", "=", "self", ".", "get_hosts_unfinished", "(", "scan_id", ")", "for", "result", "in", "self", ".", "results_iterator", "(", "scan_id", ",", "False", ")", ":", "i...
Remove results from the result table for those host
[ "Remove", "results", "from", "the", "result", "table", "for", "those", "host" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L162-L168
18,367
greenbone/ospd
ospd/misc.py
ScanCollection.create_scan
def create_scan(self, scan_id='', targets='', options=None, vts=''): """ Creates a new scan with provided scan information. """ if self.data_manager is None: self.data_manager = multiprocessing.Manager() # Check if it is possible to resume task. To avoid to resume, the # scan must be deleted from the scans_table. if scan_id and self.id_exists(scan_id) and ( self.get_status(scan_id) == ScanStatus.STOPPED): return self.resume_scan(scan_id, options) if not options: options = dict() scan_info = self.data_manager.dict() scan_info['results'] = list() scan_info['finished_hosts'] = dict( [[target, []] for target, _, _ in targets]) scan_info['progress'] = 0 scan_info['target_progress'] = dict( [[target, {}] for target, _, _ in targets]) scan_info['targets'] = targets scan_info['vts'] = vts scan_info['options'] = options scan_info['start_time'] = int(time.time()) scan_info['end_time'] = "0" scan_info['status'] = ScanStatus.INIT if scan_id is None or scan_id == '': scan_id = str(uuid.uuid4()) scan_info['scan_id'] = scan_id self.scans_table[scan_id] = scan_info return scan_id
python
def create_scan(self, scan_id='', targets='', options=None, vts=''): if self.data_manager is None: self.data_manager = multiprocessing.Manager() # Check if it is possible to resume task. To avoid to resume, the # scan must be deleted from the scans_table. if scan_id and self.id_exists(scan_id) and ( self.get_status(scan_id) == ScanStatus.STOPPED): return self.resume_scan(scan_id, options) if not options: options = dict() scan_info = self.data_manager.dict() scan_info['results'] = list() scan_info['finished_hosts'] = dict( [[target, []] for target, _, _ in targets]) scan_info['progress'] = 0 scan_info['target_progress'] = dict( [[target, {}] for target, _, _ in targets]) scan_info['targets'] = targets scan_info['vts'] = vts scan_info['options'] = options scan_info['start_time'] = int(time.time()) scan_info['end_time'] = "0" scan_info['status'] = ScanStatus.INIT if scan_id is None or scan_id == '': scan_id = str(uuid.uuid4()) scan_info['scan_id'] = scan_id self.scans_table[scan_id] = scan_info return scan_id
[ "def", "create_scan", "(", "self", ",", "scan_id", "=", "''", ",", "targets", "=", "''", ",", "options", "=", "None", ",", "vts", "=", "''", ")", ":", "if", "self", ".", "data_manager", "is", "None", ":", "self", ".", "data_manager", "=", "multiproce...
Creates a new scan with provided scan information.
[ "Creates", "a", "new", "scan", "with", "provided", "scan", "information", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L191-L222
18,368
greenbone/ospd
ospd/misc.py
ScanCollection.set_option
def set_option(self, scan_id, name, value): """ Set a scan_id scan's name option to value. """ self.scans_table[scan_id]['options'][name] = value
python
def set_option(self, scan_id, name, value): self.scans_table[scan_id]['options'][name] = value
[ "def", "set_option", "(", "self", ",", "scan_id", ",", "name", ",", "value", ")", ":", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'options'", "]", "[", "name", "]", "=", "value" ]
Set a scan_id scan's name option to value.
[ "Set", "a", "scan_id", "scan", "s", "name", "option", "to", "value", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L238-L241
18,369
greenbone/ospd
ospd/misc.py
ScanCollection.get_target_progress
def get_target_progress(self, scan_id, target): """ Get a target's current progress value. The value is calculated with the progress of each single host in the target.""" total_hosts = len(target_str_to_list(target)) host_progresses = self.scans_table[scan_id]['target_progress'].get(target) try: t_prog = sum(host_progresses.values()) / total_hosts except ZeroDivisionError: LOGGER.error("Zero division error in ", get_target_progress.__name__) raise return t_prog
python
def get_target_progress(self, scan_id, target): total_hosts = len(target_str_to_list(target)) host_progresses = self.scans_table[scan_id]['target_progress'].get(target) try: t_prog = sum(host_progresses.values()) / total_hosts except ZeroDivisionError: LOGGER.error("Zero division error in ", get_target_progress.__name__) raise return t_prog
[ "def", "get_target_progress", "(", "self", ",", "scan_id", ",", "target", ")", ":", "total_hosts", "=", "len", "(", "target_str_to_list", "(", "target", ")", ")", "host_progresses", "=", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'target_progress'"...
Get a target's current progress value. The value is calculated with the progress of each single host in the target.
[ "Get", "a", "target", "s", "current", "progress", "value", ".", "The", "value", "is", "calculated", "with", "the", "progress", "of", "each", "single", "host", "in", "the", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L248-L260
18,370
greenbone/ospd
ospd/misc.py
ScanCollection.get_target_list
def get_target_list(self, scan_id): """ Get a scan's target list. """ target_list = [] for target, _, _ in self.scans_table[scan_id]['targets']: target_list.append(target) return target_list
python
def get_target_list(self, scan_id): target_list = [] for target, _, _ in self.scans_table[scan_id]['targets']: target_list.append(target) return target_list
[ "def", "get_target_list", "(", "self", ",", "scan_id", ")", ":", "target_list", "=", "[", "]", "for", "target", ",", "_", ",", "_", "in", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'targets'", "]", ":", "target_list", ".", "append", "(", ...
Get a scan's target list.
[ "Get", "a", "scan", "s", "target", "list", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L272-L278
18,371
greenbone/ospd
ospd/misc.py
ScanCollection.get_ports
def get_ports(self, scan_id, target): """ Get a scan's ports list. If a target is specified it will return the corresponding port for it. If not, it returns the port item of the first nested list in the target's list. """ if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[1] return self.scans_table[scan_id]['targets'][0][1]
python
def get_ports(self, scan_id, target): if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[1] return self.scans_table[scan_id]['targets'][0][1]
[ "def", "get_ports", "(", "self", ",", "scan_id", ",", "target", ")", ":", "if", "target", ":", "for", "item", "in", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'targets'", "]", ":", "if", "target", "==", "item", "[", "0", "]", ":", "retu...
Get a scan's ports list. If a target is specified it will return the corresponding port for it. If not, it returns the port item of the first nested list in the target's list.
[ "Get", "a", "scan", "s", "ports", "list", ".", "If", "a", "target", "is", "specified", "it", "will", "return", "the", "corresponding", "port", "for", "it", ".", "If", "not", "it", "returns", "the", "port", "item", "of", "the", "first", "nested", "list"...
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L280-L291
18,372
greenbone/ospd
ospd/misc.py
ScanCollection.get_credentials
def get_credentials(self, scan_id, target): """ Get a scan's credential list. It return dictionary with the corresponding credential for a given target. """ if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[2]
python
def get_credentials(self, scan_id, target): if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[2]
[ "def", "get_credentials", "(", "self", ",", "scan_id", ",", "target", ")", ":", "if", "target", ":", "for", "item", "in", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'targets'", "]", ":", "if", "target", "==", "item", "[", "0", "]", ":", ...
Get a scan's credential list. It return dictionary with the corresponding credential for a given target.
[ "Get", "a", "scan", "s", "credential", "list", ".", "It", "return", "dictionary", "with", "the", "corresponding", "credential", "for", "a", "given", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L293-L300
18,373
greenbone/ospd
ospd/misc.py
ScanCollection.delete_scan
def delete_scan(self, scan_id): """ Delete a scan if fully finished. """ if self.get_status(scan_id) == ScanStatus.RUNNING: return False self.scans_table.pop(scan_id) if len(self.scans_table) == 0: del self.data_manager self.data_manager = None return True
python
def delete_scan(self, scan_id): if self.get_status(scan_id) == ScanStatus.RUNNING: return False self.scans_table.pop(scan_id) if len(self.scans_table) == 0: del self.data_manager self.data_manager = None return True
[ "def", "delete_scan", "(", "self", ",", "scan_id", ")", ":", "if", "self", ".", "get_status", "(", "scan_id", ")", "==", "ScanStatus", ".", "RUNNING", ":", "return", "False", "self", ".", "scans_table", ".", "pop", "(", "scan_id", ")", "if", "len", "("...
Delete a scan if fully finished.
[ "Delete", "a", "scan", "if", "fully", "finished", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L312-L321
18,374
Grokzen/pykwalify
pykwalify/types.py
is_timestamp
def is_timestamp(obj): """ Yaml either have automatically converted it to a datetime object or it is a string that will be validated later. """ return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
python
def is_timestamp(obj): return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
[ "def", "is_timestamp", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", "or", "is_string", "(", "obj", ")", "or", "is_int", "(", "obj", ")", "or", "is_float", "(", "obj", ")" ]
Yaml either have automatically converted it to a datetime object or it is a string that will be validated later.
[ "Yaml", "either", "have", "automatically", "converted", "it", "to", "a", "datetime", "object", "or", "it", "is", "a", "string", "that", "will", "be", "validated", "later", "." ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/types.py#L131-L136
18,375
Grokzen/pykwalify
pykwalify/__init__.py
init_logging
def init_logging(log_level): """ Init logging settings with default set to INFO """ log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": log_level, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": log_level, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf)
python
def init_logging(log_level): log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": log_level, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": log_level, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf)
[ "def", "init_logging", "(", "log_level", ")", ":", "log_level", "=", "log_level_to_string_map", "[", "min", "(", "log_level", ",", "5", ")", "]", "msg", "=", "\"%(levelname)s - %(name)s:%(lineno)s - %(message)s\"", "if", "log_level", "in", "os", ".", "environ", "e...
Init logging settings with default set to INFO
[ "Init", "logging", "settings", "with", "default", "set", "to", "INFO" ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/__init__.py#L25-L54
18,376
Grokzen/pykwalify
pykwalify/rule.py
Rule.keywords
def keywords(self): """ Returns a list of all keywords that this rule object has defined. A keyword is considered defined if the value it returns != None. """ defined_keywords = [ ('allowempty_map', 'allowempty_map'), ('assertion', 'assertion'), ('default', 'default'), ('class', 'class'), ('desc', 'desc'), ('enum', 'enum'), ('example', 'example'), ('extensions', 'extensions'), ('format', 'format'), ('func', 'func'), ('ident', 'ident'), ('include_name', 'include'), ('length', 'length'), ('map_regex_rule', 'map_regex_rule'), ('mapping', 'mapping'), ('matching', 'matching'), ('matching_rule', 'matching_rule'), ('name', 'name'), ('nullable', 'nullable') ('parent', 'parent'), ('pattern', 'pattern'), ('pattern_regexp', 'pattern_regexp'), ('range', 'range'), ('regex_mappings', 'regex_mappings'), ('required', 'required'), ('schema', 'schema'), ('schema_str', 'schema_str'), ('sequence', 'sequence'), ('type', 'type'), ('type_class', 'type_class'), ('unique', 'unique'), ('version', 'version'), ] found_keywords = [] for var_name, keyword_name in defined_keywords: if getattr(self, var_name, None): found_keywords.append(keyword_name) return found_keywords
python
def keywords(self): defined_keywords = [ ('allowempty_map', 'allowempty_map'), ('assertion', 'assertion'), ('default', 'default'), ('class', 'class'), ('desc', 'desc'), ('enum', 'enum'), ('example', 'example'), ('extensions', 'extensions'), ('format', 'format'), ('func', 'func'), ('ident', 'ident'), ('include_name', 'include'), ('length', 'length'), ('map_regex_rule', 'map_regex_rule'), ('mapping', 'mapping'), ('matching', 'matching'), ('matching_rule', 'matching_rule'), ('name', 'name'), ('nullable', 'nullable') ('parent', 'parent'), ('pattern', 'pattern'), ('pattern_regexp', 'pattern_regexp'), ('range', 'range'), ('regex_mappings', 'regex_mappings'), ('required', 'required'), ('schema', 'schema'), ('schema_str', 'schema_str'), ('sequence', 'sequence'), ('type', 'type'), ('type_class', 'type_class'), ('unique', 'unique'), ('version', 'version'), ] found_keywords = [] for var_name, keyword_name in defined_keywords: if getattr(self, var_name, None): found_keywords.append(keyword_name) return found_keywords
[ "def", "keywords", "(", "self", ")", ":", "defined_keywords", "=", "[", "(", "'allowempty_map'", ",", "'allowempty_map'", ")", ",", "(", "'assertion'", ",", "'assertion'", ")", ",", "(", "'default'", ",", "'default'", ")", ",", "(", "'class'", ",", "'class...
Returns a list of all keywords that this rule object has defined. A keyword is considered defined if the value it returns != None.
[ "Returns", "a", "list", "of", "all", "keywords", "that", "this", "rule", "object", "has", "defined", ".", "A", "keyword", "is", "considered", "defined", "if", "the", "value", "it", "returns", "!", "=", "None", "." ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/rule.py#L319-L364
18,377
Grokzen/pykwalify
pykwalify/core.py
Core._load_extensions
def _load_extensions(self): """ Load all extension files into the namespace pykwalify.ext """ log.debug(u"loading all extensions : %s", self.extensions) self.loaded_extensions = [] for f in self.extensions: if not os.path.isabs(f): f = os.path.abspath(f) if not os.path.exists(f): raise CoreError(u"Extension file: {0} not found on disk".format(f)) self.loaded_extensions.append(imp.load_source("", f)) log.debug(self.loaded_extensions) log.debug([dir(m) for m in self.loaded_extensions])
python
def _load_extensions(self): log.debug(u"loading all extensions : %s", self.extensions) self.loaded_extensions = [] for f in self.extensions: if not os.path.isabs(f): f = os.path.abspath(f) if not os.path.exists(f): raise CoreError(u"Extension file: {0} not found on disk".format(f)) self.loaded_extensions.append(imp.load_source("", f)) log.debug(self.loaded_extensions) log.debug([dir(m) for m in self.loaded_extensions])
[ "def", "_load_extensions", "(", "self", ")", ":", "log", ".", "debug", "(", "u\"loading all extensions : %s\"", ",", "self", ".", "extensions", ")", "self", ".", "loaded_extensions", "=", "[", "]", "for", "f", "in", "self", ".", "extensions", ":", "if", "n...
Load all extension files into the namespace pykwalify.ext
[ "Load", "all", "extension", "files", "into", "the", "namespace", "pykwalify", ".", "ext" ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/core.py#L131-L149
18,378
Grokzen/pykwalify
pykwalify/core.py
Core._handle_func
def _handle_func(self, value, rule, path, done=None): """ Helper function that should check if func is specified for this rule and then handle it for all cases in a generic way. """ func = rule.func # func keyword is not defined so nothing to do if not func: return found_method = False for extension in self.loaded_extensions: method = getattr(extension, func, None) if method: found_method = True # No exception will should be caught. If one is raised it should bubble up all the way. ret = method(value, rule, path) if ret is not True and ret is not None: msg = '%s. Path: {path}' % unicode(ret) self.errors.append(SchemaError.SchemaErrorEntry( msg=msg, path=path, value=None)) # If False or None or some other object that is interpreted as False if not ret: raise CoreError(u"Error when running extension function : {0}".format(func)) # Only run the first matched function. Sinc loading order is determined # it should be easy to determine which file is used before others break if not found_method: raise CoreError(u"Did not find method '{0}' in any loaded extension file".format(func))
python
def _handle_func(self, value, rule, path, done=None): func = rule.func # func keyword is not defined so nothing to do if not func: return found_method = False for extension in self.loaded_extensions: method = getattr(extension, func, None) if method: found_method = True # No exception will should be caught. If one is raised it should bubble up all the way. ret = method(value, rule, path) if ret is not True and ret is not None: msg = '%s. Path: {path}' % unicode(ret) self.errors.append(SchemaError.SchemaErrorEntry( msg=msg, path=path, value=None)) # If False or None or some other object that is interpreted as False if not ret: raise CoreError(u"Error when running extension function : {0}".format(func)) # Only run the first matched function. Sinc loading order is determined # it should be easy to determine which file is used before others break if not found_method: raise CoreError(u"Did not find method '{0}' in any loaded extension file".format(func))
[ "def", "_handle_func", "(", "self", ",", "value", ",", "rule", ",", "path", ",", "done", "=", "None", ")", ":", "func", "=", "rule", ".", "func", "# func keyword is not defined so nothing to do", "if", "not", "func", ":", "return", "found_method", "=", "Fals...
Helper function that should check if func is specified for this rule and then handle it for all cases in a generic way.
[ "Helper", "function", "that", "should", "check", "if", "func", "is", "specified", "for", "this", "rule", "and", "then", "handle", "it", "for", "all", "cases", "in", "a", "generic", "way", "." ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/core.py#L241-L277
18,379
Grokzen/pykwalify
pykwalify/core.py
Core._validate_range
def _validate_range(self, max_, min_, max_ex, min_ex, value, path, prefix): """ Validate that value is within range values. """ if not isinstance(value, int) and not isinstance(value, float): raise CoreError("Value must be a integer type") log.debug( u"Validate range : %s : %s : %s : %s : %s : %s", max_, min_, max_ex, min_ex, value, path, ) if max_ is not None and max_ < value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', greater than max limit '{max_}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, max_=max_)) if min_ is not None and min_ > value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', less than min limit '{min_}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, min_=min_)) if max_ex is not None and max_ex <= value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', greater than or equals to max limit(exclusive) '{max_ex}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, max_ex=max_ex)) if min_ex is not None and min_ex >= value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', less than or equals to min limit(exclusive) '{min_ex}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, min_ex=min_ex))
python
def _validate_range(self, max_, min_, max_ex, min_ex, value, path, prefix): if not isinstance(value, int) and not isinstance(value, float): raise CoreError("Value must be a integer type") log.debug( u"Validate range : %s : %s : %s : %s : %s : %s", max_, min_, max_ex, min_ex, value, path, ) if max_ is not None and max_ < value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', greater than max limit '{max_}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, max_=max_)) if min_ is not None and min_ > value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', less than min limit '{min_}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, min_=min_)) if max_ex is not None and max_ex <= value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', greater than or equals to max limit(exclusive) '{max_ex}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, max_ex=max_ex)) if min_ex is not None and min_ex >= value: self.errors.append(SchemaError.SchemaErrorEntry( msg=u"Type '{prefix}' has size of '{value}', less than or equals to min limit(exclusive) '{min_ex}'. Path: '{path}'", path=path, value=nativestr(value) if tt['str'](value) else value, prefix=prefix, min_ex=min_ex))
[ "def", "_validate_range", "(", "self", ",", "max_", ",", "min_", ",", "max_ex", ",", "min_ex", ",", "value", ",", "path", ",", "prefix", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", "and", "not", "isinstance", "(", "value", ","...
Validate that value is within range values.
[ "Validate", "that", "value", "is", "within", "range", "values", "." ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/core.py#L919-L966
18,380
Grokzen/pykwalify
pykwalify/cli.py
run
def run(cli_args): """ Split the functionality into 2 methods. One for parsing the cli and one that runs the application. """ from .core import Core c = Core( source_file=cli_args["--data-file"], schema_files=cli_args["--schema-file"], extensions=cli_args['--extension'], strict_rule_validation=cli_args['--strict-rule-validation'], fix_ruby_style_regex=cli_args['--fix-ruby-style-regex'], allow_assertions=cli_args['--allow-assertions'], file_encoding=cli_args['--encoding'], ) c.validate() return c
python
def run(cli_args): from .core import Core c = Core( source_file=cli_args["--data-file"], schema_files=cli_args["--schema-file"], extensions=cli_args['--extension'], strict_rule_validation=cli_args['--strict-rule-validation'], fix_ruby_style_regex=cli_args['--fix-ruby-style-regex'], allow_assertions=cli_args['--allow-assertions'], file_encoding=cli_args['--encoding'], ) c.validate() return c
[ "def", "run", "(", "cli_args", ")", ":", "from", ".", "core", "import", "Core", "c", "=", "Core", "(", "source_file", "=", "cli_args", "[", "\"--data-file\"", "]", ",", "schema_files", "=", "cli_args", "[", "\"--schema-file\"", "]", ",", "extensions", "=",...
Split the functionality into 2 methods. One for parsing the cli and one that runs the application.
[ "Split", "the", "functionality", "into", "2", "methods", "." ]
02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7
https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/cli.py#L68-L86
18,381
daler/gffutils
gffutils/pybedtools_integration.py
to_bedtool
def to_bedtool(iterator): """ Convert any iterator into a pybedtools.BedTool object. Note that the supplied iterator is not consumed by this function. To save to a temp file or to a known location, use the `.saveas()` method of the returned BedTool object. """ def gen(): for i in iterator: yield helpers.asinterval(i) return pybedtools.BedTool(gen())
python
def to_bedtool(iterator): def gen(): for i in iterator: yield helpers.asinterval(i) return pybedtools.BedTool(gen())
[ "def", "to_bedtool", "(", "iterator", ")", ":", "def", "gen", "(", ")", ":", "for", "i", "in", "iterator", ":", "yield", "helpers", ".", "asinterval", "(", "i", ")", "return", "pybedtools", ".", "BedTool", "(", "gen", "(", ")", ")" ]
Convert any iterator into a pybedtools.BedTool object. Note that the supplied iterator is not consumed by this function. To save to a temp file or to a known location, use the `.saveas()` method of the returned BedTool object.
[ "Convert", "any", "iterator", "into", "a", "pybedtools", ".", "BedTool", "object", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/pybedtools_integration.py#L12-L23
18,382
daler/gffutils
gffutils/pybedtools_integration.py
tsses
def tsses(db, merge_overlapping=False, attrs=None, attrs_sep=":", merge_kwargs=None, as_bed6=False, bedtools_227_or_later=True): """ Create 1-bp transcription start sites for all transcripts in the database and return as a sorted pybedtools.BedTool object pointing to a temporary file. To save the file to a known location, use the `.moveto()` method on the resulting `pybedtools.BedTool` object. To extend regions upstream/downstream, see the `.slop()` method on the resulting `pybedtools.BedTool object`. Requires pybedtools. Parameters ---------- db : gffutils.FeatureDB The database to use as_bed6 : bool If True, output file is in BED6 format; otherwise it remains in the GFF/GTF format and dialect of the file used to create the database. Note that the merge options below necessarily force `as_bed6=True`. merge_overlapping : bool If True, output will be in BED format. Overlapping TSSes will be merged into a single feature, and their names will be collapsed using `merge_sep` and placed in the new name field. merge_kwargs : dict If `merge_overlapping=True`, these keyword arguments are passed to pybedtools.BedTool.merge(), which are in turn sent to `bedtools merge`. The merge operates on a BED6 file which will have had the name field constructed as specified by other arguments here. See the available options for your installed version of BEDTools; the defaults used here are `merge_kwargs=dict(o='distinct', c=4, s=True)`. Any provided `merge_kwargs` are used to *update* the default. It is recommended to not override `c=4` and `s=True`, otherwise the post-merge fixing may not work correctly. Good candidates for tweaking are `d` (merge distance), `o` (operation), `delim` (delimiter to use for collapse operations). attrs : str or list Only has an effect when `as_bed6=True` or `merge_overlapping=True`. Determines what goes in the name field of an output BED file. By default, "gene_id" for GTF databases and "ID" for GFF. If a list of attributes is supplied, e.g. ["gene_id", "transcript_id"], then these will be joined by `attr_join_sep` and then placed in the name field. attrs_sep: str If `as_bed6=True` or `merge_overlapping=True`, then use this character to separate attributes in the name field of the output BED. If also using `merge_overlapping=True`, you'll probably want this to be different than `merge_sep` in order to parse things out later. bedtools_227_or_later : bool In version 2.27, BEDTools changed the output for merge. By default, this function expects BEDTools version 2.27 or later, but set this to False to assume the older behavior. For testing purposes, the environment variable GFFUTILS_USES_BEDTOOLS_227_OR_LATER is set to either "true" or "false" and is used to override this argument. Examples -------- >>> import gffutils >>> db = gffutils.create_db( ... gffutils.example_filename('FBgn0031208.gtf'), ... ":memory:", ... keep_order=True, ... verbose=False) Default settings -- no merging, and report a separate TSS on each line even if they overlap (as in the first two): >>> print(tsses(db)) # doctest: +NORMALIZE_WHITESPACE chr2L gffutils_derived transcript_TSS 7529 7529 . + . gene_id "FBgn0031208"; transcript_id "FBtr0300689"; chr2L gffutils_derived transcript_TSS 7529 7529 . + . gene_id "FBgn0031208"; transcript_id "FBtr0300690"; chr2L gffutils_derived transcript_TSS 11000 11000 . - . gene_id "Fk_gene_1"; transcript_id "transcript_Fk_gene_1"; chr2L gffutils_derived transcript_TSS 12500 12500 . - . gene_id "Fk_gene_2"; transcript_id "transcript_Fk_gene_2"; <BLANKLINE> Default merging, showing the first two TSSes merged and reported as a single unique TSS for the gene. Note the conversion to BED: >>> x = tsses(db, merge_overlapping=True) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208 . + chr2L 10999 11000 Fk_gene_1 . - chr2L 12499 12500 Fk_gene_2 . - <BLANKLINE> Report both gene ID and transcript ID in the name. In some cases this can be easier to parse than the original GTF or GFF file. With no merging specified, we must add `as_bed6=True` to see the names in BED format. >>> x = tsses(db, attrs=['gene_id', 'transcript_id'], as_bed6=True) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208:FBtr0300689 . + chr2L 7528 7529 FBgn0031208:FBtr0300690 . + chr2L 10999 11000 Fk_gene_1:transcript_Fk_gene_1 . - chr2L 12499 12500 Fk_gene_2:transcript_Fk_gene_2 . - <BLANKLINE> Use a 3kb merge distance so the last 2 features are merged together: >>> x = tsses(db, merge_overlapping=True, merge_kwargs=dict(d=3000)) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208 . + chr2L 10999 12500 Fk_gene_1,Fk_gene_2 . - <BLANKLINE> The set of unique TSSes for each gene, +1kb upstream and 500bp downstream: >>> x = tsses(db, merge_overlapping=True) >>> x = x.slop(l=1000, r=500, s=True, genome='dm3') >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 6528 8029 FBgn0031208 . + chr2L 10499 12000 Fk_gene_1 . - chr2L 11999 13500 Fk_gene_2 . - <BLANKLINE> """ _override = os.environ.get('GFFUTILS_USES_BEDTOOLS_227_OR_LATER', None) if _override is not None: if _override == 'true': bedtools_227_or_later = True elif _override == 'false': bedtools_227_or_later = False else: raise ValueError( "Unknown value for GFFUTILS_USES_BEDTOOLS_227_OR_LATER " "environment variable: {0}".format(_override)) if bedtools_227_or_later: _merge_kwargs = dict(o='distinct', s=True, c='4,5,6') else: _merge_kwargs = dict(o='distinct', s=True, c='4') if merge_kwargs is not None: _merge_kwargs.update(merge_kwargs) def gen(): """ Generator of pybedtools.Intervals representing TSSes. """ for gene in db.features_of_type('gene'): for transcript in db.children(gene, level=1): if transcript.strand == '-': transcript.start = transcript.stop else: transcript.stop = transcript.start transcript.featuretype = transcript.featuretype + '_TSS' yield helpers.asinterval(transcript) # GFF/GTF format x = pybedtools.BedTool(gen()).sort() # Figure out default attrs to use, depending on the original format. if attrs is None: if db.dialect['fmt'] == 'gtf': attrs = 'gene_id' else: attrs = 'ID' if merge_overlapping or as_bed6: if isinstance(attrs, six.string_types): attrs = [attrs] def to_bed(f): """ Given a pybedtools.Interval, return a new Interval with the name set according to the kwargs provided above. """ name = attrs_sep.join([f.attrs[i] for i in attrs]) return pybedtools.Interval( f.chrom, f.start, f.stop, name, str(f.score), f.strand) x = x.each(to_bed).saveas() if merge_overlapping: if bedtools_227_or_later: x = x.merge(**_merge_kwargs) else: def fix_merge(f): f = featurefuncs.extend_fields(f, 6) return pybedtools.Interval( f.chrom, f.start, f.stop, f[4], '.', f[3]) x = x.merge(**_merge_kwargs).saveas().each(fix_merge).saveas() return x
python
def tsses(db, merge_overlapping=False, attrs=None, attrs_sep=":", merge_kwargs=None, as_bed6=False, bedtools_227_or_later=True): _override = os.environ.get('GFFUTILS_USES_BEDTOOLS_227_OR_LATER', None) if _override is not None: if _override == 'true': bedtools_227_or_later = True elif _override == 'false': bedtools_227_or_later = False else: raise ValueError( "Unknown value for GFFUTILS_USES_BEDTOOLS_227_OR_LATER " "environment variable: {0}".format(_override)) if bedtools_227_or_later: _merge_kwargs = dict(o='distinct', s=True, c='4,5,6') else: _merge_kwargs = dict(o='distinct', s=True, c='4') if merge_kwargs is not None: _merge_kwargs.update(merge_kwargs) def gen(): """ Generator of pybedtools.Intervals representing TSSes. """ for gene in db.features_of_type('gene'): for transcript in db.children(gene, level=1): if transcript.strand == '-': transcript.start = transcript.stop else: transcript.stop = transcript.start transcript.featuretype = transcript.featuretype + '_TSS' yield helpers.asinterval(transcript) # GFF/GTF format x = pybedtools.BedTool(gen()).sort() # Figure out default attrs to use, depending on the original format. if attrs is None: if db.dialect['fmt'] == 'gtf': attrs = 'gene_id' else: attrs = 'ID' if merge_overlapping or as_bed6: if isinstance(attrs, six.string_types): attrs = [attrs] def to_bed(f): """ Given a pybedtools.Interval, return a new Interval with the name set according to the kwargs provided above. """ name = attrs_sep.join([f.attrs[i] for i in attrs]) return pybedtools.Interval( f.chrom, f.start, f.stop, name, str(f.score), f.strand) x = x.each(to_bed).saveas() if merge_overlapping: if bedtools_227_or_later: x = x.merge(**_merge_kwargs) else: def fix_merge(f): f = featurefuncs.extend_fields(f, 6) return pybedtools.Interval( f.chrom, f.start, f.stop, f[4], '.', f[3]) x = x.merge(**_merge_kwargs).saveas().each(fix_merge).saveas() return x
[ "def", "tsses", "(", "db", ",", "merge_overlapping", "=", "False", ",", "attrs", "=", "None", ",", "attrs_sep", "=", "\":\"", ",", "merge_kwargs", "=", "None", ",", "as_bed6", "=", "False", ",", "bedtools_227_or_later", "=", "True", ")", ":", "_override", ...
Create 1-bp transcription start sites for all transcripts in the database and return as a sorted pybedtools.BedTool object pointing to a temporary file. To save the file to a known location, use the `.moveto()` method on the resulting `pybedtools.BedTool` object. To extend regions upstream/downstream, see the `.slop()` method on the resulting `pybedtools.BedTool object`. Requires pybedtools. Parameters ---------- db : gffutils.FeatureDB The database to use as_bed6 : bool If True, output file is in BED6 format; otherwise it remains in the GFF/GTF format and dialect of the file used to create the database. Note that the merge options below necessarily force `as_bed6=True`. merge_overlapping : bool If True, output will be in BED format. Overlapping TSSes will be merged into a single feature, and their names will be collapsed using `merge_sep` and placed in the new name field. merge_kwargs : dict If `merge_overlapping=True`, these keyword arguments are passed to pybedtools.BedTool.merge(), which are in turn sent to `bedtools merge`. The merge operates on a BED6 file which will have had the name field constructed as specified by other arguments here. See the available options for your installed version of BEDTools; the defaults used here are `merge_kwargs=dict(o='distinct', c=4, s=True)`. Any provided `merge_kwargs` are used to *update* the default. It is recommended to not override `c=4` and `s=True`, otherwise the post-merge fixing may not work correctly. Good candidates for tweaking are `d` (merge distance), `o` (operation), `delim` (delimiter to use for collapse operations). attrs : str or list Only has an effect when `as_bed6=True` or `merge_overlapping=True`. Determines what goes in the name field of an output BED file. By default, "gene_id" for GTF databases and "ID" for GFF. If a list of attributes is supplied, e.g. ["gene_id", "transcript_id"], then these will be joined by `attr_join_sep` and then placed in the name field. attrs_sep: str If `as_bed6=True` or `merge_overlapping=True`, then use this character to separate attributes in the name field of the output BED. If also using `merge_overlapping=True`, you'll probably want this to be different than `merge_sep` in order to parse things out later. bedtools_227_or_later : bool In version 2.27, BEDTools changed the output for merge. By default, this function expects BEDTools version 2.27 or later, but set this to False to assume the older behavior. For testing purposes, the environment variable GFFUTILS_USES_BEDTOOLS_227_OR_LATER is set to either "true" or "false" and is used to override this argument. Examples -------- >>> import gffutils >>> db = gffutils.create_db( ... gffutils.example_filename('FBgn0031208.gtf'), ... ":memory:", ... keep_order=True, ... verbose=False) Default settings -- no merging, and report a separate TSS on each line even if they overlap (as in the first two): >>> print(tsses(db)) # doctest: +NORMALIZE_WHITESPACE chr2L gffutils_derived transcript_TSS 7529 7529 . + . gene_id "FBgn0031208"; transcript_id "FBtr0300689"; chr2L gffutils_derived transcript_TSS 7529 7529 . + . gene_id "FBgn0031208"; transcript_id "FBtr0300690"; chr2L gffutils_derived transcript_TSS 11000 11000 . - . gene_id "Fk_gene_1"; transcript_id "transcript_Fk_gene_1"; chr2L gffutils_derived transcript_TSS 12500 12500 . - . gene_id "Fk_gene_2"; transcript_id "transcript_Fk_gene_2"; <BLANKLINE> Default merging, showing the first two TSSes merged and reported as a single unique TSS for the gene. Note the conversion to BED: >>> x = tsses(db, merge_overlapping=True) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208 . + chr2L 10999 11000 Fk_gene_1 . - chr2L 12499 12500 Fk_gene_2 . - <BLANKLINE> Report both gene ID and transcript ID in the name. In some cases this can be easier to parse than the original GTF or GFF file. With no merging specified, we must add `as_bed6=True` to see the names in BED format. >>> x = tsses(db, attrs=['gene_id', 'transcript_id'], as_bed6=True) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208:FBtr0300689 . + chr2L 7528 7529 FBgn0031208:FBtr0300690 . + chr2L 10999 11000 Fk_gene_1:transcript_Fk_gene_1 . - chr2L 12499 12500 Fk_gene_2:transcript_Fk_gene_2 . - <BLANKLINE> Use a 3kb merge distance so the last 2 features are merged together: >>> x = tsses(db, merge_overlapping=True, merge_kwargs=dict(d=3000)) >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 7528 7529 FBgn0031208 . + chr2L 10999 12500 Fk_gene_1,Fk_gene_2 . - <BLANKLINE> The set of unique TSSes for each gene, +1kb upstream and 500bp downstream: >>> x = tsses(db, merge_overlapping=True) >>> x = x.slop(l=1000, r=500, s=True, genome='dm3') >>> print(x) # doctest: +NORMALIZE_WHITESPACE chr2L 6528 8029 FBgn0031208 . + chr2L 10499 12000 Fk_gene_1 . - chr2L 11999 13500 Fk_gene_2 . - <BLANKLINE>
[ "Create", "1", "-", "bp", "transcription", "start", "sites", "for", "all", "transcripts", "in", "the", "database", "and", "return", "as", "a", "sorted", "pybedtools", ".", "BedTool", "object", "pointing", "to", "a", "temporary", "file", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/pybedtools_integration.py#L26-L237
18,383
daler/gffutils
gffutils/gffwriter.py
GFFWriter.close
def close(self): """ Close the stream. Assumes stream has 'close' method. """ self.out_stream.close() # If we're asked to write in place, substitute the named # temporary file for the current file if self.in_place: shutil.move(self.temp_file.name, self.out)
python
def close(self): self.out_stream.close() # If we're asked to write in place, substitute the named # temporary file for the current file if self.in_place: shutil.move(self.temp_file.name, self.out)
[ "def", "close", "(", "self", ")", ":", "self", ".", "out_stream", ".", "close", "(", ")", "# If we're asked to write in place, substitute the named", "# temporary file for the current file", "if", "self", ".", "in_place", ":", "shutil", ".", "move", "(", "self", "."...
Close the stream. Assumes stream has 'close' method.
[ "Close", "the", "stream", ".", "Assumes", "stream", "has", "close", "method", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/gffwriter.py#L162-L170
18,384
daler/gffutils
gffutils/biopython_integration.py
to_seqfeature
def to_seqfeature(feature): """ Converts a gffutils.Feature object to a Bio.SeqFeature object. The GFF fields `source`, `score`, `seqid`, and `frame` are stored as qualifiers. GFF `attributes` are also stored as qualifiers. Parameters ---------- feature : Feature object, or string If string, assume it is a GFF or GTF-format line; otherwise just use the provided feature directly. """ if isinstance(feature, six.string_types): feature = feature_from_line(feature) qualifiers = { 'source': [feature.source], 'score': [feature.score], 'seqid': [feature.seqid], 'frame': [feature.frame], } qualifiers.update(feature.attributes) return SeqFeature( # Convert from GFF 1-based to standard Python 0-based indexing used by # BioPython FeatureLocation(feature.start - 1, feature.stop), id=feature.id, type=feature.featuretype, strand=_biopython_strand[feature.strand], qualifiers=qualifiers )
python
def to_seqfeature(feature): if isinstance(feature, six.string_types): feature = feature_from_line(feature) qualifiers = { 'source': [feature.source], 'score': [feature.score], 'seqid': [feature.seqid], 'frame': [feature.frame], } qualifiers.update(feature.attributes) return SeqFeature( # Convert from GFF 1-based to standard Python 0-based indexing used by # BioPython FeatureLocation(feature.start - 1, feature.stop), id=feature.id, type=feature.featuretype, strand=_biopython_strand[feature.strand], qualifiers=qualifiers )
[ "def", "to_seqfeature", "(", "feature", ")", ":", "if", "isinstance", "(", "feature", ",", "six", ".", "string_types", ")", ":", "feature", "=", "feature_from_line", "(", "feature", ")", "qualifiers", "=", "{", "'source'", ":", "[", "feature", ".", "source...
Converts a gffutils.Feature object to a Bio.SeqFeature object. The GFF fields `source`, `score`, `seqid`, and `frame` are stored as qualifiers. GFF `attributes` are also stored as qualifiers. Parameters ---------- feature : Feature object, or string If string, assume it is a GFF or GTF-format line; otherwise just use the provided feature directly.
[ "Converts", "a", "gffutils", ".", "Feature", "object", "to", "a", "Bio", ".", "SeqFeature", "object", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/biopython_integration.py#L21-L52
18,385
daler/gffutils
gffutils/biopython_integration.py
from_seqfeature
def from_seqfeature(s, **kwargs): """ Converts a Bio.SeqFeature object to a gffutils.Feature object. The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be stored as qualifiers. Any other qualifiers will be assumed to be GFF attributes. """ source = s.qualifiers.get('source', '.')[0] score = s.qualifiers.get('score', '.')[0] seqid = s.qualifiers.get('seqid', '.')[0] frame = s.qualifiers.get('frame', '.')[0] strand = _feature_strand[s.strand] # BioPython parses 1-based GenBank positions into 0-based for use within # Python. We need to convert back to 1-based GFF format here. start = s.location.start.position + 1 stop = s.location.end.position featuretype = s.type id = s.id attributes = dict(s.qualifiers) attributes.pop('source', '.') attributes.pop('score', '.') attributes.pop('seqid', '.') attributes.pop('frame', '.') return Feature(seqid, source, featuretype, start, stop, score, strand, frame, attributes, id=id, **kwargs)
python
def from_seqfeature(s, **kwargs): source = s.qualifiers.get('source', '.')[0] score = s.qualifiers.get('score', '.')[0] seqid = s.qualifiers.get('seqid', '.')[0] frame = s.qualifiers.get('frame', '.')[0] strand = _feature_strand[s.strand] # BioPython parses 1-based GenBank positions into 0-based for use within # Python. We need to convert back to 1-based GFF format here. start = s.location.start.position + 1 stop = s.location.end.position featuretype = s.type id = s.id attributes = dict(s.qualifiers) attributes.pop('source', '.') attributes.pop('score', '.') attributes.pop('seqid', '.') attributes.pop('frame', '.') return Feature(seqid, source, featuretype, start, stop, score, strand, frame, attributes, id=id, **kwargs)
[ "def", "from_seqfeature", "(", "s", ",", "*", "*", "kwargs", ")", ":", "source", "=", "s", ".", "qualifiers", ".", "get", "(", "'source'", ",", "'.'", ")", "[", "0", "]", "score", "=", "s", ".", "qualifiers", ".", "get", "(", "'score'", ",", "'.'...
Converts a Bio.SeqFeature object to a gffutils.Feature object. The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be stored as qualifiers. Any other qualifiers will be assumed to be GFF attributes.
[ "Converts", "a", "Bio", ".", "SeqFeature", "object", "to", "a", "gffutils", ".", "Feature", "object", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/biopython_integration.py#L55-L81
18,386
daler/gffutils
gffutils/interface.py
FeatureDB.set_pragmas
def set_pragmas(self, pragmas): """ Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full list. """ self.pragmas = pragmas c = self.conn.cursor() c.executescript( ';\n'.join( ['PRAGMA %s=%s' % i for i in self.pragmas.items()] ) ) self.conn.commit()
python
def set_pragmas(self, pragmas): self.pragmas = pragmas c = self.conn.cursor() c.executescript( ';\n'.join( ['PRAGMA %s=%s' % i for i in self.pragmas.items()] ) ) self.conn.commit()
[ "def", "set_pragmas", "(", "self", ",", "pragmas", ")", ":", "self", ".", "pragmas", "=", "pragmas", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "executescript", "(", "';\\n'", ".", "join", "(", "[", "'PRAGMA %s=%s'", "%", "i", ...
Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full list.
[ "Set", "pragmas", "for", "the", "current", "database", "connection", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L163-L180
18,387
daler/gffutils
gffutils/interface.py
FeatureDB._feature_returner
def _feature_returner(self, **kwargs): """ Returns a feature, adding additional database-specific defaults """ kwargs.setdefault('dialect', self.dialect) kwargs.setdefault('keep_order', self.keep_order) kwargs.setdefault('sort_attribute_values', self.sort_attribute_values) return Feature(**kwargs)
python
def _feature_returner(self, **kwargs): kwargs.setdefault('dialect', self.dialect) kwargs.setdefault('keep_order', self.keep_order) kwargs.setdefault('sort_attribute_values', self.sort_attribute_values) return Feature(**kwargs)
[ "def", "_feature_returner", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'dialect'", ",", "self", ".", "dialect", ")", "kwargs", ".", "setdefault", "(", "'keep_order'", ",", "self", ".", "keep_order", ")", "kwargs", ...
Returns a feature, adding additional database-specific defaults
[ "Returns", "a", "feature", "adding", "additional", "database", "-", "specific", "defaults" ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L182-L189
18,388
daler/gffutils
gffutils/interface.py
FeatureDB.schema
def schema(self): """ Returns the database schema as a string. """ c = self.conn.cursor() c.execute( ''' SELECT sql FROM sqlite_master ''') results = [] for i, in c: if i is not None: results.append(i) return '\n'.join(results)
python
def schema(self): c = self.conn.cursor() c.execute( ''' SELECT sql FROM sqlite_master ''') results = [] for i, in c: if i is not None: results.append(i) return '\n'.join(results)
[ "def", "schema", "(", "self", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "'''\n SELECT sql FROM sqlite_master\n '''", ")", "results", "=", "[", "]", "for", "i", ",", "in", "c", ":", "...
Returns the database schema as a string.
[ "Returns", "the", "database", "schema", "as", "a", "string", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L199-L212
18,389
daler/gffutils
gffutils/interface.py
FeatureDB.featuretypes
def featuretypes(self): """ Iterate over feature types found in the database. Returns ------- A generator object that yields featuretypes (as strings) """ c = self.conn.cursor() c.execute( ''' SELECT DISTINCT featuretype from features ''') for i, in c: yield i
python
def featuretypes(self): c = self.conn.cursor() c.execute( ''' SELECT DISTINCT featuretype from features ''') for i, in c: yield i
[ "def", "featuretypes", "(", "self", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "'''\n SELECT DISTINCT featuretype from features\n '''", ")", "for", "i", ",", "in", "c", ":", "yield", "i" ]
Iterate over feature types found in the database. Returns ------- A generator object that yields featuretypes (as strings)
[ "Iterate", "over", "feature", "types", "found", "in", "the", "database", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L339-L353
18,390
daler/gffutils
gffutils/interface.py
FeatureDB.execute
def execute(self, query): """ Execute arbitrary queries on the db. .. seealso:: :class:`FeatureDB.schema` may be helpful when writing your own queries. Parameters ---------- query : str Query to execute -- trailing ";" optional. Returns ------- A sqlite3.Cursor object that can be iterated over. """ c = self.conn.cursor() return c.execute(query)
python
def execute(self, query): c = self.conn.cursor() return c.execute(query)
[ "def", "execute", "(", "self", ",", "query", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "return", "c", ".", "execute", "(", "query", ")" ]
Execute arbitrary queries on the db. .. seealso:: :class:`FeatureDB.schema` may be helpful when writing your own queries. Parameters ---------- query : str Query to execute -- trailing ";" optional. Returns ------- A sqlite3.Cursor object that can be iterated over.
[ "Execute", "arbitrary", "queries", "on", "the", "db", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L440-L461
18,391
daler/gffutils
gffutils/interface.py
FeatureDB.interfeatures
def interfeatures(self, features, new_featuretype=None, merge_attributes=True, dialect=None, attribute_func=None, update_attributes=None): """ Construct new features representing the space between features. For example, if `features` is a list of exons, then this method will return the introns. If `features` is a list of genes, then this method will return the intergenic regions. Providing N features will return N - 1 new features. This method purposefully does *not* do any merging or sorting of coordinates, so you may want to use :meth:`FeatureDB.merge` first, or when selecting features use the `order_by` kwarg, e.g., `db.features_of_type('gene', order_by=('seqid', 'start'))`. Parameters ---------- features : iterable of :class:`feature.Feature` instances Sorted, merged iterable new_featuretype : string or None The new features will all be of this type, or, if None (default) then the featuretypes will be constructed from the neighboring features, e.g., `inter_exon_exon`. merge_attributes : bool If True, new features' attributes will be a merge of the neighboring features' attributes. This is useful if you have provided a list of exons; the introns will then retain the transcript and/or gene parents as a single item. Otherwise, if False, the attribute will be a comma-separated list of values, potentially listing the same gene ID twice. attribute_func : callable or None If None, then nothing special is done to the attributes. If callable, then the callable accepts two attribute dictionaries and returns a single attribute dictionary. If `merge_attributes` is True, then `attribute_func` is called before `merge_attributes`. This could be useful for manually managing IDs for the new features. update_attributes : dict After attributes have been modified and merged, this dictionary can be used to replace parts of the attributes dictionary. Returns ------- A generator that yields :class:`Feature` objects """ for i, f in enumerate(features): # no inter-feature for the first one if i == 0: interfeature_start = f.stop last_feature = f continue interfeature_stop = f.start if new_featuretype is None: new_featuretype = 'inter_%s_%s' % ( last_feature.featuretype, f.featuretype) if last_feature.strand != f.strand: new_strand = '.' else: new_strand = f.strand if last_feature.chrom != f.chrom: # We've moved to a new chromosome. For example, if we're # getting intergenic regions from all genes, they will be on # different chromosomes. We still assume sorted features, but # don't complain if they're on different chromosomes -- just # move on. last_feature = f continue strand = new_strand chrom = last_feature.chrom # Shrink interfeature_start += 1 interfeature_stop -= 1 if merge_attributes: new_attributes = helpers.merge_attributes( last_feature.attributes, f.attributes) else: new_attributes = {} if update_attributes: new_attributes.update(update_attributes) new_bin = bins.bins( interfeature_start, interfeature_stop, one=True) _id = None fields = dict( seqid=chrom, source='gffutils_derived', featuretype=new_featuretype, start=interfeature_start, end=interfeature_stop, score='.', strand=strand, frame='.', attributes=new_attributes, bin=new_bin) if dialect is None: # Support for @classmethod -- if calling from the class, then # self.dialect is not defined, so defer to Feature's default # (which will be constants.dialect, or GFF3). try: dialect = self.dialect except AttributeError: dialect = None yield self._feature_returner(**fields) interfeature_start = f.stop
python
def interfeatures(self, features, new_featuretype=None, merge_attributes=True, dialect=None, attribute_func=None, update_attributes=None): for i, f in enumerate(features): # no inter-feature for the first one if i == 0: interfeature_start = f.stop last_feature = f continue interfeature_stop = f.start if new_featuretype is None: new_featuretype = 'inter_%s_%s' % ( last_feature.featuretype, f.featuretype) if last_feature.strand != f.strand: new_strand = '.' else: new_strand = f.strand if last_feature.chrom != f.chrom: # We've moved to a new chromosome. For example, if we're # getting intergenic regions from all genes, they will be on # different chromosomes. We still assume sorted features, but # don't complain if they're on different chromosomes -- just # move on. last_feature = f continue strand = new_strand chrom = last_feature.chrom # Shrink interfeature_start += 1 interfeature_stop -= 1 if merge_attributes: new_attributes = helpers.merge_attributes( last_feature.attributes, f.attributes) else: new_attributes = {} if update_attributes: new_attributes.update(update_attributes) new_bin = bins.bins( interfeature_start, interfeature_stop, one=True) _id = None fields = dict( seqid=chrom, source='gffutils_derived', featuretype=new_featuretype, start=interfeature_start, end=interfeature_stop, score='.', strand=strand, frame='.', attributes=new_attributes, bin=new_bin) if dialect is None: # Support for @classmethod -- if calling from the class, then # self.dialect is not defined, so defer to Feature's default # (which will be constants.dialect, or GFF3). try: dialect = self.dialect except AttributeError: dialect = None yield self._feature_returner(**fields) interfeature_start = f.stop
[ "def", "interfeatures", "(", "self", ",", "features", ",", "new_featuretype", "=", "None", ",", "merge_attributes", "=", "True", ",", "dialect", "=", "None", ",", "attribute_func", "=", "None", ",", "update_attributes", "=", "None", ")", ":", "for", "i", "...
Construct new features representing the space between features. For example, if `features` is a list of exons, then this method will return the introns. If `features` is a list of genes, then this method will return the intergenic regions. Providing N features will return N - 1 new features. This method purposefully does *not* do any merging or sorting of coordinates, so you may want to use :meth:`FeatureDB.merge` first, or when selecting features use the `order_by` kwarg, e.g., `db.features_of_type('gene', order_by=('seqid', 'start'))`. Parameters ---------- features : iterable of :class:`feature.Feature` instances Sorted, merged iterable new_featuretype : string or None The new features will all be of this type, or, if None (default) then the featuretypes will be constructed from the neighboring features, e.g., `inter_exon_exon`. merge_attributes : bool If True, new features' attributes will be a merge of the neighboring features' attributes. This is useful if you have provided a list of exons; the introns will then retain the transcript and/or gene parents as a single item. Otherwise, if False, the attribute will be a comma-separated list of values, potentially listing the same gene ID twice. attribute_func : callable or None If None, then nothing special is done to the attributes. If callable, then the callable accepts two attribute dictionaries and returns a single attribute dictionary. If `merge_attributes` is True, then `attribute_func` is called before `merge_attributes`. This could be useful for manually managing IDs for the new features. update_attributes : dict After attributes have been modified and merged, this dictionary can be used to replace parts of the attributes dictionary. Returns ------- A generator that yields :class:`Feature` objects
[ "Construct", "new", "features", "representing", "the", "space", "between", "features", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L650-L766
18,392
daler/gffutils
gffutils/interface.py
FeatureDB.update
def update(self, data, make_backup=True, **kwargs): """ Update database with features in `data`. data : str, iterable, FeatureDB instance If FeatureDB, all data will be used. If string, assume it's a filename of a GFF or GTF file. Otherwise, assume it's an iterable of Feature objects. The classes in gffutils.iterators may be helpful in this case. make_backup : bool If True, and the database you're about to update is a file on disk, makes a copy of the existing database and saves it with a .bak extension. Notes ----- Other kwargs are used in the same way as in gffutils.create_db; see the help for that function for details. Returns ------- FeatureDB with updated features. """ from gffutils import create from gffutils import iterators if make_backup: if isinstance(self.dbfn, six.string_types): shutil.copy2(self.dbfn, self.dbfn + '.bak') # get iterator-specific kwargs _iterator_kwargs = {} for k, v in kwargs.items(): if k in constants._iterator_kwargs: _iterator_kwargs[k] = v # Handle all sorts of input data = iterators.DataIterator(data, **_iterator_kwargs) if self.dialect['fmt'] == 'gtf': if 'id_spec' not in kwargs: kwargs['id_spec'] = { 'gene': 'gene_id', 'transcript': 'transcript_id'} db = create._GTFDBCreator( data=data, dbfn=self.dbfn, dialect=self.dialect, **kwargs) elif self.dialect['fmt'] == 'gff3': if 'id_spec' not in kwargs: kwargs['id_spec'] = 'ID' db = create._GFFDBCreator( data=data, dbfn=self.dbfn, dialect=self.dialect, **kwargs) else: raise ValueError db._populate_from_lines(data) db._update_relations() db._finalize() return db
python
def update(self, data, make_backup=True, **kwargs): from gffutils import create from gffutils import iterators if make_backup: if isinstance(self.dbfn, six.string_types): shutil.copy2(self.dbfn, self.dbfn + '.bak') # get iterator-specific kwargs _iterator_kwargs = {} for k, v in kwargs.items(): if k in constants._iterator_kwargs: _iterator_kwargs[k] = v # Handle all sorts of input data = iterators.DataIterator(data, **_iterator_kwargs) if self.dialect['fmt'] == 'gtf': if 'id_spec' not in kwargs: kwargs['id_spec'] = { 'gene': 'gene_id', 'transcript': 'transcript_id'} db = create._GTFDBCreator( data=data, dbfn=self.dbfn, dialect=self.dialect, **kwargs) elif self.dialect['fmt'] == 'gff3': if 'id_spec' not in kwargs: kwargs['id_spec'] = 'ID' db = create._GFFDBCreator( data=data, dbfn=self.dbfn, dialect=self.dialect, **kwargs) else: raise ValueError db._populate_from_lines(data) db._update_relations() db._finalize() return db
[ "def", "update", "(", "self", ",", "data", ",", "make_backup", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "gffutils", "import", "create", "from", "gffutils", "import", "iterators", "if", "make_backup", ":", "if", "isinstance", "(", "self", "...
Update database with features in `data`. data : str, iterable, FeatureDB instance If FeatureDB, all data will be used. If string, assume it's a filename of a GFF or GTF file. Otherwise, assume it's an iterable of Feature objects. The classes in gffutils.iterators may be helpful in this case. make_backup : bool If True, and the database you're about to update is a file on disk, makes a copy of the existing database and saves it with a .bak extension. Notes ----- Other kwargs are used in the same way as in gffutils.create_db; see the help for that function for details. Returns ------- FeatureDB with updated features.
[ "Update", "database", "with", "features", "in", "data", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L814-L871
18,393
daler/gffutils
gffutils/interface.py
FeatureDB.create_introns
def create_introns(self, exon_featuretype='exon', grandparent_featuretype='gene', parent_featuretype=None, new_featuretype='intron', merge_attributes=True): """ Create introns from existing annotations. Parameters ---------- exon_featuretype : string Feature type to use in order to infer introns. Typically `"exon"`. grandparent_featuretype : string If `grandparent_featuretype` is not None, then group exons by children of this featuretype. If `granparent_featuretype` is "gene" (default), then introns will be created for all first-level children of genes. This may include mRNA, rRNA, ncRNA, etc. If you only want to infer introns from one of these featuretypes (e.g., mRNA), then use the `parent_featuretype` kwarg which is mutually exclusive with `grandparent_featuretype`. parent_featuretype : string If `parent_featuretype` is not None, then only use this featuretype to infer introns. Use this if you only want a subset of featuretypes to have introns (e.g., "mRNA" only, and not ncRNA or rRNA). Mutually exclusive with `grandparent_featuretype`. new_featuretype : string Feature type to use for the inferred introns; default is `"intron"`. merge_attributes : bool Whether or not to merge attributes from all exons. If False then no attributes will be created for the introns. Returns ------- A generator object that yields :class:`Feature` objects representing new introns Notes ----- The returned generator can be passed directly to the :meth:`FeatureDB.update` method to permanently add them to the database, e.g., :: db.update(db.create_introns()) """ if (grandparent_featuretype and parent_featuretype) or ( grandparent_featuretype is None and parent_featuretype is None ): raise ValueError("exactly one of `grandparent_featuretype` or " "`parent_featuretype` should be provided") if grandparent_featuretype: def child_gen(): for gene in self.features_of_type(grandparent_featuretype): for child in self.children(gene, level=1): yield child elif parent_featuretype: def child_gen(): for child in self.features_of_type(parent_featuretype): yield child for child in child_gen(): exons = self.children(child, level=1, featuretype=exon_featuretype, order_by='start') for intron in self.interfeatures( exons, new_featuretype=new_featuretype, merge_attributes=merge_attributes, dialect=self.dialect ): yield intron
python
def create_introns(self, exon_featuretype='exon', grandparent_featuretype='gene', parent_featuretype=None, new_featuretype='intron', merge_attributes=True): if (grandparent_featuretype and parent_featuretype) or ( grandparent_featuretype is None and parent_featuretype is None ): raise ValueError("exactly one of `grandparent_featuretype` or " "`parent_featuretype` should be provided") if grandparent_featuretype: def child_gen(): for gene in self.features_of_type(grandparent_featuretype): for child in self.children(gene, level=1): yield child elif parent_featuretype: def child_gen(): for child in self.features_of_type(parent_featuretype): yield child for child in child_gen(): exons = self.children(child, level=1, featuretype=exon_featuretype, order_by='start') for intron in self.interfeatures( exons, new_featuretype=new_featuretype, merge_attributes=merge_attributes, dialect=self.dialect ): yield intron
[ "def", "create_introns", "(", "self", ",", "exon_featuretype", "=", "'exon'", ",", "grandparent_featuretype", "=", "'gene'", ",", "parent_featuretype", "=", "None", ",", "new_featuretype", "=", "'intron'", ",", "merge_attributes", "=", "True", ")", ":", "if", "(...
Create introns from existing annotations. Parameters ---------- exon_featuretype : string Feature type to use in order to infer introns. Typically `"exon"`. grandparent_featuretype : string If `grandparent_featuretype` is not None, then group exons by children of this featuretype. If `granparent_featuretype` is "gene" (default), then introns will be created for all first-level children of genes. This may include mRNA, rRNA, ncRNA, etc. If you only want to infer introns from one of these featuretypes (e.g., mRNA), then use the `parent_featuretype` kwarg which is mutually exclusive with `grandparent_featuretype`. parent_featuretype : string If `parent_featuretype` is not None, then only use this featuretype to infer introns. Use this if you only want a subset of featuretypes to have introns (e.g., "mRNA" only, and not ncRNA or rRNA). Mutually exclusive with `grandparent_featuretype`. new_featuretype : string Feature type to use for the inferred introns; default is `"intron"`. merge_attributes : bool Whether or not to merge attributes from all exons. If False then no attributes will be created for the introns. Returns ------- A generator object that yields :class:`Feature` objects representing new introns Notes ----- The returned generator can be passed directly to the :meth:`FeatureDB.update` method to permanently add them to the database, e.g., :: db.update(db.create_introns())
[ "Create", "introns", "from", "existing", "annotations", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L945-L1017
18,394
daler/gffutils
gffutils/interface.py
FeatureDB.merge
def merge(self, features, ignore_strand=False): """ Merge overlapping features together. Parameters ---------- features : iterator of Feature instances ignore_strand : bool If True, features on multiple strands will be merged, and the final strand will be set to '.'. Otherwise, ValueError will be raised if trying to merge features on differnt strands. Returns ------- A generator object that yields :class:`Feature` objects representing the newly merged features. """ # Consume iterator up front... features = list(features) if len(features) == 0: raise StopIteration # Either set all strands to '+' or check for strand-consistency. if ignore_strand: strand = '.' else: strands = [i.strand for i in features] if len(set(strands)) > 1: raise ValueError('Specify ignore_strand=True to force merging ' 'of multiple strands') strand = strands[0] # Sanity check to make sure all features are from the same chromosome. chroms = [i.chrom for i in features] if len(set(chroms)) > 1: raise NotImplementedError('Merging multiple chromosomes not ' 'implemented') chrom = chroms[0] # To start, we create a merged feature of just the first feature. current_merged_start = features[0].start current_merged_stop = features[0].stop # We don't need to check the first one, so start at feature #2. for feature in features[1:]: # Does this feature start within the currently merged feature?... if feature.start <= current_merged_stop + 1: # ...It starts within, so leave current_merged_start where it # is. Does it extend any farther? if feature.stop >= current_merged_stop: # Extends further, so set a new stop position current_merged_stop = feature.stop else: # If feature.stop < current_merged_stop, it's completely # within the previous feature. Nothing more to do. continue else: # The start position is outside the merged feature, so we're # done with the current merged feature. Prepare for output... merged_feature = dict( seqid=feature.chrom, source='.', featuretype=feature.featuretype, start=current_merged_start, end=current_merged_stop, score='.', strand=strand, frame='.', attributes='') yield self._feature_returner(**merged_feature) # and we start a new one, initializing with this feature's # start and stop. current_merged_start = feature.start current_merged_stop = feature.stop # need to yield the last one. if len(features) == 1: feature = features[0] merged_feature = dict( seqid=feature.chrom, source='.', featuretype=feature.featuretype, start=current_merged_start, end=current_merged_stop, score='.', strand=strand, frame='.', attributes='') yield self._feature_returner(**merged_feature)
python
def merge(self, features, ignore_strand=False): # Consume iterator up front... features = list(features) if len(features) == 0: raise StopIteration # Either set all strands to '+' or check for strand-consistency. if ignore_strand: strand = '.' else: strands = [i.strand for i in features] if len(set(strands)) > 1: raise ValueError('Specify ignore_strand=True to force merging ' 'of multiple strands') strand = strands[0] # Sanity check to make sure all features are from the same chromosome. chroms = [i.chrom for i in features] if len(set(chroms)) > 1: raise NotImplementedError('Merging multiple chromosomes not ' 'implemented') chrom = chroms[0] # To start, we create a merged feature of just the first feature. current_merged_start = features[0].start current_merged_stop = features[0].stop # We don't need to check the first one, so start at feature #2. for feature in features[1:]: # Does this feature start within the currently merged feature?... if feature.start <= current_merged_stop + 1: # ...It starts within, so leave current_merged_start where it # is. Does it extend any farther? if feature.stop >= current_merged_stop: # Extends further, so set a new stop position current_merged_stop = feature.stop else: # If feature.stop < current_merged_stop, it's completely # within the previous feature. Nothing more to do. continue else: # The start position is outside the merged feature, so we're # done with the current merged feature. Prepare for output... merged_feature = dict( seqid=feature.chrom, source='.', featuretype=feature.featuretype, start=current_merged_start, end=current_merged_stop, score='.', strand=strand, frame='.', attributes='') yield self._feature_returner(**merged_feature) # and we start a new one, initializing with this feature's # start and stop. current_merged_start = feature.start current_merged_stop = feature.stop # need to yield the last one. if len(features) == 1: feature = features[0] merged_feature = dict( seqid=feature.chrom, source='.', featuretype=feature.featuretype, start=current_merged_start, end=current_merged_stop, score='.', strand=strand, frame='.', attributes='') yield self._feature_returner(**merged_feature)
[ "def", "merge", "(", "self", ",", "features", ",", "ignore_strand", "=", "False", ")", ":", "# Consume iterator up front...", "features", "=", "list", "(", "features", ")", "if", "len", "(", "features", ")", "==", "0", ":", "raise", "StopIteration", "# Eithe...
Merge overlapping features together. Parameters ---------- features : iterator of Feature instances ignore_strand : bool If True, features on multiple strands will be merged, and the final strand will be set to '.'. Otherwise, ValueError will be raised if trying to merge features on differnt strands. Returns ------- A generator object that yields :class:`Feature` objects representing the newly merged features.
[ "Merge", "overlapping", "features", "together", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L1019-L1112
18,395
daler/gffutils
gffutils/interface.py
FeatureDB.children_bp
def children_bp(self, feature, child_featuretype='exon', merge=False, ignore_strand=False): """ Total bp of all children of a featuretype. Useful for getting the exonic bp of an mRNA. Parameters ---------- feature : str or Feature instance child_featuretype : str Which featuretype to consider. For example, to get exonic bp of an mRNA, use `child_featuretype='exon'`. merge : bool Whether or not to merge child features together before summing them. ignore_strand : bool If True, then overlapping features on different strands will be merged together; otherwise, merging features with different strands will result in a ValueError. Returns ------- Integer representing the total number of bp. """ children = self.children(feature, featuretype=child_featuretype, order_by='start') if merge: children = self.merge(children, ignore_strand=ignore_strand) total = 0 for child in children: total += len(child) return total
python
def children_bp(self, feature, child_featuretype='exon', merge=False, ignore_strand=False): children = self.children(feature, featuretype=child_featuretype, order_by='start') if merge: children = self.merge(children, ignore_strand=ignore_strand) total = 0 for child in children: total += len(child) return total
[ "def", "children_bp", "(", "self", ",", "feature", ",", "child_featuretype", "=", "'exon'", ",", "merge", "=", "False", ",", "ignore_strand", "=", "False", ")", ":", "children", "=", "self", ".", "children", "(", "feature", ",", "featuretype", "=", "child_...
Total bp of all children of a featuretype. Useful for getting the exonic bp of an mRNA. Parameters ---------- feature : str or Feature instance child_featuretype : str Which featuretype to consider. For example, to get exonic bp of an mRNA, use `child_featuretype='exon'`. merge : bool Whether or not to merge child features together before summing them. ignore_strand : bool If True, then overlapping features on different strands will be merged together; otherwise, merging features with different strands will result in a ValueError. Returns ------- Integer representing the total number of bp.
[ "Total", "bp", "of", "all", "children", "of", "a", "featuretype", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L1114-L1152
18,396
daler/gffutils
gffutils/interface.py
FeatureDB.bed12
def bed12(self, feature, block_featuretype=['exon'], thick_featuretype=['CDS'], thin_featuretype=None, name_field='ID', color=None): """ Converts `feature` into a BED12 format. GFF and GTF files do not necessarily define genes consistently, so this method provides flexiblity in specifying what to call a "transcript". Parameters ---------- feature : str or Feature instance In most cases, this feature should be a transcript rather than a gene. block_featuretype : str or list Which featuretype to use as the exons. These are represented as blocks in the BED12 format. Typically 'exon'. Use the `thick_featuretype` and `thin_featuretype` arguments to control the display of CDS as thicker blocks and UTRs as thinner blocks. Note that the features for `thick` or `thin` are *not* automatically included in the blocks; if you do want them included, then those featuretypes should be added to this `block_features` list. If no child features of type `block_featuretype` are found, then the full `feature` is returned in BED12 format as if it had a single exon. thick_featuretype : str or list Child featuretype(s) to use in order to determine the boundaries of the "thick" blocks. In BED12 format, these represent coding sequences; typically this would be set to "CDS". This argument is mutually exclusive with `thin_featuretype`. Specifically, the BED12 thickStart will be the start coord of the first `thick` item and the thickEnd will be the stop coord of the last `thick` item. thin_featuretype : str or list Child featuretype(s) to use in order to determine the boundaries of the "thin" blocks. In BED12 format, these represent untranslated regions. Typically "utr" or ['three_prime_UTR', 'five_prime_UTR']. Mutually exclusive with `thick_featuretype`. Specifically, the BED12 thickStart field will be the stop coord of the first `thin` item and the thickEnd field will be the start coord of the last `thin` item. name_field : str Which attribute of `feature` to use as the feature's name. If this field is not present, a "." placeholder will be used instead. color : None or str If None, then use black (0,0,0) as the RGB color; otherwise this should be a comma-separated string of R,G,B values each of which are integers in the range 0-255. """ if thick_featuretype and thin_featuretype: raise ValueError("Can only specify one of `thick_featuertype` or " "`thin_featuretype`") exons = list(self.children(feature, featuretype=block_featuretype, order_by='start')) if len(exons) == 0: exons = [feature] feature = self[feature] first = exons[0].start last = exons[-1].stop if first != feature.start: raise ValueError( "Start of first exon (%s) does not match start of feature (%s)" % (first, feature.start)) if last != feature.stop: raise ValueError( "End of last exon (%s) does not match end of feature (%s)" % (last, feature.stop)) if color is None: color = '0,0,0' color = color.replace(' ', '').strip() # Use field names as defined at # http://genome.ucsc.edu/FAQ/FAQformat.html#format1 chrom = feature.chrom chromStart = feature.start - 1 chromEnd = feature.stop orig = constants.always_return_list constants.always_return_list = True try: name = feature[name_field][0] except KeyError: name = "." constants.always_return_list = orig score = feature.score if score == '.': score = '0' strand = feature.strand itemRgb = color blockCount = len(exons) blockSizes = [len(i) for i in exons] blockStarts = [i.start - 1 - chromStart for i in exons] if thick_featuretype: thick = list(self.children(feature, featuretype=thick_featuretype, order_by='start')) if len(thick) == 0: thickStart = feature.start thickEnd = feature.stop else: thickStart = thick[0].start - 1 # BED 0-based coords thickEnd = thick[-1].stop if thin_featuretype: thin = list(self.children(feature, featuretype=thin_featuretype, order_by='start')) if len(thin) == 0: thickStart = feature.start thickEnd = feature.stop else: thickStart = thin[0].stop thickEnd = thin[-1].start - 1 # BED 0-based coords tst = chromStart + blockStarts[-1] + blockSizes[-1] assert tst == chromEnd, "tst=%s; chromEnd=%s" % (tst, chromEnd) fields = [ chrom, chromStart, chromEnd, name, score, strand, thickStart, thickEnd, itemRgb, blockCount, ','.join(map(str, blockSizes)), ','.join(map(str, blockStarts))] return '\t'.join(map(str, fields))
python
def bed12(self, feature, block_featuretype=['exon'], thick_featuretype=['CDS'], thin_featuretype=None, name_field='ID', color=None): if thick_featuretype and thin_featuretype: raise ValueError("Can only specify one of `thick_featuertype` or " "`thin_featuretype`") exons = list(self.children(feature, featuretype=block_featuretype, order_by='start')) if len(exons) == 0: exons = [feature] feature = self[feature] first = exons[0].start last = exons[-1].stop if first != feature.start: raise ValueError( "Start of first exon (%s) does not match start of feature (%s)" % (first, feature.start)) if last != feature.stop: raise ValueError( "End of last exon (%s) does not match end of feature (%s)" % (last, feature.stop)) if color is None: color = '0,0,0' color = color.replace(' ', '').strip() # Use field names as defined at # http://genome.ucsc.edu/FAQ/FAQformat.html#format1 chrom = feature.chrom chromStart = feature.start - 1 chromEnd = feature.stop orig = constants.always_return_list constants.always_return_list = True try: name = feature[name_field][0] except KeyError: name = "." constants.always_return_list = orig score = feature.score if score == '.': score = '0' strand = feature.strand itemRgb = color blockCount = len(exons) blockSizes = [len(i) for i in exons] blockStarts = [i.start - 1 - chromStart for i in exons] if thick_featuretype: thick = list(self.children(feature, featuretype=thick_featuretype, order_by='start')) if len(thick) == 0: thickStart = feature.start thickEnd = feature.stop else: thickStart = thick[0].start - 1 # BED 0-based coords thickEnd = thick[-1].stop if thin_featuretype: thin = list(self.children(feature, featuretype=thin_featuretype, order_by='start')) if len(thin) == 0: thickStart = feature.start thickEnd = feature.stop else: thickStart = thin[0].stop thickEnd = thin[-1].start - 1 # BED 0-based coords tst = chromStart + blockStarts[-1] + blockSizes[-1] assert tst == chromEnd, "tst=%s; chromEnd=%s" % (tst, chromEnd) fields = [ chrom, chromStart, chromEnd, name, score, strand, thickStart, thickEnd, itemRgb, blockCount, ','.join(map(str, blockSizes)), ','.join(map(str, blockStarts))] return '\t'.join(map(str, fields))
[ "def", "bed12", "(", "self", ",", "feature", ",", "block_featuretype", "=", "[", "'exon'", "]", ",", "thick_featuretype", "=", "[", "'CDS'", "]", ",", "thin_featuretype", "=", "None", ",", "name_field", "=", "'ID'", ",", "color", "=", "None", ")", ":", ...
Converts `feature` into a BED12 format. GFF and GTF files do not necessarily define genes consistently, so this method provides flexiblity in specifying what to call a "transcript". Parameters ---------- feature : str or Feature instance In most cases, this feature should be a transcript rather than a gene. block_featuretype : str or list Which featuretype to use as the exons. These are represented as blocks in the BED12 format. Typically 'exon'. Use the `thick_featuretype` and `thin_featuretype` arguments to control the display of CDS as thicker blocks and UTRs as thinner blocks. Note that the features for `thick` or `thin` are *not* automatically included in the blocks; if you do want them included, then those featuretypes should be added to this `block_features` list. If no child features of type `block_featuretype` are found, then the full `feature` is returned in BED12 format as if it had a single exon. thick_featuretype : str or list Child featuretype(s) to use in order to determine the boundaries of the "thick" blocks. In BED12 format, these represent coding sequences; typically this would be set to "CDS". This argument is mutually exclusive with `thin_featuretype`. Specifically, the BED12 thickStart will be the start coord of the first `thick` item and the thickEnd will be the stop coord of the last `thick` item. thin_featuretype : str or list Child featuretype(s) to use in order to determine the boundaries of the "thin" blocks. In BED12 format, these represent untranslated regions. Typically "utr" or ['three_prime_UTR', 'five_prime_UTR']. Mutually exclusive with `thick_featuretype`. Specifically, the BED12 thickStart field will be the stop coord of the first `thin` item and the thickEnd field will be the start coord of the last `thin` item. name_field : str Which attribute of `feature` to use as the feature's name. If this field is not present, a "." placeholder will be used instead. color : None or str If None, then use black (0,0,0) as the RGB color; otherwise this should be a comma-separated string of R,G,B values each of which are integers in the range 0-255.
[ "Converts", "feature", "into", "a", "BED12", "format", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L1154-L1299
18,397
daler/gffutils
gffutils/iterators.py
DataIterator
def DataIterator(data, checklines=10, transform=None, force_dialect_check=False, from_string=False, **kwargs): """ Iterate over features, no matter how they are provided. Parameters ---------- data : str, iterable of Feature objs, FeatureDB `data` can be a string (filename, URL, or contents of a file, if from_string=True), any arbitrary iterable of features, or a FeatureDB (in which case its all_features() method will be called). checklines : int Number of lines to check in order to infer a dialect. transform : None or callable If not None, `transform` should accept a Feature object as its only argument and return either a (possibly modified) Feature object or a value that evaluates to False. If the return value is False, the feature will be skipped. force_dialect_check : bool If True, check the dialect of every feature. Thorough, but can be slow. from_string : bool If True, `data` should be interpreted as the contents of a file rather than the filename itself. dialect : None or dict Provide the dialect, which will override auto-detected dialects. If provided, you should probably also use `force_dialect_check=False` and `checklines=0` but this is not enforced. """ _kwargs = dict(data=data, checklines=checklines, transform=transform, force_dialect_check=force_dialect_check, **kwargs) if isinstance(data, six.string_types): if from_string: return _StringIterator(**_kwargs) else: if os.path.exists(data): return _FileIterator(**_kwargs) elif is_url(data): return _UrlIterator(**_kwargs) elif isinstance(data, FeatureDB): _kwargs['data'] = data.all_features() return _FeatureIterator(**_kwargs) else: return _FeatureIterator(**_kwargs)
python
def DataIterator(data, checklines=10, transform=None, force_dialect_check=False, from_string=False, **kwargs): _kwargs = dict(data=data, checklines=checklines, transform=transform, force_dialect_check=force_dialect_check, **kwargs) if isinstance(data, six.string_types): if from_string: return _StringIterator(**_kwargs) else: if os.path.exists(data): return _FileIterator(**_kwargs) elif is_url(data): return _UrlIterator(**_kwargs) elif isinstance(data, FeatureDB): _kwargs['data'] = data.all_features() return _FeatureIterator(**_kwargs) else: return _FeatureIterator(**_kwargs)
[ "def", "DataIterator", "(", "data", ",", "checklines", "=", "10", ",", "transform", "=", "None", ",", "force_dialect_check", "=", "False", ",", "from_string", "=", "False", ",", "*", "*", "kwargs", ")", ":", "_kwargs", "=", "dict", "(", "data", "=", "d...
Iterate over features, no matter how they are provided. Parameters ---------- data : str, iterable of Feature objs, FeatureDB `data` can be a string (filename, URL, or contents of a file, if from_string=True), any arbitrary iterable of features, or a FeatureDB (in which case its all_features() method will be called). checklines : int Number of lines to check in order to infer a dialect. transform : None or callable If not None, `transform` should accept a Feature object as its only argument and return either a (possibly modified) Feature object or a value that evaluates to False. If the return value is False, the feature will be skipped. force_dialect_check : bool If True, check the dialect of every feature. Thorough, but can be slow. from_string : bool If True, `data` should be interpreted as the contents of a file rather than the filename itself. dialect : None or dict Provide the dialect, which will override auto-detected dialects. If provided, you should probably also use `force_dialect_check=False` and `checklines=0` but this is not enforced.
[ "Iterate", "over", "features", "no", "matter", "how", "they", "are", "provided", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/iterators.py#L229-L279
18,398
daler/gffutils
gffutils/inspect.py
inspect
def inspect(data, look_for=['featuretype', 'chrom', 'attribute_keys', 'feature_count'], limit=None, verbose=True): """ Inspect a GFF or GTF data source. This function is useful for figuring out the different featuretypes found in a file (for potential removal before creating a FeatureDB). Returns a dictionary with a key for each item in `look_for` and a corresponding value that is a dictionary of how many of each unique item were found. There will always be a `feature_count` key, indicating how many features were looked at (if `limit` is provided, then `feature_count` will be the same as `limit`). For example, if `look_for` is ['chrom', 'featuretype'], then the result will be a dictionary like:: { 'chrom': { 'chr1': 500, 'chr2': 435, 'chr3': 200, ... ... }. 'featuretype': { 'gene': 150, 'exon': 324, ... }, 'feature_count': 5000 } Parameters ---------- data : str, FeatureDB instance, or iterator of Features If `data` is a string, assume it's a GFF or GTF filename. If it's a FeatureDB instance, then its `all_features()` method will be automatically called. Otherwise, assume it's an iterable of Feature objects. look_for : list List of things to keep track of. Options are: - any attribute of a Feature object, such as chrom, source, start, stop, strand. - "attribute_keys", which will look at all the individual attribute keys of each feature limit : int Number of features to look at. Default is no limit. verbose : bool Report how many features have been processed. Returns ------- dict """ results = {} obj_attrs = [] for i in look_for: if i not in ['attribute_keys', 'feature_count']: obj_attrs.append(i) results[i] = Counter() attr_keys = 'attribute_keys' in look_for d = iterators.DataIterator(data) feature_count = 0 for f in d: if verbose: sys.stderr.write('\r%s features inspected' % feature_count) sys.stderr.flush() for obj_attr in obj_attrs: results[obj_attr].update([getattr(f, obj_attr)]) if attr_keys: results['attribute_keys'].update(f.attributes.keys()) feature_count += 1 if limit and feature_count == limit: break new_results = {} for k, v in results.items(): new_results[k] = dict(v) new_results['feature_count'] = feature_count return new_results
python
def inspect(data, look_for=['featuretype', 'chrom', 'attribute_keys', 'feature_count'], limit=None, verbose=True): results = {} obj_attrs = [] for i in look_for: if i not in ['attribute_keys', 'feature_count']: obj_attrs.append(i) results[i] = Counter() attr_keys = 'attribute_keys' in look_for d = iterators.DataIterator(data) feature_count = 0 for f in d: if verbose: sys.stderr.write('\r%s features inspected' % feature_count) sys.stderr.flush() for obj_attr in obj_attrs: results[obj_attr].update([getattr(f, obj_attr)]) if attr_keys: results['attribute_keys'].update(f.attributes.keys()) feature_count += 1 if limit and feature_count == limit: break new_results = {} for k, v in results.items(): new_results[k] = dict(v) new_results['feature_count'] = feature_count return new_results
[ "def", "inspect", "(", "data", ",", "look_for", "=", "[", "'featuretype'", ",", "'chrom'", ",", "'attribute_keys'", ",", "'feature_count'", "]", ",", "limit", "=", "None", ",", "verbose", "=", "True", ")", ":", "results", "=", "{", "}", "obj_attrs", "=",...
Inspect a GFF or GTF data source. This function is useful for figuring out the different featuretypes found in a file (for potential removal before creating a FeatureDB). Returns a dictionary with a key for each item in `look_for` and a corresponding value that is a dictionary of how many of each unique item were found. There will always be a `feature_count` key, indicating how many features were looked at (if `limit` is provided, then `feature_count` will be the same as `limit`). For example, if `look_for` is ['chrom', 'featuretype'], then the result will be a dictionary like:: { 'chrom': { 'chr1': 500, 'chr2': 435, 'chr3': 200, ... ... }. 'featuretype': { 'gene': 150, 'exon': 324, ... }, 'feature_count': 5000 } Parameters ---------- data : str, FeatureDB instance, or iterator of Features If `data` is a string, assume it's a GFF or GTF filename. If it's a FeatureDB instance, then its `all_features()` method will be automatically called. Otherwise, assume it's an iterable of Feature objects. look_for : list List of things to keep track of. Options are: - any attribute of a Feature object, such as chrom, source, start, stop, strand. - "attribute_keys", which will look at all the individual attribute keys of each feature limit : int Number of features to look at. Default is no limit. verbose : bool Report how many features have been processed. Returns ------- dict
[ "Inspect", "a", "GFF", "or", "GTF", "data", "source", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/inspect.py#L7-L105
18,399
daler/gffutils
gffutils/scripts/gffutils-flybase-convert.py
clean_gff
def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None, featuretypes_to_ignore=None): """ Cleans a GFF file by removing features on unwanted chromosomes and of unwanted featuretypes. Optionally adds "chr" to chrom names. """ logger.info("Cleaning GFF") chroms_to_ignore = chroms_to_ignore or [] featuretypes_to_ignore = featuretypes_to_ignore or [] with open(cleaned, 'w') as fout: for i in gffutils.iterators.DataIterator(gff): if add_chr: i.chrom = "chr" + i.chrom if i.chrom in chroms_to_ignore: continue if i.featuretype in featuretypes_to_ignore: continue fout.write(str(i) + '\n') return cleaned
python
def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None, featuretypes_to_ignore=None): logger.info("Cleaning GFF") chroms_to_ignore = chroms_to_ignore or [] featuretypes_to_ignore = featuretypes_to_ignore or [] with open(cleaned, 'w') as fout: for i in gffutils.iterators.DataIterator(gff): if add_chr: i.chrom = "chr" + i.chrom if i.chrom in chroms_to_ignore: continue if i.featuretype in featuretypes_to_ignore: continue fout.write(str(i) + '\n') return cleaned
[ "def", "clean_gff", "(", "gff", ",", "cleaned", ",", "add_chr", "=", "False", ",", "chroms_to_ignore", "=", "None", ",", "featuretypes_to_ignore", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Cleaning GFF\"", ")", "chroms_to_ignore", "=", "chroms_to_i...
Cleans a GFF file by removing features on unwanted chromosomes and of unwanted featuretypes. Optionally adds "chr" to chrom names.
[ "Cleans", "a", "GFF", "file", "by", "removing", "features", "on", "unwanted", "chromosomes", "and", "of", "unwanted", "featuretypes", ".", "Optionally", "adds", "chr", "to", "chrom", "names", "." ]
6f7f547cad898738a1bd0a999fd68ba68db2c524
https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/scripts/gffutils-flybase-convert.py#L25-L45