示例#1
0
    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!")
示例#2
0
def make_random_fast():
    ''' Link /dev/random to /dev/urandom.

        See
            Myths about /dev/urandom
                http://www.2uo.de/myths-about-urandom/
            Hacker news discussion where cperciva does not disagree with "Myths about /dev/urandom"
                https://news.ycombinator.com/item?id=10149019

        The risk of using urandom is that it can be deterministic.
        If you know the seed, you may know all of urandom's output forever.

        That is why we prefer to add entropy at runtime, using e.g. haveged.
        But does haveged affect urandom? The urandom seed may be set just
        once and saved, or set at boot before haveged runs.
    '''
    
    # delete /dev/random
    if os.path.exists('/dev/random'):
        if os.path.isfile('/dev/random') or os.path.islink('/dev/random'):
            os.remove('/dev/random')
        else:
            try:
                sh.umount('/dev/random')
            except:
                sh.rm('--force', '--recursive', '/dev/random')

    # "rngd -r /dev/urandom" should only be used during testing, if ever
    # if not is_program_running('rngd'):
    #     sh.rngd('-r', '/dev/urandom')

    sh.ln('--symbolic', '/dev/urandom', '/dev/random')
示例#3
0
    def load(self, mode="ro"):
        try:
            self.create_output_path()
            sh.chmod("700", self.output_path)
        except sh.ErrorReturnCode as e:
            ## Already mounted readonly.
            pass
        try:
            log.debug("Loading {0}".format(self))

            self.loaded = self.mount_compat("rw")
            if self.loaded:
                try:
                    sh.rm(
                        "-rf", os.path.join(self.output_path, '._.Trashes'),
                        os.path.join(self.output_path, '.Spotlight-V100'),
                        os.path.join(self.output_path, 'lost+found'),
                        os.path.join(self.output_path, '$RECYCLE.BIN'),
                        os.path.join(self.output_path,
                                     'System Volume Information'))
                except:
                    pass
                try:
                    sh.umount(self.output_path)
                except:
                    self.loaded = False
                self.loaded = self.mount_compat(mode)
                return self.loaded
            else:
                return False
        except sh.ErrorReturnCode as e:
            self.unload()
            log.exception(e)
            return False
示例#4
0
文件: creator.py 项目: poxip/pyWinUSB
 def close_stream(self):
     """ Zamykanie urządzenia i kasowanie plików tymczasowych
     """
     if self.source_mount is not None:
         sh.sync()
         sh.umount(self.source_mount, self.destination_mount)
         sh.rm(self.mount_folder, '-rf')
示例#5
0
 def close_stream(self):
     """ Zamykanie urządzenia i kasowanie plików tymczasowych
     """
     if self.source_mount is not None:
         sh.sync()
         sh.umount(self.source_mount, self.destination_mount)
         sh.rm(self.mount_folder, '-rf')
示例#6
0
    def unmount(target):
        if not target:
            raise NameError('Unmounting requires a target directory')

        try:
            sh.umount(target)
        except sh.ErrorReturnCode:
            print('Unmounting ' + target + ' failed.')
示例#7
0
文件: create_vm.py 项目: bmoar/vm
    def umount_vm(self, mount_path=""):
        """
            Umount the image at mount_path
        """

        if not os.path.exists(mount_path):
            sys.exit("Error unmounting %s" % (mount_path))

        with sh.sudo:
            sh.umount(mount_path)
示例#8
0
    def teardown(self):
        try:
            sh.umount(self.http_directory)
        except Exception as ex:
            pass

        try:
            sh.umount(self.https_directory)
        except Exception as ex:
            pass
