Best Python code snippet using avocado_python
container_manager.py
Source:container_manager.py  
...47    global _CONTAINER_LOCATION48    global _CONTAINER_MOUNT49    return util.silent_execute([50        "veracrypt", "--text", "--list", _CONTAINER_LOCATION51    ]) == 0 and util.is_dir_mounted(_CONTAINER_MOUNT)52def lock_container():53    global _CONTAINER_MOUNT54    global _ENCRYPTED_HOME_FOLDERS55    global _ENCRYPTED_SWAP_LOCATION56    global _CONTAINER_LOCATION57    global _ORIGINAL_SWAP_TMP58    # Check if the user is not root.59    if os.geteuid() != 0:60        util.eprint("The utility must be running as root!")61        return 162    # Check if the container is not mounted.63    if not _is_container_mounted():64        print("Container is not mounted!")65        return 066    # Dismount all encrypted users' home folders, killing all their running processes.67    if os.path.exists(_ENCRYPTED_HOME_FOLDERS):68        for user in os.listdir(_ENCRYPTED_HOME_FOLDERS):69            if util.is_dir_mounted("/home/" + user):70                util.kill_all_processes_owning_a_folder("/home/" + user)71                ret = util.silent_execute([72                    "umount", "/home/" + user73                ])74                if ret:75                    util.eprint(76                        "Could not unmount {user}'s encrypted home folder!".format(user=user))77                if util.is_dir_mounted("/home/" + user):78                    ret = util.silent_execute([79                        "umount", "-l", "/home/" + user80                    ])81                    if ret:82                        util.eprint(83                            "Could not lazy unmount {user}'s encrypted home folder!".format(user=user))84                        return ret85    util.kill_all_processes_owning_a_folder(_CONTAINER_MOUNT)86    # Swap off the encrypted swap image, and restore the original swap images.87    if os.path.exists(_ENCRYPTED_SWAP_LOCATION):88        util.silent_execute([89            "swapon", _ENCRYPTED_SWAP_LOCATION90        ])91        ret = util.silent_execute([92            "swapoff", _ENCRYPTED_SWAP_LOCATION93        ])94        if ret:95            util.eprint("Could not swap off the encrypted swap file!")96            return ret97    if os.path.exists(_ORIGINAL_SWAP_TMP):98        with open(_ORIGINAL_SWAP_TMP, "r") as fd:99            original_swap_text = fd.read().strip()100            original_swaps = original_swap_text.split(os.linesep)101            for swap in original_swaps:102                if swap.strip():103                    util.silent_execute([104                        "swapoff", swap.strip()105                    ])106                    ret = util.silent_execute([107                        "swapon", swap.strip()108                    ])109                    if ret:110                        util.eprint("Could not swap on {swap}!".format(111                            swap=swap.strip()))112                        return ret113    # Lock the container.114    ret = util.silent_execute([115        "veracrypt", "--text", "--dismount", _CONTAINER_LOCATION116    ])117    if ret:118        util.eprint("Could not lock the container!")119        return ret120    return 0121def unlock_container(password):122    global _CONTAINER_LOCATION123    global _CONTAINER_MOUNT124    global _ENCRYPTED_HOME_FOLDERS125    global _ENCRYPTED_SWAP_LOCATION126    global _HOME_ENCRYPTION_UTIL_TMP_LOCATION127    global _ORIGINAL_SWAP_TMP128    # Check if the user is not root.129    if os.geteuid() != 0:130        util.eprint("The utility must be running as root!")131        return 1132    # Check if the container is mounted.133    if _is_container_mounted():134        print("Container is mounted already!")135        return 0136    # Make sure the container is truly dismounted from VeraCrypt.137    util.silent_execute([138        "veracrypt", "--text", "--dismount", _CONTAINER_LOCATION139    ])140    # Unlock the container.141    original_proc_visibility = _hide_proc()142    while not original_proc_visibility:143        util.eprint("Could not hide root processes! Trying again...")144        time.sleep(2)145        original_proc_visibility = _hide_proc()146    try:147        os.makedirs(_CONTAINER_MOUNT, exist_ok=True)148    except OSError:149        util.eprint("Could not create the countainer's mount point folder!")150        while not _restore_proc_visibility(original_proc_visibility):151            util.eprint(152                "Could not restore root processes visibility! Trying again...")153            time.sleep(2)154        return 1155    ret = util.silent_execute([156        "veracrypt", "--text", "--password", password, "--non-interactive",157        _CONTAINER_LOCATION, _CONTAINER_MOUNT158    ])159    if ret:160        util.eprint("Could not unlock the container!")161        while not _restore_proc_visibility(original_proc_visibility):162            util.eprint(163                "Could not restore root processes visibility! Trying again...")164            time.sleep(2)165        return ret166    while not _restore_proc_visibility(original_proc_visibility):167        util.eprint(168            "Could not restore root processes visibility! Trying again...")169        time.sleep(2)170    # Record and swap off the current swap images/partitions,171    # and use the encrypted swap instead.172    try:173        os.makedirs(_HOME_ENCRYPTION_UTIL_TMP_LOCATION, exist_ok=True)174    except OSError:175        util.eprint("Could not create the utility's temporary folder!")176        return 1177    with open(_ORIGINAL_SWAP_TMP, "w") as fd:178        original_swap_text = None179        try:180            original_swap_text = subprocess.check_output([181                "swapon", "--show=name", "--noheadings"182            ]).decode("UTF-8").strip()183        except subprocess.CalledProcessError:184            util.eprint("Could not get the original swap locations!")185            return 1186        original_swaps = original_swap_text.split(os.linesep)187        fd.write(original_swap_text)188        for swap in original_swaps:189            if swap.strip():190                util.silent_execute([191                    "swapon", swap.strip()192                ])193                ret = util.silent_execute([194                    "swapoff", swap.strip()195                ])196                if ret:197                    util.eprint("Could not swap off {swap}!".format(198                        swap=swap.strip()))199                    return ret200    if os.path.exists(_ENCRYPTED_SWAP_LOCATION):201        util.silent_execute([202            "swapoff", _ENCRYPTED_SWAP_LOCATION203        ])204        ret = util.silent_execute([205            "swapon", _ENCRYPTED_SWAP_LOCATION206        ])207        if ret:208            util.eprint("Could not swap on the encrypted swap file!")209            return ret210    # Run the looper Python process as root on the container directory to disallow211    # non-root users from dismounting the container.212    subprocess.Popen([213        sys.executable, os.path.join(os.path.dirname(__file__), "looper.py")214    ], start_new_session=True)215    # Mount all encrypted users.216    if os.path.exists(_ENCRYPTED_HOME_FOLDERS):217        for user in os.listdir(_ENCRYPTED_HOME_FOLDERS):218            try:219                os.makedirs("/home/" + user, exist_ok=True)220            except OSError:221                util.eprint(222                    "Could not create {user}'s home folder's encryption mount point!".format(user=user))223                return 1224            ret = util.silent_execute([225                "mount", "--bind", os.path.join(_ENCRYPTED_HOME_FOLDERS,226                                                user), "/home/" + user227            ])228            if ret:229                util.eprint(230                    "Could not mount {user}'s encrypted home folder!".format(user=user))231                return ret232    return 0233def encrypt_user(user, password):234    global _ENCRYPTED_HOME_FOLDERS235    # Check if the user is not root.236    if os.geteuid() != 0:237        util.eprint("The utility must be running as root!")238        return 1239    # Store the original lock/unlock state.240    is_container_mounted_check = _is_container_mounted()241    # Unlock the container.242    ret = unlock_container(password)243    if ret:244        util.eprint("Could not unlock the encrypted container!")245        return ret246    # Check if the user is already encrypted.247    if os.path.exists(os.path.join(_ENCRYPTED_HOME_FOLDERS, user)):248        print("User is already encrypted!")249        # Restore the original lock/unlock state, and if the original250        # lock/unlock state is unlocked, mount the user's encrypted home folder.251        if not is_container_mounted_check:252            ret = lock_container()253            if ret:254                util.eprint("Could not lock the container again!")255                return ret256        else:257            os.makedirs("/home/" + user, exist_ok=True)258            ret = util.silent_execute([259                "mount", "--bind", os.path.join(_ENCRYPTED_HOME_FOLDERS,260                                                user), "/home/" + user261            ])262            if ret:263                util.eprint(264                    "Could not mount {user}'s encrypted home folder!".format(user=user))265                return ret266        return 0267    util.kill_all_processes_owning_a_folder("/home/" + user)268    ret = util.silent_execute([269        "rm", "-rf",270        os.path.join(_ENCRYPTED_HOME_FOLDERS, user)271    ])272    if ret:273        util.eprint(274            "Could not delete {user}'s empty folder inside the encrypted container!".format(user=user))275        return ret276    try:277        os.makedirs(_ENCRYPTED_HOME_FOLDERS, exist_ok=True)278    except OSError:279        util.eprint(280            "Could not create the main home folder inside the encrypted container!")281        return 1282    ret = util.silent_execute([283        "mv",284        "/home/" + user,285        os.path.join(_ENCRYPTED_HOME_FOLDERS, user)286    ])287    if ret:288        util.eprint(289            "Could not move {user}'s home folder inside the encrypted container!".format(user=user))290        return ret291    # Restore the original lock/unlock state, and if the original292    # lock/unlock state is unlocked, mount the user's encrypted home folder.293    if not is_container_mounted_check:294        # Lock the container.295        ret = lock_container()296        if ret:297            util.eprint("Could not lock the encrypted container again!")298            return ret299    else:300        try:301            os.makedirs("/home/" + user, exist_ok=True)302        except OSError:303            util.eprint(304                "Could not create {user}'s home folder's encryption mount point!".format(user=user))305            return 1306        ret = util.silent_execute([307            "mount", "--bind", os.path.join(_ENCRYPTED_HOME_FOLDERS,308                                            user), "/home/" + user309        ])310        if ret:311            util.eprint(312                "Could not mount {user}'s encrypted home folder!".format(user=user))313            return ret314    return 0315def decrypt_user(user, password):316    global _ENCRYPTED_HOME_FOLDERS317    # Check if the user is not root.318    if os.geteuid() != 0:319        util.eprint("The utility must be running as root!")320        return 1321    # Store the original lock/unlock state.322    is_container_mounted_check = _is_container_mounted()323    # Unlock the container.324    ret = unlock_container(password)325    if ret:326        util.eprint("Could not unlock the encrypted container!")327        return ret328    # Check if the user is not encrypted.329    if not os.path.exists(os.path.join(_ENCRYPTED_HOME_FOLDERS, user)):330        print("User is not encrypted!")331        # Restore the original lock/unlock state.332        if not is_container_mounted_check:333            ret = lock_container()334            if ret:335                util.eprint("Could not lock the encrypted container again!")336                return ret337        return 0338    # Unmount the user's encrypted home folder.339    if util.is_dir_mounted("/home/" + user):340        util.kill_all_processes_owning_a_folder("/home/" + user)341        ret = util.silent_execute([342            "umount", "/home/" + user343        ])344        if ret:345            util.eprint(346                "Could not unmount {user}'s encrypted home folder!".format(user=user))347        if util.is_dir_mounted("/home/" + user):348            ret = util.silent_execute([349                "umount", "-l", "/home/" + user350            ])351            if ret:352                util.eprint(353                    "Could not lazy unmount {user}'s encrypted home folder!".format(user=user))354                return ret355    # Delete the folder that exists in the main system home folder, and356    # move the user's home folder outside the encrypted container into the main system home folder.357    ret = util.silent_execute([358        "rm", "-rf",359        "/home/" + user360    ])361    if ret:362        util.eprint(363            "Could not delete {user}'s encrypted home folder mount point!".format(user=user))364        return ret365    try:366        os.makedirs("/home", exist_ok=True)367    except OSError:368        util.eprint("Could not create the main system home folder!")369        return 1370    ret = util.silent_execute([371        "mv",372        os.path.join(_ENCRYPTED_HOME_FOLDERS, user),373        "/home/" + user374    ])375    if ret:376        util.eprint(377            "Could not move {user}'s home folder back into the main system home folder!".format(user=user))378        return ret379    # Restore the original lock/unlock state.380    if not is_container_mounted_check:381        ret = lock_container()382        if ret:383            util.eprint("Could not lock the encrypted container again!")384            return ret385    return 0386def decrypt_all_users(password):387    global _ENCRYPTED_HOME_FOLDERS388    # Check if the user is not root.389    if os.geteuid() != 0:390        util.eprint("The utility must be running as root!")391        return 1392    # Do the same as "decrypt_user", but for all users inside the encrypted container.393    # Store the original lock/unlock state.394    is_container_mounted_check = _is_container_mounted()395    # Unlock the container.396    ret = unlock_container(password)397    if ret:398        util.eprint("Could not unlock the encrypted container!")399        return ret400    if os.path.exists(_ENCRYPTED_HOME_FOLDERS):401        for user in os.listdir(_ENCRYPTED_HOME_FOLDERS):402            # Unmount the user's encrypted home folder.403            if util.is_dir_mounted("/home/" + user):404                util.kill_all_processes_owning_a_folder("/home/" + user)405                ret = util.silent_execute([406                    "umount", "/home/" + user407                ])408                if ret:409                    util.eprint(410                        "Could not unmount {user}'s encrypted home folder!".format(user=user))411                if util.is_dir_mounted("/home/" + user):412                    ret = util.silent_execute([413                        "umount", "-l", "/home/" + user414                    ])415                    if ret:416                        util.eprint(417                            "Could not lazy unmount {user}'s encrypted home folder!".format(user=user))418                        return ret419            # Delete the folder that exists in the main system home folder, and420            # move the user's home folder outside the encrypted container into the main system home folder.421            ret = util.silent_execute([422                "rm", "-rf",423                "/home/" + user424            ])425            if ret:...drives.py
Source:drives.py  
...7        s.udev = pyudev.Context()8        s.mnt = mnt9    def mount(s, dev, path):10        try:11            if s.mnt.is_dir_mounted(path):12                path += "_{0}".format(int(time.time()))13            r=subprocess.check_output(["mkdir", "-p", path], stderr=subprocess.STDOUT, shell=False)14            r=subprocess.check_output(["mount", dev, path, "-o", "rw"], stderr=subprocess.STDOUT, shell=False)15            return True16        except subprocess.CalledProcessError as e:17            print(e)18            return False19    def unmount(s, dev):20        try:21            if s.mnt.is_dev_mounted(dev):22                r=subprocess.check_output(["umount", dev], stderr=subprocess.STDOUT, shell=False)23            return True24        except subprocess.CalledProcessError as e:25            print(e)...mount.py
Source:mount.py  
...31        return (len(r) > 0)32    def get_dev_mounts(s, d):33        r = [m['Path'] for m in s.mounts if m['Device'] == d]34        return r35    def is_dir_mounted(s, d):36        r = [m for m in s.mounts if m['Path'] == d]37        return (len(r) > 0)38    def dev_contains_rootfs(s, d):39        r = [m['Path'] for m in s.mounts if d in m['Device']]40        if '/' in r:41            return True...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!!
