• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python run_cmd.call函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中misc.run_cmd.call函数的典型用法代码示例。如果您正苦于以下问题:Python call函数的具体用法?Python call怎么用?Python call使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了call函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: create_zfs_vol

    def create_zfs_vol(self, pool_name, vol_name, swap_size=None):
        """ Creates zfs vol inside the pool
            if size is given, it should be in GB.
            If vol_name is "swap" it will be setup as a swap space """

        cmd = ["zfs", "create"]

        if swap_size:
            # If size is given, mountpoint cannot be set (zfs)
            # Round up
            swap_size = math.ceil(swap_size)
            logging.debug("Creating a zfs vol %s/%s of size %dGB", pool_name, vol_name, swap_size)
            cmd.extend(["-V", "{0}G".format(swap_size)])
        else:
            logging.debug("Creating a zfs vol %s/%s", pool_name, vol_name)
            if vol_name == "swap":
                cmd.extend(["-o", "mountpoint=none"])
            else:
                cmd.extend(["-o", "mountpoint={0}/{1}".format(DEST_DIR, vol_name)])

        cmd.append("{0}/{1}".format(pool_name, vol_name))
        call(cmd, fatal=True)

        if vol_name == "swap":
            self.create_swap(pool_name, vol_name)
开发者ID:FrankDev14,项目名称:Cnchi,代码行数:25,代码来源:zfs.py


示例2: run_mkconfig

    def run_mkconfig(self):
        """ Create grub.cfg file using grub-mkconfig """
        logging.debug("Generating grub.cfg...")

        # Make sure that /dev and others are mounted (binded).
        special_dirs.mount(self.dest_dir)

        # if self.settings.get("zfs"):
        #     # grub-mkconfig does not properly detect the ZFS filesystem,
        #     # so it is necessary to edit grub.cfg manually.
        #     zfs_pool_name = self.settings.get("zfs_pool_name")
        #     grub_cfg_path = os.path.join(self.dest_dir, "boot/grub/grub.cfg")
        #     with open(grub_cfg_path, "w") as grub_cfg:
        #         grub_cfg.write('set timeout=2\n')
        #         grub_cfg.write('set default=0\n\n')
        #         grub_cfg.write('# (0) Antergos Linux\n')
        #         grub_cfg.write('\tmenuentry "Antergos Linux (zfs)" {\n')
        #         # grub_cfg.write('\tsearch --no-floppy --label --set=root {0}\n'.format(zfs_pool_name))
        #         grub_cfg.write('\tlinux /vmlinuz-linux zfs={0} rw\n'.format(zfs_pool_name))
        #         grub_cfg.write('\tinitrd /initramfs-linux.img\n')
        #         grub_cfg.write('}\n')
        # else:
        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()
        logging.debug("Running grub-mkconfig...")
        locale = self.settings.get("locale")
        cmd = 'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
        cmd_sh = ['sh', '-c', cmd]
        if not chroot_call(cmd_sh, self.dest_dir, timeout=300):
            msg = ("grub-mkconfig does not respond. Killing grub-mount and"
                   "os-prober so we can continue.")
            logging.error(msg)
            call(['killall', 'grub-mount'])
            call(['killall', 'os-prober'])
开发者ID:imsory,项目名称:Cnchi,代码行数:34,代码来源:grub2.py


示例3: unmount_all_in_device

def unmount_all_in_device(device):
    """ Unmounts all partitions from device """

    # Unmount all swap
    cmd = ["swapon", "--show=NAME", "--noheadings"]
    swaps = call(cmd)
    swaps = swaps.split("\n")
    for name in filter(None, swaps):
        if "/dev/zram" not in name:
            call(["swapoff", name])

    # Get all mounted devices
    mount_result = call(["mount"])
    mount_result = mount_result.split("\n")

    # Umount all partitions of device
    dirs = []
    for mount in mount_result:
        if device in mount:
            try:
                directory = mount.split()[0]
                dirs.append(directory)
            except IndexError:
                pass

    for directory in dirs:
        unmount(directory)