示例#9
0
    def setup(self):
        """
        Set up filesystem in user space for http and https
        so that we can retrieve tiles from remote sources.

        Parameters
        ----------
        tmp_dir: string
            The temporary directory where to create the
            http and https directories
        """
        from simple_httpfs import HttpFs

        if not op.exists(self.http_directory):
            os.makedirs(self.http_directory)
        if not op.exists(self.https_directory):
            os.makedirs(self.https_directory)
        if not op.exists(self.diskcache_directory):
            os.makedirs(self.diskcache_directory)

        try:
            sh.umount(self.http_directory)
        except Exception as ex:
            pass

        try:
            sh.umount(self.https_directory)
        except Exception as ex:
            pass

        disk_cache_size = 2**25
        disk_cache_dir = self.diskcache_directory
        lru_capacity = 400
        print(
            "self.diskcache_directory",
            self.diskcache_directory,
            op.exists(self.diskcache_directory),
        )

        def start_fuse(directory):
            print("starting fuse")
            fuse = FUSE(
                HttpFs(
                    "http",
                    disk_cache_size=disk_cache_size,
                    disk_cache_dir=self.diskcache_directory,
                    lru_capacity=lru_capacity,
                ),
                directory,
                foreground=False,
            )

        proc = mp.Process(target=start_fuse, args=[self.http_directory])
        proc.start()
        proc.join()
示例#10
0
 def unload(self):
     log.debug("Unloading {0}".format(self))
     try:
         sh.umount("-lf", self.path)
     except sh.ErrorReturnCode:
         pass
     try:
         sh.rm("-rf", self.output_path)
     except sh.ErrorReturnCode:
         return False
     self.loaded = False
     return True
示例#11
0
def umount_dir(tgt):

    result = subprocess.Popen(["mountpoint", "-q", tgt])

    # we must explictly wait for the process to finish.
    # Otherwise, we do not get the correct result
    result.wait()
    if result.returncode == 0:
        try:
            umount("-l", tgt)
        except Exception as ex:
            msg = (('exception is : %s'), six.text_type(ex))
            LOG.error(msg)
    return True
示例#12
0
文件: creator.py 项目: poxip/pyWinUSB
 def open_device(self):
     # Odmontowywanie urządzenia jeśli jest ono zamontowane
     mount_path = USBCreator.get_mount_path(self.device)
     if mount_path:
         response = MessageBox( parent=self
                              , title="Device is already in use"
                              , message="Unmount device {device} mounted in:\n {mount_path}?"
                                 .format(device=self.device, mount_path=mount_path)
                              )
         if response == Gtk.ResponseType.OK:
             # Odmontowywanie urządzenia jeśli zatwierdzone
             sh.umount(mount_path)
         else:
             raise Exception("Device must be unmounted before copying!")
示例#13
0
 def open_device(self):
     # Odmontowywanie urządzenia jeśli jest ono zamontowane
     mount_path = USBCreator.get_mount_path(self.device)
     if mount_path:
         response = MessageBox(
             parent=self,
             title="Device is already in use",
             message="Unmount device {device} mounted in:\n {mount_path}?".
             format(device=self.device, mount_path=mount_path))
         if response == Gtk.ResponseType.OK:
             # Odmontowywanie urządzenia jeśli zatwierdzone
             sh.umount(mount_path)
         else:
             raise Exception("Device must be unmounted before copying!")
示例#14
0
def umount_dir(tgt):
    # For some reason sh.mountpoint does not work, so
    # using subprocess instead.
    result = subprocess.Popen(["mountpoint", "-q", tgt])

    # we must explictly wait for the process to finish.
    # Otherwise, we do not get the correct result
    result.wait()
    if result.returncode == 0:
        try:
            umount("-l", tgt)
        except Exception as ex:
            msg = (_('exception is : %s'), six.text_type(ex))
            LOG.error(msg)
            raise exception.HPEPluginUMountException(reason=msg)
    return True
示例#15
0
def umount_dir(tgt):
    # For some reason sh.mountpoint does not work, so
    # using subprocess instead.
    result = subprocess.Popen(["mountpoint", "-q", tgt])

    # we must explictly wait for the process to finish.
    # Otherwise, we do not get the correct result
    result.wait()
    if result.returncode == 0:
        try:
            umount("-l", tgt)
        except Exception as ex:
            msg = (_('exception is : %s'), six.text_type(ex))
            LOG.error(msg)
            raise exception.HPEPluginUMountException(reason=msg)
    return True
