Best Python code snippet using selene_python
store.py
Source:store.py
...163 def script(self):164 """Script which generates dispatcher for this definition (str)."""165 return self._script166 @property167 def script_result(self):168 """Name of the output of :attr:`script` in its namespace (str)."""169 return self._script_result170class VDispatchStore(VLockable):171 """A :mod:`sqlite3` based store for dispatcher and service definitions.172 :param filename: filename of store173 :type filename: str174 :raises: :exc:`exceptions.IOError`175 The store can be used for persisting definitions of :term:`VRI`176 path services and sub-path dispatchers which should be resolved by177 a :class:`versile.manager.dispatch.VDispatcher`\ . This is useful178 e.g. for initializing a dispatcher for a service which is179 automatically started by a booting system.180 """181 def __init__(self, filename):...
main.py
Source:main.py
1import logging2import importlib3import inspect4from datetime import datetime5from typing import Dict6import bcrypt7from flask import abort, session, current_app8from pyscriptdeck._version import VERSION9from pyscriptdeck.config import getconfig10from pyscriptdeck.common import ScriptDeck, global_config11from pyscriptdeck.dao import UserDao, ExecutionHistory, ExecutionHistoryDao, ParameterDao12EXECUTION_HISTORY_LIMIT = 1013logger = logging.getLogger(__name__)14class Main:15 def __init__(self):16 self._config = {}17 self._scripts = {}18 self._load_config()19 self._load_modules()20 def _load_config(self):21 self._config = getconfig()22 global_config.update(self._config)23 logger.info("config loaded")24 def _load_modules(self):25 self._scripts = {}26 for module_name in self._config["app.script.modules"]:27 module = importlib.import_module(module_name)28 self._load_module(module)29 def _load_module(self, module):30 scripts_count = 031 for attribute_name in dir(module):32 if (33 not attribute_name.startswith("__")34 and inspect.isclass(getattr(module, attribute_name))35 and issubclass(getattr(module, attribute_name), ScriptDeck)36 and not inspect.isabstract(getattr(module, attribute_name))37 ):38 script_instance = getattr(module, attribute_name)()39 self._scripts[script_instance.get_id()] = script_instance40 logger.info("%s discovered", attribute_name)41 scripts_count += 142 logger.info("'%s' module loaded (%d scripts)", module.__name__, scripts_count)43 def is_script_exist(self, script_id: str):44 return script_id in self._scripts45 def get_scripts_descriptions(self):46 if current_app.config["ENV"] == "development":47 self._load_modules()48 logger.info("Get scripts descriptions")49 scripts = list(map(lambda script: script.get_full_description(), self._scripts.values()))50 scripts.sort(key=lambda script: script["id"])51 return scripts52 def get_script_info(self, script_id: str):53 logger.info("Get script info for %s", script_id)54 script_info = self._scripts[script_id].get_full_description()55 script_info["executions"] = self.get_script_executions(script_id)56 return script_info57 def get_script_executions(self, script_id: str):58 logger.info("Get script executions for %s", script_id)59 return list(map(lambda exec: exec.dict(), ExecutionHistoryDao.findall_by_script_id( \60 script_id, EXECUTION_HISTORY_LIMIT)))61 def run_script(self, script_id: str, data_input: Dict):62 try:63 script_result = self._scripts[script_id].run(data_input).dict()64 except Exception as exception:65 logger.exception("Error while running the script %s", script_id)66 script_result = {}67 script_result["success"] = False68 script_result["message"] = getattr(exception, 'message', repr(exception))69 script_result["runAt"] = datetime.now().timestamp()70 user_id = self.get_current_user_id()71 execution_history = ExecutionHistory(72 script_id=script_id,73 run_at=datetime.now(),74 executed_by_id=user_id,75 execution_success=script_result["success"],76 execution_message=script_result["message"]77 )78 ExecutionHistoryDao.insert(execution_history)79 logger.info("Script %s run with the status %s", script_id, script_result["success"])80 return script_result81 def get_executions(self):82 logger.info("Get executions")83 return list(map(lambda exec: exec.dict(), ExecutionHistoryDao.findall()))84 def get_groups(self):85 logger.info("Get groups")86 groups = list(set(map(lambda script: script["group"], self.get_scripts_descriptions())))87 groups.sort()88 return groups89 def get_current_user_id(self):90 if "user" not in session:91 abort(403, "cannot get current user_id with session")92 user = UserDao.find_by_username(session["user"])93 return user.id94 def login(self, username: str, password: str):95 user = UserDao.find_by_username(username)96 if user is None:97 logger.info("User '%s' not found", username)98 return False99 login = bcrypt.checkpw(password.encode(), user.password)100 logger.info("Login attempt for %s and the result is %s", username, login)101 return login102 def get_status(self):103 return {104 "status": ParameterDao.find_by_id("general.status").value,105 "currentDate": datetime.now().timestamp(),106 "coreVersion": VERSION,107 "appVersion": self._config["app.version"]...
nmapssh.py
Source:nmapssh.py
1#!/usr/bin/python32# Python3 wrapper for nmap 3# Written by Jason Testart4# March 20205import subprocess6import shlex7import os8import uuid9import xmltodict10# Set the location of nmap here11NMAP_PATH='/usr/bin/nmap'12# Method: scan13# given options for nmap, call nmap and fetch XML14# Return a dict respresentation of the XML15def scan(options):16 my_dict = None17 dev_null = open(os.devnull, 'wb')18 tmpfile_name = f'/tmp/nmapsslpy_{uuid.uuid4().hex[0:6]}.xml'19 testssl_cmd = f"{NMAP_PATH} -oX {tmpfile_name} -Pn {options}"20 args = shlex.split(testssl_cmd)21 testssl_result = subprocess.run(args, stdout=dev_null, stderr=dev_null)22 if not testssl_result.returncode:23 with open(tmpfile_name, 'r') as tmpfile:24 data = tmpfile.read()25 my_dict = xmltodict.parse(data)26 if os.path.exists(tmpfile_name):27 os.remove(tmpfile_name)28 return my_dict29# Run nmap with the "ssh-auth-methods" NSE script.30# NOTE: The scan is intrusive!31def get_auth_methods(host,port):32 options = f"--script ssh-auth-methods -p {port} {host}"33 xmldict = scan(options)34 port_result = xmldict['nmaprun']['host']['ports']['port']35 if not 'script' in port_result.keys():36 return None37 script_result = xmldict['nmaprun']['host']['ports']['port']['script']['table']['elem']38 methods = []39 if isinstance(script_result, list):40 for method in script_result:41 methods.append(method)42 else:43 methods.append(script_result)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!