开发者ID:Antergos,项目名称:Cnchi,代码行数:27,代码来源:auto_partition.py


示例4: freeze_unfreeze_xfs

    def freeze_unfreeze_xfs(self):
        """ Freeze and unfreeze xfs, as hack for grub(2) installing """
        if not os.path.exists("/usr/bin/xfs_freeze"):
            return

        xfs_boot = False
        xfs_root = False

        call(["sync"])
        with open("/proc/mounts") as mounts_file:
            mounts = mounts_file.readlines()
        # We leave a blank space in the end as we want to search
        # exactly for this mount points
        boot_mount_point = self.dest_dir + "/boot "
        root_mount_point = self.dest_dir + " "
        for line in mounts:
            if " xfs " in line:
                if boot_mount_point in line:
                    xfs_boot = True
                elif root_mount_point in line:
                    xfs_root = True
        if xfs_boot:
            boot_mount_point = boot_mount_point.rstrip()
            call(["xfs_freeze", "-f", boot_mount_point])
            call(["xfs_freeze", "-u", boot_mount_point])
        if xfs_root:
            call(["xfs_freeze", "-f", self.dest_dir])
            call(["xfs_freeze", "-u", self.dest_dir])
开发者ID:EntityOS,项目名称:Cnchi,代码行数:28,代码来源:loader.py


示例5: unmount_all_in_directory

def unmount_all_in_directory(dest_dir):
    """ Unmounts all devices that are mounted inside dest_dir """

    # Unmount all swap devices
    cmd = ["swapon", "--show=NAME", "--noheadings"]
    swaps = call(cmd)
    if swaps:
        swaps = swaps.split("\n")
        for name in filter(None, swaps):
            if "/dev/zram" not in name:
                call(["swapoff", name])

    # Get all mounted devices
    mount_result = call(["mount"]).split("\n")

    # Umount all devices mounted inside dest_dir (if any)
    dirs = []
    for mount in mount_result:
        if dest_dir in mount:
            try:
                directory = mount.split()[2]
                # Do not unmount dest_dir now (we will do it later)
                if directory != dest_dir:
                    dirs.append(directory)
            except IndexError:
                pass

    for directory in dirs:
        unmount(directory)

    # Now is the time to unmount the device that is mounted in dest_dir (if any)
    unmount(dest_dir)
开发者ID:EntityOS,项目名称:Cnchi,代码行数:32,代码来源:auto_partition.py


示例6: label_fs

def label_fs(fstype, part, label):
    """ Set filesystem label """
    ladic = {'ext2': 'e2label %(part)s %(label)s',
             'ext3': 'e2label %(part)s %(label)s',
             'ext4': 'e2label %(part)s %(label)s',
             'f2fs': 'blkid -s LABEL -o value %(part)s %(label)s',
             'fat': 'mlabel -i %(part)s ::%(label)s',
             'fat16': 'mlabel -i %(part)s ::%(label)s',
             'fat32': 'mlabel -i %(part)s ::%(label)s',
             'ntfs': 'ntfslabel %(part)s %(label)s',
             'jfs': 'jfs_tune -L %(label)s %(part)s',
             'reiserfs': 'reiserfstune -l %(label)s %(part)s',
             'xfs': 'xfs_admin -l %(label)s %(part)s',
             'btrfs': 'btrfs filesystem label %(part)s %(label)s',
             'swap': 'swaplabel -L %(label)s %(part)s'}

    fstype = fstype.lower()

    # OK, the below is a quick cheat.  vars() returns all variables
    # in a dictionary.  So 'part' and 'label' will be defined
    # and replaced in above dic
    if fstype in ladic:
        cmd = shlex.split(ladic[fstype] % vars())
        call(cmd)
    else:
        # Not being able to label a partition shouldn't worry us much
        logging.warning("Can't label %s (%s) with label %s", part, fstype, label)
开发者ID:Antergos,项目名称:Cnchi,代码行数:27,代码来源:filesystems.py