示例#16
0
 def umount_volume(self):
     logger.debug('Un mounting {} volume from droplet {}'.format(
         self.name, droplet.id))
     try:
         mountpoint('-q', self.mount_point)
     except ErrorReturnCode_1:
         logger.debug('Volume {} is not mounted on {}'.format(
             self.name, droplet.id))
         return True
     else:
         try:
             umount(self.mount_point)
         except ErrorReturnCode as err:
             logger.error('Umount failed: {}'.format(err))
             return False
     return True
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)
示例#18
0
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)
示例#19
0
    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
示例#20
0
def terminate(uuid: str) -> str:
    result = find_uuid(uuid)
    if not result:
        return "no such container: " + uuid
    # elif result not in processes:
    # print("unexpected behavior", file=sys.stderr)
    # return "already exited"
    else:
        uuid = result
        proc = processes.get(uuid, None)
        mount_path = os.path.join('container', str(uuid))
        if proc:
            proc.terminate()
            proc.wait()
        # cleanup
        umount(mount_path)
        os.rmdir(mount_path)
        return "should be stopped"
示例#21
0
 def unmount(self, devices, sudo = False):
     log.debug('unmount(%r, %r)', devices, sudo)
     mounted = filter(lambda mount: mount.spec in devices, self._mounts)
     if mounted:
         if len(mounted) > 1:
             for m in mounted:
                 log.critical(str(m))
             raise Exception('Found more than one mount for device "%s"', devices[0])
         mount = mounted.pop()
         log.info('Unmounting %s mounted at %s', mount.spec, mount.file)
         if sudo:
             sh.sudo('-n', 'umount', mount.spec)
         else:
             sh.umount(mount.spec)
         self._orig_mount = mount
         return mount
     log.info('Device %s not found in mounted filesystems', devices[0])
     return
示例#22
0
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'
示例#23
0
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')
示例#24
0
def unmount_device(device_path):
    if not sys.platform.startswith("linux"):
        if settings.DEBUG:
            logger.debug("(virtually) unmounting {}".format(device_path))
            return
        else:
            raise NotImplemented("USB exports is Linux-only")

    dev_root, dev_name = device_path.rsplit("/", 1)
    partitions = [
        os.path.join(dev_root, fname) for fname in os.listdir(dev_root)
        if fname.startswith(dev_name) and fname != dev_name
    ]

    with sh.sudo:
        for device_partition in partitions:
            logger.debug("unmounting {}".format(device_partition))
            try:
                sh.umount(device_partition)
            except sh.ErrorReturnCode_32:
                pass
示例#25
0
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')
示例#26
0
    def umount_chroot(self,chroot_dir):
        '''
        Umount system directories with -lazy, 
        '''
        if not isinstance(chroot_dir,Path):
            chroot_dir = Path(chroot_dir)

        # Test if exists chroot
        if not chroot_dir.is_dir():
            print("NO DIR CHROOT: "+str(chroot_dir))
            return n4d.responses.build_successful_call_response(True)
        else:
            devices_mounted = [ z[2] for z in re.findall(r"(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\n", mount().stdout.decode('utf-8')) ]
            points_to_umount = [ "net/mirror", "proc", "sys", "dev/pts", "dev", "etc/hosts", "etc/ld.so.conf.d", "etc/nsswitch.conf" ]

            for x in points_to_umount:
                if chroot_dir.joinpath(x) in devices_mounted:
                    umount(chroot_dir.joinpath(x),lazy=True)
            if chroot_dir in devices_mounted:
                umount(chroot_dir,lazy=True)
   
        return n4d.responses.build_successful_call_response(True)
示例#27
0
文件: aws.py 项目: arshak/JuliaBox
 def unmount_device(dev_id, mount_dir):
     mount_point = os.path.join(mount_dir, dev_id)
     actual_mount_point = CloudHost._get_mount_point(dev_id)
     if actual_mount_point is None:
         return  # not mounted
     CloudHost.log_debug("Unmounting dev_id:" + repr(dev_id) +
                           " mount_point:" + repr(mount_point) +
                           " actual_mount_point:" + repr(actual_mount_point))
     if mount_point != actual_mount_point:
         CloudHost.log_info("Mount point expected:" + mount_point + ", got:" + repr(actual_mount_point))
         mount_point = actual_mount_point
     res = sh.umount(mount_point)  # the mount point must be mentioned in fstab file
     if res.exit_code != 0:
         raise Exception("Device could not be unmounted from " + mount_point)
