Best Python code snippet using tempest_python
Baseline-Analyzer.py
Source:Baseline-Analyzer.py  
1import os2import re3import subprocess4import section24, section_5_and_9, section6, section78, section10125import argparse6import shutil7from argparse import RawTextHelpFormatter8'''9Will either run or print the command given based on the remedy flag10'''11def commandRun(command):12    if remedy:13        os.system('{} >/dev/null 2>&1'.format(command))14    else:15        print('Run Command: {}'.format(command))16        print()17'''18Section 1: Planning and Installation19'''20def section1():21    print("### Start of Section 1 ###\n")22    ## Section 1.1 Ensure the Pre-Installation Planning Checklist Has Been Implemented23    print("Ensure the Pre-Installation Planning Checklist in Section 1.1 of the CIS Apache 2.4 Benchmark has been implemented.\n")24    25    ## Section 1.2 Ensure the Server Is Not a Multi-Use System26    ret = subprocess.run("systemctl list-units --all --type=service --no-pager | grep -w active | grep running > active_running_services.txt", capture_output=True, shell=True)27    active_running_output = ret.stdout.decode()28    print("All active and running services are saved to active_running_services.txt. Disable or uninstall unneeded services.\n")29    if remedy:30        disable_service = ""31        while not disable_service == "y" and not disable_service == "n":32            disable_service = input("Disable service(s)? (Y/N) ").rstrip().lower()33            if disable_service == "y":34                services_to_disable = input("Enter service(s) to disable (separated by comma): ")35                services_to_disable_list = services_to_disable.split(",")36                for service in services_to_disable_list:37                    service = service.strip().replace("\n", "")38                    ret2= subprocess.run("systemctl stop " + service, capture_output=True, shell=True)39                    ret3 = subprocess.run("systemctl disable " + service, capture_output=True, shell=True)40                    if ret2.returncode!=0:41                        print("Failed to stop " + service)42                    43                    if ret3.returncode!=0:44                        print("Failed to disable " + service)45            elif disable_service == "n" :46                print("No services will be disabled.\n")47                48            else:49                continue50    ## Section 1.3  Ensure Apache Is Installed From the Appropriate Binaries51    print("Ensure that Apache is installed with \'apt-get install apache2\', instead of downloading and installing custom Apache binaries.")52    print("\n### End of Section 1 ###")53'''54Pre-requisites checks:551. Check if root.562. Check if Apache is installed.573. Check if Apache is running.58'''59def prereq_check():60    # id -u checks for user id. 0 means root, non-zero means normal user.61    command = "id -u"62    ret = subprocess.run(command, capture_output=True, shell=True)63    user_id = int(ret.stdout.decode())64    if user_id != 0:65        print("Root required. Please run as root!")66        exit(-1)67    else:68        install_apache = ""69        ret = subprocess.run("apachectl", capture_output=True, shell=True)70        apachectl_error_code = ret.returncode71        # If Apache is not installed.72        if apachectl_error_code!=1:73            while not install_apache == "y" and not install_apache == "n":74                install_apache = input("Apache is not installed. Install Apache? (Y/N) ").rstrip().lower()75                if install_apache == "y":76                    print("Installing Apache...\n")77                    subprocess.run("apt-get install apache2 -y >/dev/null 2>&1", shell=True)78                    79                elif install_apache == "n":80                    print("Apache will not be installed.")81                    print("Script Terminated.")82                    exit(-1)83                    84                else:85                    continue86        # If Apache is installed, check if Apache is running.87        else:88            print("Apache is installed.")89            run_apache = ""90            91            ret = subprocess.run("systemctl is-active --quiet apache2 >/dev/null 2>&1", capture_output=True, shell=True)92            apache2_error_code = ret.returncode93            94            # If Apache is not running, prompt user to run Apache.95            if apache2_error_code!=0:96                while not run_apache == "y" and not run_apache == "n":97                    run_apache = input("Apache is not running. Start Apache? (Y/N) ").rstrip().lower()98                    if run_apache == "y":99                        print("Starting Apache...\n")100                        subprocess.run("service apache2 start", shell=True)101                        102                    elif run_apache == "n":103                        print("Apache will not be started.")104                        print("Script Terminated.")105                        exit(-1)106                        107                    else:108                        continue109            else:110                print("Apache is running.\n")111    dirs = os.listdir('conf')112    if len(dirs):113        print('Config files found in conf folder! Removing files...\n')114        shutil.rmtree('conf')115        os.mkdir('conf')116if __name__ == '__main__':117    toolDesc = ('Web Baseline Analyzer.\n' +118                'This tool is a targeted web server auditing and hardening tool based on the CIS Apache 2.4 Benchmark.')119    parser = argparse.ArgumentParser(description=toolDesc, formatter_class=RawTextHelpFormatter)120    group = parser.add_mutually_exclusive_group()121    parser.add_argument('-r', action='store_true', help='Run script with this option to automatically perform remedies')122    group.add_argument('-e', action='extend', nargs='+', type=int, metavar=(1, 2), help='Enter list of sections to perform audit (E.g. 3 5 6)')123    group.add_argument('-d', action='extend', nargs='+', type=int, metavar=(1, 2), help='Enter list of sections to skip audit (E.g. 3 5 6)')124    args = parser.parse_args()125    remedy = args.r126    sectionsAudit = {1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12}127    if args.e:128        sectionsAudit = args.e129    elif args.d:130        sectionsAudit -= set(args.d)131    prereq_check()132    # Goal: Determine web server configuration dir133    webSerDir = r'/etc/apache2'134    if not os.path.isdir(webSerDir):135        webSerDir = input('Enter Configuration Folder Location: ')136    137    apacheConfFile = '{}/apache2.conf'.format(webSerDir)138    if not os.path.isfile(apacheConfFile):139        apacheConfFile = input('Enter Main Configuration File Location: ')140    # Get Apache Environment Variables141    envVarPath = '{}/envvars'.format(webSerDir)142    while not os.path.isfile(envVarPath):143        envVarPath = input('Enter path to environment variable file: ')144    145    envVars = [i.split('export ')[1].split('=') for i in os.popen('cat {} | grep export'.format(envVarPath)).read().split('\n') if i and i[0] != '#']146    varDict = {}147    for var in envVars:148        if len(var) == 2:149            varDict[var[0]] = var[1]150    for section in list(sectionsAudit):151        if section == 1:152            section1()153        elif section == 2:154            modCheck, modules = section24.section2Audit()155            section24.section2Analyze(modCheck, modules, remedy)156        elif section == 3:157            section24.section3Audit(apacheConfFile, varDict, webSerDir, remedy)158        elif section == 4:159            section24.section4Audit(apacheConfFile, webSerDir, remedy)160        elif section == 5:161            print("### Start of Section 5 ###\n")162            section_5_and_9.section_5_methods()163            print("\n### End of Section 5 ###")164        elif section == 6:165            section6.section6Audit(webSerDir, apacheConfFile, varDict, remedy)166        elif section == 7:167            print("### Start of Section 7 ###\n")168            section78.fullSect7Audit(remedy)169            print("\n### End of Section 7 ###")170        elif section == 8:171            print("### Start of Section 8 ###\n")172            section78.fullSect8Audit(apacheConfFile, remedy)173            print("\n### End of Section 8 ###")174        elif section == 9:175            print("### Start of Section 9 ###\n")176            section_5_and_9.section_9_methods()177            print("\n### End of Section 9 ###")178        elif section == 10:179            section1012.section10(apacheConfFile, remedy)180        elif section == 11:181            section1012.section11(remedy)182        elif section == 12:183            section1012.section12(remedy)184    185    # Reload apache2 server if remedy were automatically ran186    if remedy:187        print('Reloading apache2 to apply changes')188        commandRun('service apache2 reload')189    else:190        dirs = os.listdir('conf')191        if len(dirs):192            print('Updated config files can be found in the conf folder')193            print('Replace the originals with these to apply changes')...gcp_apis.py
Source:gcp_apis.py  
1#     Copyright 2021 Dynatrace LLC2#3#     Licensed under the Apache License, Version 2.0 (the "License");4#     you may not use this file except in compliance with the License.5#     You may obtain a copy of the License at6#7#         http://www.apache.org/licenses/LICENSE-2.08#9#     Unless required by applicable law or agreed to in writing, software10#     distributed under the License is distributed on an "AS IS" BASIS,11#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12#     See the License for the specific language governing permissions and13#     limitations under the License.14from aiohttp import ClientResponseError15from lib.context import MetricsContext16GCP_SERVICE_USAGE_URL = "https://serviceusage.googleapis.com/v1/projects/"17async def get_all_disabled_apis(context: MetricsContext, project_id: str):18    base_url = f"{GCP_SERVICE_USAGE_URL}{project_id}/services?filter=state:DISABLED"19    headers = context.create_gcp_request_headers(project_id)20    disabled_apis = set()21    try:22        response = await context.gcp_session.get(base_url, headers=headers, raise_for_status=True)23        disabled_services_json = await response.json()24        disabled_services = disabled_services_json.get("services", [])25        disabled_apis.update({disable_service.get("config", {}).get("name", "") for disable_service in disabled_services})26        while disabled_services_json.get("nextPageToken"):27            url = f"{base_url}&pageToken={disabled_services_json['nextPageToken']}"28            response = await context.gcp_session.get(url, headers=headers, raise_for_status=True)29            disabled_services_json = await response.json()30            disabled_services = disabled_services_json.get("services", [])31            disabled_apis.update({disable_service.get("config", {}).get("name", "") for disable_service in disabled_services})32        return disabled_apis33    except ClientResponseError as e:34        context.log(project_id, f'Disabled APIs call returned failed status code. {e}')35        return disabled_apis36    except Exception as e:37        context.log(project_id, f'Cannot get disabled APIs: {GCP_SERVICE_USAGE_URL}/projects/{project_id}/services?filter=state:DISABLED. {e}')...context_processors.py
Source:context_processors.py  
1from.models import *2def categories_processor(request):3    config = WebsiteConfiguration.objects.all().first()4    # config = ""5    net = Network.objects.all()6    checkbank = Disable_Service.objects.get(service="Bankpayment").disable7    monnifybank = Disable_Service.objects.get(service="Monnfy bank").disable8    monnifyATM = Disable_Service.objects.get(service="Monnify ATM").disable9    paystack = Disable_Service.objects.get(service="paystack").disable10    aircash = Disable_Service.objects.get( service="Airtime_Funding").disable...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!!