示例7: get_os_dict

def get_os_dict():
    """ Returns all detected OSes in a dict """
    oses = {}

    tmp_dir = tempfile.mkdtemp()

    with open("/proc/partitions", 'r') as partitions_file:
        for line in partitions_file:
            line_split = line.split()
            if len(line_split) > 0:
                device = line_split[3]
                if "sd" in device and re.search(r'\d+$', device):
                    # ok, it has sd and ends with a number
                    device = "/dev/" + device
                    call(["mount", device, tmp_dir])
                    oses[device] = _get_os(tmp_dir)
                    call(["umount", "-l", tmp_dir])
                    if oses[device] == _("unknown"):
                        # As a last resort, try reading partition info
                        # with hexdump
                        oses[device] = _get_partition_info(device)

    try:
        os.rmdir(tmp_dir)
    except OSError:
        pass

    return oses
开发者ID:Antergos,项目名称:Cnchi,代码行数:28,代码来源:bootinfo.py


示例8: do_destroy_zfs_pools

    def do_destroy_zfs_pools(self):
        """ Try to destroy existing antergos zfs pools """
        self.load_existing_pools()

        for pool_name in self.existing_pools:
            if "antergos" in pool_name.lower():
                pool_id, pool_state = self.existing_pools[pool_name]
                destroy_cmd = ['zpool', 'destroy', '-f', pool_name]
                if not call(destroy_cmd, warning=False):
                    destroy_cmd = ['zfs', 'destroy', '-R', '-f', pool_name]
                    call(destroy_cmd, warning=False)
开发者ID:FrankDev14,项目名称:Cnchi,代码行数:11,代码来源:zfs.py


示例9: close_antergos_luks_devices

def close_antergos_luks_devices():
    """ Close LUKS devices (they may have been left open because of a previous
    failed installation) """

    volumes = ["/dev/mapper/cryptAntergos", "/dev/mapper/cryptAntergosHome"]

    err_msg = "Can't close already opened LUKS devices"

    for volume in volumes:
        if os.path.exists(volume):
            cmd = ["cryptsetup", "luksClose", volume]
            call(cmd, msg=err_msg)
开发者ID:Antergos,项目名称:Cnchi,代码行数:12,代码来源:auto_partition.py


示例10: setup_luks

def setup_luks(luks_device, luks_name, luks_pass=None, luks_key=None):
    """ Setups a luks device """

    if (luks_pass is None or luks_pass == "") and luks_key is None:
        txt = "Can't setup LUKS in device {0}. A password or a key file are needed".format(luks_device)
        logging.error(txt)
        return

    # For now, we we'll use the same password for root and /home
    # If instead user wants to use a key file, we'll have two different key files.

    logging.debug("Cnchi will setup LUKS on device %s", luks_device)

    # Wipe LUKS header (just in case we're installing on a pre LUKS setup)
    # For 512 bit key length the header is 2MiB
    # If in doubt, just be generous and overwrite the first 10MiB or so
    wrapper.dd("/dev/zero", luks_device, bs=512, count=20480)

    err_msg = "Can't format and open the LUKS device {0}".format(luks_device)

    if luks_pass is None or luks_pass == "":
        # No key password given, let's create a random keyfile
        wrapper.dd("/dev/urandom", luks_key, bs=1024, count=4)

        # Set up luks with a keyfile
        cmd = [
            "cryptsetup", "luksFormat", "-q", "-c", "aes-xts-plain",
            "-s", "512", luks_device, luks_key]
        call(cmd, msg=err_msg, fatal=True)

        cmd = [
            "cryptsetup", "luksOpen", luks_device, luks_name, "-q",
            "--key-file", luks_key]
        call(cmd, msg=err_msg, fatal=True)
    else:
        # Set up luks with a password key

        luks_pass_bytes = bytes(luks_pass, 'UTF-8')

        # https://code.google.com/p/cryptsetup/wiki/Cryptsetup160
        # aes-xts-plain
        # aes-cbc-essiv:sha256
        cmd = [
            "cryptsetup", "luksFormat", "-q", "-c", "aes-xts-plain64",
            "-s", "512", "--key-file=-", luks_device]
        proc = popen(cmd, msg=err_msg, fatal=True)
        proc.communicate(input=luks_pass_bytes)

        cmd = [
            "cryptsetup", "luksOpen", luks_device, luks_name, "-q",
            "--key-file=-"]
        proc = popen(cmd, msg=err_msg, fatal=True)
        proc.communicate(input=luks_pass_bytes)