示例#28
0
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)
示例#29
0
    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
示例#30
0
文件: creator.py 项目: poxip/pyWinUSB
    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!")
示例#31
0
def unmount(mountpoint):
    ''' Unmount mountpoint. '''

    if mounted(mountpoint):
        log.debug('unmount {}'.format(mountpoint))

        try:
            sh.umount(mountpoint)

        finally:
            log.debug('error in unmount: {}'.format(mountpoint))
            # if not mounted, try to find out why
            if mounted(mountpoint):

                # import delayed to avoid import recursion
                import syr.process

                # find what has the path open
                msg = 'unmount failed: {}'.format(mountpoint)
                programs = syr.process.programs_using_file(mountpoint)
                if programs:
                    msg += ', in use by {}'.format(programs)
                log.debug(msg)

                # try waiting a couple of seconds
                import time # DEBUG
                time.sleep(2) # DEBUG
                if mounted(mountpoint): # DEBUG
                    log.debug('still mounted after delay: {}'.format(mountpoint)) # DEBUG
                else: # DEBUG
                    log.debug('NOT mounted after delay: {}'.format(mountpoint)) # DEBUG

                raise FileSystemException(msg)

            else:
                log.debug('umount had error but path is not mounted: {}'.format(mountpoint))
示例#32
0
def clean_up():
    #umount(MNT_TMP, '-fl', '>', '/dev/null')
    files = subprocess.run(
        ['ls', DIR_TMP],
        stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
    for f in files:
        if f.startswith('mnt'):
            try:
                umount('-fl', DIR_TMP + '/' + f)
            except:
                print('Failure to unmount: ' + f)

    if os.path.exists(DIR_TMP):
        shutil.rmtree(DIR_TMP)
    if os.path.exists(APK_TMP):
        shutil.rmtree(APK_TMP)
    if os.path.exists(ZIP_TMP):
        shutil.rmtree(ZIP_TMP)
    if os.path.exists(ODEX_TMP):
        shutil.rmtree(ODEX_TMP)
    if os.path.exists(TAR_TMP):
        shutil.rmtree(TAR_TMP)
    if os.path.exists(MSC_TMP):
        shutil.rmtree(MSC_TMP)
示例#33
0
    def teardown(self):
        try:
            if OS_NAME == 'Darwin':
                sh.umount("HttpFs")
                sh.umount(self.http_directory)
            else:
                sh.fusermount("-uz", self.http_directory)
        except Exception:
            pass

        try:
            if OS_NAME == 'Darwin':
                sh.umount("HttpFs")
                sh.umount(self.https_directory)
            else:
                sh.fusermount("-uz", self.https_directory)
        except Exception:
            pass
示例#34
0
 def unmount_device(dev_id, mount_dir):
     mount_point = os.path.join(mount_dir, dev_id)
     actual_mount_point = CloudHost._get_mount_point(dev_id)
     if actual_mount_point is None:
         return  # not mounted
     t1 = time.time()
     CloudHost.log_debug("Unmounting dev_id:" + repr(dev_id) +
                         " mount_point:" + repr(mount_point) +
                         " actual_mount_point:" + repr(actual_mount_point))
     if mount_point != actual_mount_point:
         CloudHost.log_warn("Mount point expected:" + mount_point + ", got:" + repr(actual_mount_point))
         mount_point = actual_mount_point
     res = sh.umount(mount_point)  # the mount point must be mentioned in fstab file
     if res.exit_code != 0:
         raise Exception("Device could not be unmounted from " + mount_point)
     tdiff = int(time.time() - t1)
     CloudHost.publish_stats("EBSUnmountTime", "Count", tdiff)
示例#35
0
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))
示例#36
0
 def unmount_device(dev_id, mount_dir):
     mount_point = os.path.join(mount_dir, dev_id)
     actual_mount_point = CloudHost._get_mount_point(dev_id)
     if actual_mount_point is None:
         return  # not mounted
     CloudHost.log_debug("Unmounting dev_id:" + repr(dev_id) +
                         " mount_point:" + repr(mount_point) +
                         " actual_mount_point:" + repr(actual_mount_point))
     if mount_point != actual_mount_point:
         CloudHost.log_info("Mount point expected:" + mount_point +
                            ", got:" + repr(actual_mount_point))
         mount_point = actual_mount_point
     res = sh.umount(
         mount_point)  # the mount point must be mentioned in fstab file
     if res.exit_code != 0:
         raise Exception("Device could not be unmounted from " +
                         mount_point)
