def mount(*args, **kwargs): ''' Convenience function for sh.mount. ''' try: sh.mount(*args, **kwargs) except Exception as exc: log.debug(exc) raise
def mount_dir(src, tgt): try: mount("-t", "ext4", src, tgt) except Exception as ex: msg = (_('exception is : %s'), six.text_type(ex)) LOG.error(msg) raise exception.HPEPluginMountException(reason=msg) return True
def mount(device, target): if not target: raise NameError('Mounting requires a target directory') try: sh.mount(device.device_node, target) except sh.ErrorReturnCode: print('Mounting ' + device.device_node + ' failed.')
def MountCrypt(self, filepath): container = self.containers[filepath] self.logger.info('Mounting encrypted container [{0}] to [{1}]'.format(container.filepath, container.mount_path)) if os.path.exists(container.mount_path) and os.path.isfile(container.mount_path): raise RuntimeError('The mount path [{0}] already exists and is a file'.format(container.mount_path)) if not os.path.exists(container.mount_path): self.logger.info('Creating directory [{0}] for mounting encrypted container [{1}]'.format(container.mount_path, container.filepath)) os.makedirs(container.mount_path) sh.chown(container.user_owner, container.mount_path) sh.mount('-t', 'btrfs', container.mapped_device, container.mount_path)
def mount_vm(self, img_src="", mount_path=""): """ Mount img_src at mount_path with kpartx """ if not os.path.exists(img_src): sys.exit("Invalid image to mount: %s" % (img_src)) if not os.path.exists(mount_path): sys.exit("Invalid mount path: %s" % (mount_path)) with sh.sudo: sh.kpartx('-a', img_src) mount_device=sh.head(sh.awk(sh.grep(sh.kpartx('-l', img_src), '-v', 'deleted'), '{print $1}'), '-1') sh.mount("/dev/mapper/%s" % (mount_device.rstrip()), mount_path)
def handle_ext4(img): global BOOT_OAT, BOOT_OAT_64 ext = getBasename(img) mnt_name = MNT_TMP + '_' + ext os.makedirs(DIR_TMP, exist_ok=True) os.makedirs(mnt_name, exist_ok=True) cp(img, DIR_TMP + '/' + ext) try: mount('-o', 'ro', '-t', 'ext4', DIR_TMP + '/' + ext, mnt_name) except sh.ErrorReturnCode_32: print('error mounting vfat image: ' + ext) BOOT_OAT = '' BOOT_OAT_64 = '' return True
def parse_mounts(): mountpoints = [] out = mount().strip().split("\n") for o in out: o1 = o.split(" on ") o2 = o1[1].split(" type ") short_mount = o2[0].strip().replace("/run/media/igor/", "") short_mount = short_mount.replace("/media/", "") o3 = o2[1].split() if o3[0] == "fuseblk": fs = real_fs(o1[0].strip()) else: fs = o3[0].strip() mountpoints.append({ "drive": o1[0].strip(), "mount": o2[0].strip(), "short_mount": short_mount, "fs": fs }) return mountpoints
def get_mount_path(device): """ Pobieranie ścieżki, w której zamontowane jest urządzenie :param device: Urządzenie np. /dev/sdb """ for line in sh.mount(): match = re.search("^{}.*on.(.*) type".format(device), line) if match is not None: return match.group(1)
def cleanup_mount_partitions(test_env_path, testing_options): """ Make cleanup of partitions dirs @param test_env_path: str path to test environment @param testing_options: dict with special options for testing like available partitions for mounting """ if (testing_options is None or testing_options.get('mounting', None) is None): log_guest("No mounting options found") return available_partitions = testing_options['mounting'].get('partitions', None) if available_partitions is None: log_guest("No available partitions found") return if not os.path.exists(test_env_path): os.mkdir(test_env_path) tmp_mount_dir = f'{test_env_path}/tmp{uuid.uuid4().hex}' if not os.path.exists(tmp_mount_dir): log_guest(f"Creating {tmp_mount_dir} for cleanup of mount partitions") os.mkdir(tmp_mount_dir) for partition in available_partitions: # mount points can be nested and therefore we could umount all the # mounted partitions in the first iteration, we have to check each time # remaining partitions all_mounted_partitions = sh.df().stdout.decode() if not os.path.exists(partition): log_guest(f"{partition} does not exist, removing from the options") available_partitions.remove(partition) continue # if the partition is mounted somewhere in the filesystem, umount it # first and we will mount it to our specific dir if partition in all_mounted_partitions: log_guest(f"Umount of {partition}") sh.umount(partition, '-O --recursive') log_guest(f"Cleanup of device {partition}") sh.mount(partition, tmp_mount_dir, '-text4') shutil.rmtree(tmp_mount_dir, ignore_errors=True) sh.umount(partition) os.rmdir(tmp_mount_dir)
def mount_remote_source(): global config global console type_remote_source = config.get('remote_source', 'type') if type_remote_source == 'smb': target = config.get('source', 'dir') path = config.get('remote_source', 'net_path') user = config.get('remote_source', 'user') password = config.get('remote_source', 'password') smb_version = config.get('remote_source', 'smb_version') console.print( 'Демонтирую удаленный источник {}... '.format(path), end='', effect='6', flush=True, ) try: sh.umount(target) console.print('ok', color='green') except: logger.exception(Exception) console.print('ok', color='green') console.print( 'Монтирую удаленный источник {}... '.format(path), end='', effect='6', flush=True, ) try: sh.mount( '-t', 'cifs', path, target, '-o', 'username='******',password='******',iocharset=utf8' + ',file_mode=0777,dir_mode=0777,' + 'vers=' + smb_version) console.print('ok', color='green') except sh.ErrorReturnCode_32: logger.exception(Exception) print_error('Ошибка монтирования remote_source! ' + \ 'Устройство занято!', True) except: logger.exception(Exception) print_error('Ошибка монтирования remote_source!', True)
def setupDisks(numDisks): print "Setup Disks" devLetters = list(string.ascii_lowercase) for x in range(1, int(numDisks) + 1): try: mkfs("/dev/xvd" + devLetters[x], "-text4", "-E lazy_itable_init=1") except Exception as e: pass if not os.path.exists("/mnt/data" + str(x)): os.makedirs("/mnt/data" + str(x)) try: mount("/dev/xvd" + devLetters[x], "/mnt/data" + str(x), "-text4") except Exception as e: pass try: Fstab.add("/dev/xvd" + devLetters[x], "/mnt/data" + str(x), filesystem="ext4") except Exception as e: pass
def usb_download(): # Get a list of all /dev/sd* partitions usb_partitions_re = re.compile("/dev/sd+(?P<part>\w+)", re.I) partitions = subprocess.check_output(["fdisk", "-l"]) devices = [] for i in partitions.split('\n'): if i: info = usb_partitions_re.match(i) if info: dinfo = info.groupdict() dinfo = '/dev/sd%s' % (dinfo.pop('part')) devices.append(dinfo) print devices # If no USB drives, return and try calling internet_wait() if not len(devices): return # Delete local pictures, make sure no USB is mounted before we begin clean_pictures() try: umount("/mnt") except: pass # For each partition, look for image files on the partition for i in devices: mount(i, "/mnt") file_list = subprocess.check_output(["ls", "/mnt"]) for i in file_list.split('\n'): if i.lower().endswith(tuple(img_types)): shutil.copy("/mnt/" + i, "/home/pi/Pictures") umount("/mnt") # Recursively chown/chmod Pictures folder for root, dirs, files in os.walk(slideshow_path): for f in files: os.chmod(os.path.join(slideshow_path, f), 0644) os.chown(os.path.join(slideshow_path, f), 1000, 1000) # UID of user 'pi'
def __init__(self): """Parses mounts to identify child partitions""" UdevDeviceManager.__init__(self) self.mounts = {} try: for line in sh.mount(): parts = line.split() if len(parts) >= 3 and parts[1] == 'on': self.mounts[parts[0]] = parts[2] except: pass
def mount(self, device=None, mount_point=None, sudo=False): if device is None or mount_point is None: log.debug('Mounting all filesystems') mount_args = ['-a'] else: log.debug('Mounting %s', mount_point) mount_args = [device, mount_point] if sudo: mount = sh.sudo('-n', 'mount', *mount_args) else: mount = sh.mount(*mount_args) return mount
def take_sequence(): sh.mount('/mnt/spb') with picamera.PiCamera() as camera: camera.resolution = (1024, 768) # Wait for the automatic gain control to settle time.sleep(1) # Set values so that set of pictures have the same brightness, color, # and contrast. camera.shutter_speed = camera.exposure_speed camera.exposure_mode = 'off' g = camera.awb_gains camera.awb_mode = 'off' camera.awb_gains = g # Take 5 shots, saving file in current directory with timestamp. camera.capture_sequence( ['/mnt/spb/{}_{:02d}.jpg'.format(time.strftime('%Y.%m.%d-%H:%M:%S'), i) for i in range(5)]) sh.umount('/mnt/spb')
def take_sequence(): sh.mount('/mnt/spb') with picamera.PiCamera() as camera: camera.resolution = (1024, 768) # Wait for the automatic gain control to settle time.sleep(1) # Set values so that set of pictures have the same brightness, color, # and contrast. camera.shutter_speed = camera.exposure_speed camera.exposure_mode = 'off' g = camera.awb_gains camera.awb_mode = 'off' camera.awb_gains = g # Take 5 shots, saving file in current directory with timestamp. camera.capture_sequence([ '/mnt/spb/{}_{:02d}.jpg'.format(time.strftime('%Y.%m.%d-%H:%M:%S'), i) for i in range(5) ]) sh.umount('/mnt/spb')
def _mount_device(dev_id, mount_dir): device = os.path.join('/dev', dev_id) mount_point = os.path.join(mount_dir, dev_id) actual_mount_point = CloudHost._get_mount_point(dev_id) if actual_mount_point == mount_point: return elif actual_mount_point is None: CloudHost.log_debug("Mounting device " + device + " at " + mount_point) res = sh.mount(mount_point) # the mount point must be mentioned in fstab file if res.exit_code != 0: raise Exception("Failed to mount device " + device + " at " + mount_point) else: raise Exception("Device already mounted at " + actual_mount_point)
def collect_existing_mounts(): """ return a dictionary of currently registered info. Key: mount path. Value: the block device path Note when a block is removed from system, the mount path is still registered """ result = {} for mount in sh.mount().stdout.decode('utf-8').splitlines(): tokens = mount.split() if tokens[1] == 'on' and tokens[0].startswith('/dev/'): device = tokens[0][5:] result[tokens[2]] = device return result
def mount_disk(device, mntpnt, fs): mkdir_err = False try: umount("-f", device) except ErrorReturnCode as ex: if "not mounted" in ex.stderr.decode(): pass if fs == "ntfs": fs = "-t ntfs-3g" try: mount(device, mntpnt, fs) except ErrorReturnCode as ex: if "does not exist" in ex.stderr.decode(): mkdir(mntpnt) if mkdir_err is False: try: mount(device, mntpnt, fs) except ErrorReturnCode as ex: if "does not exist" in ex.stderr.decode(): mkdir(mntpnt)
def get_mount_point(device_): """ Get the mounted directory path for a specific device. :param device_: Device name (e.g., "/dev/sdb1") :return: String """ for line in grep(mount(), device_, _ok_code=[0, 1], _iter=True): words = line.split() if device_ in words[0]: if mem.options.debug: print "[+] get_mount_point found {0} mounted on {1}".format( device_, words[2]) return words[2] return None
def mount_devices(self): """ Montowanie obrazu dysku :param image_path: Ścieżka bezwzględna do obrazu """ self.mount_folder = "/media/pyWinUSB/{}".format(hashlib.sha1(self.image_path.encode("utf-8")).hexdigest()) self.source_mount = self.mount_folder + "/source" self.destination_mount = self.mount_folder + "/destination" # Odmontowywanie na wszelki wypadek try: sh.umount(self.source_mount) except: pass # Montownie obrazu ISO dysku sh.mkdir(self.source_mount, self.destination_mount, "-p") sh.mount(self.image_path, self.source_mount, o="loop") # Montowanie urządzenia subprocess.call(["sfdisk", self.device, "-R"]) subprocess.call(["mount", self.device + "1", self.destination_mount]) # Sprawdzanie systemu plików pod kątem rozmiaru if USBCreator.get_device_size(self.device) < os.path.getsize(self.image_path): raise Exception("No enough space on disk/partition!")
def LicheePiImage(workdir, boot_files, kernel_files, rootfs_files): mkdir('-p', workdir) IMAGE_NAME = 'sdcard.img' IMAGE_PATH = str(Path(workdir).joinpath(IMAGE_NAME)) dd('if=/dev/zero', 'of={}'.format(IMAGE_PATH), 'bs=1M', 'count=300') loop_dev = str(losetup('-f')).split()[0] losetup(loop_dev, IMAGE_PATH) sfdisk(cat(_in='1M,16M,c\n,,L'), loop_dev) partx('-u', loop_dev) mkfsvfat('{}p1'.format(loop_dev)) mkfsext4('{}p2'.format(loop_dev)) dd('if=/dev/zero', 'of={}'.format(loop_dev), 'bs=1K', 'seek=1', 'count=1023') dd('if={}'.format(boot_files['bootstrap']), 'of={}'.format(loop_dev), 'bs=1K', 'seek=8') sync() mkdir('-p', '/tmp/p1') mkdir('-p', '/tmp/p2') mount('{}p1'.format(loop_dev), '/tmp/p1') mount('{}p2'.format(loop_dev), '/tmp/p2') cp(boot_files['bin'], '/tmp/p1/') cp(kernel_files['bin'], '/tmp/p1/') cp(kernel_files['dtb'], '/tmp/p1/') mkimage('-C', 'none', '-A', 'arm', '-T', 'script', '-d', './resources/boot.cmd', '/tmp/p1/boot.scr') rsync('-r', '--links', rootfs_files['rootdir'] + '/', '/tmp/p2/') mkdir('-p', '/tmp/p2/etc/init.d') mkdir('-p', '/tmp/p2/proc') mkdir('-p', '/tmp/p2/dev') mkdir('-p', '/tmp/p2/sys') mkdir('-p', '/tmp/p2/var') touch('/tmp/p2/etc/init.d/rcS') chown('-R', 'root:root', '/tmp/p2/')
def _mount_device(dev_id, mount_dir): device = os.path.join('/dev', dev_id) mount_point = os.path.join(mount_dir, dev_id) actual_mount_point = CloudHost._get_mount_point(dev_id) if actual_mount_point == mount_point: return elif actual_mount_point is None: CloudHost.log_debug("Mounting device " + device + " at " + mount_point) res = sh.mount( mount_point) # the mount point must be mentioned in fstab file if res.exit_code != 0: raise Exception("Failed to mount device " + device + " at " + mount_point) else: raise Exception("Device already mounted at " + actual_mount_point)
def get_device_mount(dev_): """ Return mount point for specified device. :param string_: :return: """ if dev_ is None: return None, None for line in mount(_iter=True): if dev_ in line: dev_mount_ = line.split()[2] if mem.options.debug: print "[+] get_device_mount found {0} mounted on {1}".format( dev_, dev_mount_) return dev_mount_ return None
def mount(partition, inspect_path): """ Mount given partition. Args: partition (str): The path to the partition to mount. inspect_path (str): The path where the partition should be mounted. """ click.echo(_("Mounting {}.").format(partition)) mount_result = sh.mount("-t", "auto", "{}".format(partition), "{}".format(inspect_path)) click.echo(_("Mounting result {}.").format(mount_result.exit_code)) yield mount_result click.echo(_("UnMounting {}.").format(partition)) unmount_result = sh.umount("{}".format(inspect_path)) click.echo(_("UnMounting result {}.").format(unmount_result.exit_code))
def _mount_device(dev_id, mount_dir): t1 = time.time() device = os.path.join('/dev', dev_id) mount_point = os.path.join(mount_dir, dev_id) actual_mount_point = CloudHost._get_mount_point(dev_id) if actual_mount_point == mount_point: CloudHost.log_debug("Device %s already mounted at %s", device, mount_point) return elif actual_mount_point is None: CloudHost.log_debug("Mounting device %s at %s", device, mount_point) res = sh.mount(mount_point) # the mount point must be mentioned in fstab file if res.exit_code != 0: raise Exception("Failed to mount device %s at %s. Error code: %d", device, mount_point, res.exit_code) else: raise Exception("Device already mounted at " + actual_mount_point) tdiff = int(time.time() - t1) CloudHost.publish_stats("EBSMountTime", "Count", tdiff)
def _create_bootstrap_img(self): self._bootstrap_dir = tempfile.mkdtemp() sh.chmod("o+rwx", self._bootstrap_dir) self._bootstrap_files = os.path.join(self._bootstrap_dir, "files") os.makedirs(self._bootstrap_files) with open(os.path.join(os.path.dirname(__file__), "bootstrap.py"), "r") as f: bootstrap_contents = f.read() with open(os.path.join(self._bootstrap_files, "bootstrap.py"), "wb") as f: f.write(bootstrap_contents) with open(os.path.join(self._bootstrap_files, "config.json"), "wb") as f: f.write(self._make_config()) self._bootstrap_img = os.path.join(self._bootstrap_dir, "bootstrap.img") sh.dd("if=/dev/null", "bs=1K", "of={}".format(self._bootstrap_img), "seek=2040") sh.Command("mkfs.ntfs")("-F", self._bootstrap_img) #sh.Command("mkfs.vfat")(self._bootstrap_img) mounted_dir = os.path.join(self._bootstrap_dir, "mounted") os.makedirs(mounted_dir) output = sh.mount("-t", "ntfs", "-o", "loop", self._bootstrap_img, mounted_dir) #output = sh.mount("-t", "vfat", "-o", "loop", self._bootstrap_img, mounted_dir) #self._log.debug("mount output: " + str(output)) shutil.copy(os.path.join(self._bootstrap_files, "bootstrap.py"), mounted_dir) shutil.copy(os.path.join(self._bootstrap_files, "config.json"), mounted_dir) try: sh.umount(mounted_dir) except: pass return self._bootstrap_img
def find_device_bystring(string_): """ Look for device mounted by searching mount output for string_. :param string_: :return: """ if string_ is None: return None, None for line in grep(mount(), "udisks", _ok_code=[0, 1], _iter=True): words = line.split() w1_ = words[0] w2_ = words[2] if string_ in w2_: if mem.options.debug: print "[+] find_device_by_string found {0} mounted on {1}".format( w1_, w2_) return w1_, w2_ return None, None
def mount_compat(self, mode="ro"): status = True try: sh.mount("-o", "{0},{1}".format(mode, self.MOUNT_OPTIONS), self.path, self.output_path) except sh.ErrorReturnCode as e: log.debug("Legacy re-mount opts for {0}".format(self)) try: sh.mount("-o", "{0}".format(mode), self.path, self.output_path) except: try: sh.mount(self.path, self.output_path) except Exception as e: log.error("Cannot mount : {0}".format(self)) log.exception(e) status = False return status
log("mountpoint %s now exists" % mountpoint ) # Check to see if the volume is already mounted and linked, and change the state # if not (I assume this means mount it and link it if it is not mounted or if # the symlink is wrong) if not mounted(mountpoint) : # mount( table[node][VOLUME], table[node][TYPE], mountpoint, table[node][OPTIONS] ) # Mounts device of file system type fs_type at mountpoint mountpoint, # with options options. Reads /proc/mounts (the requirements don't say anything about which # operating system this software has to run on. If running on something other # than linux, this subroutine will throw a FileNotFoundError) to see if the # file system is mounted. It assumes that the mountpoint exists.""" # mount is from module sh log("mounting %s at mountpoint % file system %s with options %s" % \ ( table[node][VOLUME], mountpoint, fs_type, options) ) mount( table[node][VOLUME], mountpoint, "-t " + fs_type, "-o "+options ) else : raise ValueError(("Invalid value of ENABLE %s") % table[node][ENABLE] ) # The entry in the LINK column should be symlinked to the mount point. handle_symlink ( mountpoint, table[node][LINK] ) # This should be completed in an hour end_time = datetime.datetime.now() duration = end_time - start_time log("-------- ended at %s duration %s \n" % (str(end_time), str(duration) ) ) if duration > datetime.timedelta(hours=1) : log ("FAILED TO COMPLETE IN 1 HOUR, actually took " + str(duration) )
def remount(self, directory): " Remount a directory." sh.mount('-o', 'remount', directory, _err=sys.stderr, _out=sys.stdout)
cblog(msg, 1) ret = E_FAIL_CONN_MEDIA_SRV return ret nfs_path = "%s:%s" % (srv, media_path) ## check whether mounted try: if not os.path.exists(dest_path): exit_code = exec_shell_cmd('mkdir', "-p", dest_path) if exit_code != 0: print "Fail to create dest_path ", dest_path ret = E_FAIL_CREATE_DIR return ret except Exception, e: pass try: out = sh.grep( sh.mount(), dest_path ) exit_code = out.exit_code except Exception, e: exit_code = -1 ret = E_NO_MEDIA_EXPORT pass if exit_code == 0: ## the dest_path has mounted return E_NO_ERR ret = E_NO_ERR count = 0 while count < 2: exit_code = exec_shell_cmd('mount', "-t", "nfs", nfs_path, dest_path) if exit_code == 32: ## rpcbind did not start exit_code = start_rpc_bind() if exit_code != 0: break count += 1
def device_mount_context_manager(device): mountpoint = mkdtemp() mount(device, mountpoint, **SH_OPTS) yield mountpoint umount(mountpoint, **SH_OPTS) os.rmdir(mountpoint)
mountpoint = 'priv-esc' # mount point for my priv-esc dir to have locally in my working dir exploits_mount = 'exploits' shells_mount = 'shells' scripts_mount = 'scripts' dirs = [ 'enum', exploits_mount, 'exfiltrated', mountpoint, shells_mount, scripts_mount ] #dirs to create with priv-esc to be used as mount point try: ostype = sys.argv[1] #take first argument as the unix or windows for item in dirs: sh.mkdir( item ) #loop through the dirs list and create each one in the current dir if ostype == 'windows': #conditional statements to check for windows or unix and make the proper mount point sh.mount('--bind', '/root/priv-esc/windows/', mountpoint) elif ostype == 'unix': sh.mount('--bind', '/root/priv-esc/unix/', mountpoint) else: print("must choose 'windows' or 'unix' for first arg") print("usage: dirtree.py [unix/windows]" ) #choose windows or unix to mount proper priv-esc point sh.mount( '--bind', '/root/exploits/', exploits_mount ) #start mounting the bind points for the created dirs(these are OS indifferent) sh.mount('--bind', '/root/shells/', shells_mount) sh.mount('--bind', '/root/scripts/', scripts_mount) except Exception as e: print(e) print("usage: dirtree.py [unix/windows]" ) #choose windows or unix to mount proper priv-esc point
import purestorage import pyodbc import requests import sh requests.packages.urllib3.disable_warnings() db = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=tcp:testinstance.puresql.lab;DATABASE=master;UID=demo;PWD=demo', autocommit = True) cursor = db.cursor() cursor.execute('ALTER DATABASE TestDB SET OFFLINE WITH ROLLBACK IMMEDIATE') sh.umount('/var/opt/mssql/data/TestDB') array = purestorage.FlashArray("flasharray-m20.puresql.lab", api_token = "28a21f21-7d42-255a-11fd-cf42117ab86d") array.copy_volume("production-data-volume", "test-data-volume", **{"overwrite": True}) sh.mount('/var/opt/mssql/data/TestDB') cursor.execute('ALTER DATABASE TestDB SET ONLINE') array.invalidate_cookie()
#!/usr/bin/env python import os, sh from time import sleep import RPi.GPIO as gpio gpio.setmode(gpio.BCM) gpio.setwarnings(False) import boot_selector_config try: print('\032[1;32;40m mounting /dev/mmcblk0p2') sh.mount('/dev/mmcblk0p2', '/mnt') except sh.ErrorReturnCode_32: print('\033[1;33;40m \t/dev/mmcblk0p2 is already mounted') pass except sh.ErrorReturnCode_1: print('\031[1;31;40m Run as root!') quit(1) except Exception as e: print('\031[1;31;40m {0}\n{1} -> {2}'.format(e, type(e).__name__, e.args)) quit(2) if not os.path.isfile('./images.log'): print('\032[1;33;40m creating images.log file') sh.touch('./images.log') else: print('\032[1;32;40m images.log file exists') if not os.path.isfile('/mnt/data/runonce'): print('\032[1;33;40m creating runonce file') sh.touch('/mnt/data/runonce')
mount = path.join("/mnt/usb", split[i + 1]).replace(":", "..") return mount # Get available USB drives drives = glob("/dev/disk/by-path/*-usb-*part1") # Get intended mount points mounts = [mountpoint(device) for device in drives] # Get all previously mounted points mounted = glob("/mnt/usb/*") # Get ro mounts ro = [] for line in sh.mount(_iter=True): for mount in mounted: if mount in line and "ro" in line: ro.append(mount) # Unmount all missing drives for mount in mounted: if mount not in mounts or mount in ro: print(f"Unmounting {mount}") try: sh.umount(mount) except Exception as e: pass try: sh.rmdir(mount)
def _get_mount_point(dev_id): device = os.path.join('/dev', dev_id) for line in sh.mount(): if line.startswith(device): return line.split()[2] return None
def make_temp_filesystem(root, mb_size): with sh.contrib.sudo: sh.mount("-t", "tmpfs", "-o", "size=" + str(mb_size) + "M", "tmpfs", root)
def other_mounts(): sh.mount('/dev/disk/by-partlabel/boot', f'{paths.zroot}/boot') sh.mount('--rbind', '/dev', f'{paths.zroot}/dev', '--make-rslave') sh.mount('--rbind', '/proc', f'{paths.zroot}/proc', '--make-rslave') sh.mount('--rbind', '/sys', f'{paths.zroot}/sys', '--make-rslave')
def other_mounts(): sh.mount(config.boot_dev, f'{paths.zroot}/boot') sh.mount('--rbind', '/dev', f'{paths.zroot}/dev', '--make-rslave') sh.mount('--rbind', '/proc', f'{paths.zroot}/proc', '--make-rslave') sh.mount('--rbind', '/sys', f'{paths.zroot}/sys', '--make-rslave')
def run(detach: bool, image: str = 'ubuntu', uuid: str = None, load: bool = False, cmd=('/bin/uname', '-a')): cgroup_name = 'test' base_image_path = os.path.join('./base_images/', image + '.img') # TODO exist? if not uuid: uuid = uuid1() if type(cmd) is str: cmd = tuple(shlex.split(cmd)) container_name = str(uuid) + '.img' img_path = os.path.join('container', container_name) mount_path = './container/' + str(uuid) if not load: shutil.copy(base_image_path, img_path) if not os.path.exists(mount_path): os.mkdir(mount_path) mount('-o', 'rw', img_path, mount_path) cg = Cgroup(cgroup_name) cg.set_cpu_limit(50) cg.set_memory_limit(512) print("uuid:", uuid) # TODO remove # create record create_record(uuid, image, cmd) # env my_env = os.environ.copy() path = set(my_env["PATH"].split(":")) path.add("/bin") path.add("/sbin") path.add("/usr/bin") path.add("/usr/sbin") path.add("/usr/local/bin") path.add("/usr/local/sbin") my_env["PATH"] = ":".join(path) def hook(): cg.add(os.getpid()) os.chroot('.') # proc = subprocess.Popen('echo hello world subprocess!', shell=True) # proc = subprocess.Popen(['ls', '-lah'], shell=False) # proc = subprocess.Popen(['free', '-h'], preexec_fn=hook, shell=False) proc = subprocess.Popen(cmd, preexec_fn=hook, cwd=mount_path, env=my_env) # TODO try catch # stdout_r, stdout_w = os.pipe() # stdout_r = os.fdopen(stdout_r) # stdout_w = os.fdopen(stdout_w, 'w') # proc = subprocess.Popen('/bin/bash', preexec_fn=hook, cwd=mount_path, env=my_env, # stdin=subprocess.PIPE, stdout=stdout_w, stderr=subprocess.STDOUT, # universal_newlines=True) # # proc.stdin.write(b'ls /\n') # # proc.stdin.flush() # # while True: # # buf = stdout_r.readline() # # if not buf: # # break # # redirect_socket.send(buf) # # buf = redirect_socket.recv(1024) # # proc.stdin.write(buf) # print("Input: ", end="", file=stdout_w, flush=True) # print(redirect_socket.recv(1024).decode(), file=proc.stdin, flush=True) # buf = stdout_r.readline() # redirect_socket.send(buf.encode()) if detach: # TODO add to pool processes[str(uuid)] = proc return str(uuid) # TODO else: proc.wait() # cleanup umount(mount_path) os.rmdir(mount_path)