开发者ID:EntityOS,项目名称:Cnchi,代码行数:53,代码来源:auto_partition.py


示例11: get_part_sizes

    def get_part_sizes(self, disk_size, start_part_sizes=1):
        part_sizes = {"disk": disk_size, "boot": 256, "efi": 0}

        if self.gpt and self.bootloader == "grub2":
            part_sizes["efi"] = 200

        cmd = ["grep", "MemTotal", "/proc/meminfo"]
        mem_total = call(cmd)
        mem_total = int(mem_total.split()[1])
        mem = mem_total / 1024

        # Suggested sizes from Anaconda installer
        if mem < 2048:
            part_sizes["swap"] = 2 * mem
        elif 2048 <= mem < 8192:
            part_sizes["swap"] = mem
        elif 8192 <= mem < 65536:
            part_sizes["swap"] = mem // 2
        else:
            part_sizes["swap"] = 4096

        # Max swap size is 10% of all available disk size
        max_swap = disk_size * 0.1
        if part_sizes["swap"] > max_swap:
            part_sizes["swap"] = max_swap

        part_sizes["swap"] = math.ceil(part_sizes["swap"])

        other_than_root_size = start_part_sizes + part_sizes["efi"] + part_sizes["boot"] + part_sizes["swap"]
        part_sizes["root"] = disk_size - other_than_root_size

        if self.home:
            # Decide how much we leave to root and how much we leave to /home
            # Question: why 5?
            new_root_part_size = part_sizes["root"] // 5
            if new_root_part_size > MAX_ROOT_SIZE:
                new_root_part_size = MAX_ROOT_SIZE
            elif new_root_part_size < MIN_ROOT_SIZE:
                new_root_part_size = MIN_ROOT_SIZE

            if new_root_part_size >= part_sizes["root"]:
                # new_root_part_size can't be bigger than part_sizes['root'] !
                # this could happen if new_root_part_size == MIN_ROOT_SIZE but
                # our harddisk is smaller (detected using vbox)
                # Should we fail here or install without a separated /home partition?
                logging.warning("There's not enough free space to have a separate /home partition")
                self.home = False
                part_sizes["home"] = 0
            else:
                part_sizes["home"] = part_sizes["root"] - new_root_part_size
                part_sizes["root"] = new_root_part_size
        else:
            part_sizes["home"] = 0

        part_sizes["lvm_pv"] = part_sizes["swap"] + part_sizes["root"] + part_sizes["home"]

        for part in part_sizes:
            part_sizes[part] = int(part_sizes[part])

        return part_sizes
开发者ID:Antergos,项目名称:Cnchi,代码行数:60,代码来源:auto_partition.py