示例#37
0
文件: M2x.py 项目: eliasbakken/redeem
  def execute(self, g):
    device_id = check_device_id(self.printer, g)
    if not device_id:
      return

    if device_id == '/usb':
      sh.umount(USB_MOUNT_LOCATION)
      self.printer.send_message(g.prot, "external memory location closed '{}'".format(device_id))

    if device_id == '/sd':
      sh.umount(SD_DEVICE_1_LOCATION)
      sh.umount(SD_DEVICE_2_LOCATION)
示例#38
0
 def unmount_device(dev_id, mount_dir):
     mount_point = os.path.join(mount_dir, dev_id)
     actual_mount_point = CloudHost._get_mount_point(dev_id)
     if actual_mount_point is None:
         return  # not mounted
     t1 = time.time()
     CloudHost.log_debug("Unmounting dev_id:" + repr(dev_id) +
                         " mount_point:" + repr(mount_point) +
                         " actual_mount_point:" + repr(actual_mount_point))
     if mount_point != actual_mount_point:
         CloudHost.log_warn("Mount point expected:" + mount_point +
                            ", got:" + repr(actual_mount_point))
         mount_point = actual_mount_point
     res = sh.umount(
         mount_point)  # the mount point must be mentioned in fstab file
     if res.exit_code != 0:
         raise Exception("Device could not be unmounted from " +
                         mount_point)
     tdiff = int(time.time() - t1)
     CloudHost.publish_stats("EBSUnmountTime", "Count", tdiff)
# requirements document says and what the key name is in table, and volume.
        filername, volume = table[node][VOLUME].split(":") 
        mountpoint = "/mnt/%s/%s%s" % ( table[node][TYPE], filername, volume )
        log("Mountpoint is %s\n" % mountpoint )
# This is new in Python 3.  I can create the directory without throwing an
# exception if it already exists
        os.makedirs(mountpoint, exist_ok=True)

# if the ENABLE field is marked N, then the volume should be unmounted and
# commented out in in fstab.  This should be completed in 1 hour
        if table[node][ENABLE] == "N" :
# This isn't portable to non-linux systems, but the requirements document
# didn't say anything about portability.  If the volume is mounted, then
# it should appear in /proc/mounts
            if string_in_file (volume, "/proc/mounts") != "" :
                umount( table[node][volume] )
                log("Umounting %s\n" % table[node][volume] )
            else :
                log("%s wasn't mounted and enable was 'N', so do nothing\n" % table[node][VOLUME] )
        elif table[node][ENABLE] == "Y" :
# do not assume that the mountpoint exists.  Since exist_ok is true, this call
# will not throw an exception if the 
            os.makedirs(mountpoint,exist_ok=True)
            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
示例#40
0
 def unmount(self):
     """Execute an unmount action against this device node. Must be running as root."""
     sh.umount(self.device_node)
示例#41
0
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()
示例#42
0
文件: camera.py 项目: linky/picamera
def umountDrive():
	print('umount %s' % VIDEO_DIR)
	try:
		sh.umount(VIDEO_DIR)
	except:
		pass
示例#43
0
	def umount(self):
		"""umount the device"""
		sh.umount(self.mount_point)
示例#44
0
# 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)
    except Exception as e:
        pass

# Mount all present drives
for drive in drives:
    mount = mountpoint(drive)
    # Abort if folder already exists
    if path.exists(mount):
        print(f"{mount} already exists!")
        continue