示例12: init_device

    def init_device(self, device_path, scheme="GPT"):
        """ Initialize device """

        logging.debug("Zapping device %s...", device_path)

        offset = 20480

        # Zero out all GPT and MBR data structures
        wrapper.sgdisk("zap-all", device_path)

        # Clear all magic strings/signatures
        # Wipe out first "offset" sectors
        wrapper.dd("/dev/zero", device_path, bs=512, count=offset)

        # Clear the end "offset" sectors of the disk, too.
        try:
            seek = int(call(["blockdev", "--getsz", device_path])) - offset
            wrapper.dd("/dev/zero", device_path, bs=512, count=offset, seek=seek)
        except ValueError as ex:
            logging.warning(ex)

        if not wrapper.wipefs(device_path, fatal=False):
            pname, pid, _n = self.get_pool_id('_', include_offline=True)

            if self.do_destroy_zfs_pool():
                call(["udevadm", "settle"])
                call(["sync"])
                wrapper.wipefs(device_path, fatal=True)

        if scheme == "GPT":
            # Create fresh GPT table
            wrapper.sgdisk("clear", device_path)

            # Inform the kernel of the partition change.
            # Needed if the hard disk had a MBR partition table.
            call(["partprobe", device_path])
        else:
            # Create fresh MBR table
            wrapper.parted_mklabel(device_path, "msdos")

        """
        if self.zfs_options["encrypt_disk"]:
            from installation import auto_partition as ap
            vol_name = device_path.split("/")[-1]
            ap.setup_luks(
                luks_device=device_path,
                luks_name=vol_name,
                luks_pass=self.zfs_options["encrypt_password"])
            self.settings.set("use_luks", True)
        """

        call(["sync"])
开发者ID:imsory,项目名称:Cnchi,代码行数:52,代码来源:zfs.py


示例13: get_info

def get_info(part):
    """ Get partition info using blkid """

    ret = ''
    partdic = {}
    # Do not try to get extended partition info
    if part and not misc.is_partition_extended(part):
        # -c /dev/null means no cache
        cmd = ['blkid', '-c', '/dev/null', part]
        call(cmd)

        for info in ret.split():
            if '=' in info:
                info = info.split('=')
                partdic[info[0]] = info[1].strip('"')

    return partdic
开发者ID:Antergos,项目名称:Cnchi,代码行数:17,代码来源:filesystems.py


示例14: get_type

def get_type(part):
    """ Get filesystem type using blkid """
    ret = ''
    if part and not misc.is_partition_extended(part):
        cmd = ['blkid', '-o', 'value', '-s', 'TYPE', part]
        ret = call(cmd)

    return ret
开发者ID:Antergos,项目名称:Cnchi,代码行数:8,代码来源:filesystems.py


示例15: run_mkconfig

    def run_mkconfig(self):
        """ Create grub.cfg file using grub-mkconfig """
        logging.debug("Generating grub.cfg...")

        # Make sure that /dev and others are mounted (binded).
        special_dirs.mount(self.dest_dir)

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()
        logging.debug("Running grub-mkconfig...")
        locale = self.settings.get("locale")
        cmd = "LANG={0} grub-mkconfig -o /boot/grub/grub.cfg".format(locale)
        cmd_sh = ["sh", "-c", cmd]
        if not chroot_call(cmd_sh, self.dest_dir, timeout=300):
            msg = "grub-mkconfig does not respond. Killing grub-mount and" "os-prober so we can continue."
            logging.error(msg)
            call(["killall", "grub-mount"])
            call(["killall", "os-prober"])
开发者ID:Antergos,项目名称:Cnchi,代码行数:18,代码来源:grub2.py


示例16: set_keymap

    def set_keymap(self, layout, variant=None):
        self.settings.keyboard_layout = layout
        self.settings.keyboard_variant = variant

        # setxkbmap sets the keyboard layout for the current X session only
        cmd = ['setxkbmap', '-layout', layout]

        if variant:
            cmd.extend(['-variant', variant])
            txt = 'Set keyboard to "{0}" ({1}), variant "{2}" ({3})'
            txt = txt.format('', layout, '', variant)
        else:
            txt = 'Set keyboard to "{0}" ({1})'.format('', layout)

        try:
            call(cmd)
            self.logger.debug(txt)
        except (OSError, subprocess.CalledProcessError) as setxkbmap_error:
            self.logger.warning(setxkbmap_error)
开发者ID:MichaelTunnell,项目名称:Cnchi,代码行数:19,代码来源:keymap.py


示例17: create_zfs_vol

    def create_zfs_vol(self, pool_name, vol_name, size):
        """ Creates zfs vol inside the pool
            size is in GB """

        # Round up
        size = math.ceil(size)
        logging.debug(
            "Creating a zfs vol %s/%s of size %dGB",
            pool_name,
            vol_name,
            size)
        cmd = [
            "zfs", "create",
            "-V", "{0}G".format(size),
            "-b", str(os.sysconf("SC_PAGE_SIZE")),
            "-o", "primarycache=metadata",
            "-o", "checksum=off",
            "-o", "com.sun:auto-snapshot=false",
            "{0}/{1}".format(pool_name, vol_name)]
        call(cmd, fatal=True)
开发者ID:imsory,项目名称:Cnchi,代码行数:20,代码来源:zfs.py


示例18: create_swap

    def create_swap(self, pool_name, vol_name):
        """ mkswap on a zfs zvol """

        zvol = "{0}/{1}".format(pool_name, vol_name)

        cmd = ["zfs", "set", "com.sun:auto-snapshot=false", zvol]
        call(cmd)

        cmd = ["zfs", "set", "sync=always", zvol]
        call(cmd)

        path = "/dev/zvol/{0}/swap".format(pool_name)
        if os.path.exists(path):
            logging.debug("Formatting swap (%s)", path)
            cmd = ["mkswap", "-f", path]
            if call(cmd):
                self.devices["swap"] = path
                self.fs_devices[path] = "swap"
                self.mount_devices["swap"] = path
        else:
            logging.warning("Can't find %s to create swap on it", path)
开发者ID:FrankDev14,项目名称:Cnchi,代码行数:21,代码来源:zfs.py


示例19: get_info

def get_info(part):
    """ Get partition info using blkid """

    ret = ''
    partdic = {}
    # Do not try to get extended partition info
    if part and not misc.is_partition_extended(part):
        # -c /dev/null means no cache
        cmd = ['blkid', '-c', '/dev/null', part]
        call(cmd)
        try:

            ret = subprocess.check_output(cmd).decode().strip()
        except subprocess.CalledProcessError as err:
            logging.warning("Error running %s: %s", err.cmd, err.output)

        for info in ret.split():
            if '=' in info:
                info = info.split('=')
                partdic[info[0]] = info[1].strip('"')

    return partdic
开发者ID:EntityOS,项目名称:Cnchi,代码行数:22,代码来源:fs_module.py


示例20: prepare_pacman_keyring

    def prepare_pacman_keyring():
        """ Add gnupg pacman files to installed system """

        dirs = ["var/cache/pacman/pkg", "var/lib/pacman"]
        for pacman_dir in dirs:
            mydir = os.path.join(DEST_DIR, pacman_dir)
            os.makedirs(mydir, mode=0o755, exist_ok=True)

        # Be sure that haveged is running (liveCD)
        # haveged is a daemon that generates system entropy; this speeds up
        # critical operations in cryptographic programs such as gnupg
        # (including the generation of new keyrings)
        cmd = ["systemctl", "start", "haveged"]
        call(cmd)

        # Delete old gnupg files
        dest_path = os.path.join(DEST_DIR, "etc/pacman.d/gnupg")
        cmd = ["rm", "-rf", dest_path]
        call(cmd)
        os.mkdir(dest_path)

        # Tell pacman-key to regenerate gnupg files
        # Initialize the pacman keyring
        cmd = ["pacman-key", "--init", "--gpgdir", dest_path]
        call(cmd)

        # Load the signature keys
        cmd = ["pacman-key", "--populate", "--gpgdir", dest_path, "archlinux", "antergos"]
        call(cmd)

        # path = os.path.join(DEST_DIR, "root/.gnupg/dirmngr_ldapservers.conf")
        # Run dirmngr
        # https://bbs.archlinux.org/viewtopic.php?id=190380
        with open(os.devnull, "r") as dev_null:
            cmd = ["dirmngr"]
            call(cmd, stdin=dev_null)
开发者ID:karasu,项目名称:Cnchi,代码行数:36,代码来源:install.py



注:本文中的misc.run_cmd.call函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.toString函数代码示例发布时间:2022-05-27
下一篇:
Python json.loads函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap