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

Python linux.system函数代码示例

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

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



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

示例1: on_init

    def on_init(self, *args, **kwargs):
        bus.on("before_hello", self.on_before_hello)
        bus.on("before_host_init", self.on_before_host_init)
        bus.on("before_restart", self.on_before_restart)
        bus.on("before_reboot_finish", self.on_before_reboot_finish)

        try:
            system(('ntpdate', '-u', '0.amazon.pool.ntp.org'))
        except:
            pass

        msg_service = bus.messaging_service
        producer = msg_service.get_producer()
        producer.on("before_send", self.on_before_message_send)

        if not os_dist.windows_family and not __node__.get('hostname'):
            # Set the hostname to this instance's public hostname
            try:
                hostname_as_pubdns = int(__ec2__['hostname_as_pubdns'])
            except:
                hostname_as_pubdns = True

            if hostname_as_pubdns:
                pub_hostname = self._platform.get_public_hostname()
                self._logger.debug('Setting hostname to %s' % pub_hostname)
                system2("hostname " + pub_hostname, shell=True)

        if disttool.is_ubuntu():
            # Ubuntu cloud-init scripts may disable root ssh login
            for path in ('/etc/ec2-init/ec2-config.cfg', '/etc/cloud/cloud.cfg'):
                if os.path.exists(path):
                    c = None
                    with open(path, 'r') as fp:
                        c = fp.read()
                    c = re.sub(re.compile(r'^disable_root[^:=]*([:=]).*', re.M), r'disable_root\1 0', c)
                    with open(path, 'w') as fp:
                        fp.write(c)

        if not linux.os.windows_family:
            # Add server ssh public key to authorized_keys
            ssh_key = self._platform.get_ssh_pub_key()
            if ssh_key:
                add_authorized_key(ssh_key)

        # Mount ephemeral devices
        # Seen on eucalyptus:
        #       - fstab contains invalid fstype and `mount -a` fails
        if self._platform.name == 'eucalyptus':
            mtab = mount.mounts()
            fstab = mount.fstab()
            for device in self._platform.instance_store_devices:
                if os.path.exists(device) and device in fstab and device not in mtab:
                    entry = fstab[device]
                    try:
                        mount.mount(device, entry.mpoint, '-o', entry.options)
                    except:
                        self._logger.warn(sys.exc_info()[1])
        else:
            if not os_dist.windows_family:
                system2('mount -a', shell=True, raise_exc=False)
开发者ID:AnyBucket,项目名称:scalarizr,代码行数:60,代码来源:lifecycle.py


示例2: upload

def upload(step):
        key_path = os.environ.get('GCS_KEY')
        with open(key_path) as f:
            key = base64.b64encode(f.read())
        access_data = dict(service_account_name='[email protected]', key=key)

        gcs.bus = mock.MagicMock()
        gcs.bus.platform.get_access_data = lambda k: access_data[k]

        gsm = GoogleServiceManager(gcs.bus.platform,
                "storage", "v1beta2", *STORAGE_FULL_SCOPE)

        gcs.bus.platform.get_numeric_project_id.return_value = '876103924605'
        gcs.bus.platform.new_storage_client = lambda: gsm.get_service()

        world.gcs = gcs.GCSFileSystem()
        world.tmpdir = tempfile.mkdtemp()
        # make random file
        tmp_file = os.path.join(world.tmpdir, 'test_file')
        system("dd if=/dev/urandom of=%s bs=1M count=1" % tmp_file, shell=True)
        world.src_md5 = system('md5sum %s' % tmp_file, shell=True)[0]
        LOG.info('MD5 : %s' % world.src_md5)
        world.bucket_name = 'scalr-tests-%s' % str(uuid.uuid4())[:8]
        LOG.info('Bucket name: %s' % world.bucket_name)

        world.dst_path = 'gcs://%s/test_file' % world.bucket_name

        try:
            world.gcs.ls(world.dst_path)
        except:
            pass
        else:
            raise Exception('Destination path already exist')
        world.gcs.put(tmp_file, world.dst_path)
        os.unlink(tmp_file)
开发者ID:AnyBucket,项目名称:scalarizr,代码行数:35,代码来源:gcs.py


示例3: create_volume

    def create_volume(self, **params):
        size = params.get('size')
        snapshot_id = params.get('snapshot')

        assert size or snapshot_id, 'Not enough params to create volume'
        if snapshot_id:
            snapshot = self.describe_snapshot(snapshot_id)
            if size:
                if int(size) < int(snapshot['size']):
                    raise StorageError('Size you specified is smaller than snapshot')
        else:
            # Size in Gigabytes
            size = int(size)

        id = 'vol-%s' % str(uuid.uuid4())[:7]

        lvm2.lvcreate(vg_name, name=id, size='%sG' % size)
        lvinfo = lvm2.lvs(lvm2.lvpath(vg_name, id)).values()[0]
        device = os.path.realpath(lvinfo.lv_path)
        if snapshot_id:
            # Apply snapshot
            system('dd if=%s of=%s' % (self._get_snapshot_path(snapshot_id), device), shell=True)

        stat = os.stat(device)
        maj, min = (os.major(stat.st_rdev), os.minor(stat.st_rdev))

        self.volumes[id] = dict(id=id, attached_to=None, maj=maj, min=min,
                      host_path=device, size=str(size), source_snapshot=snapshot_id)
        return self.volumes[id]
开发者ID:AnyBucket,项目名称:scalarizr,代码行数:29,代码来源:storage.py


示例4: check

    def check(self):
        if linux.os['family'] in ('RedHat', 'Oracle') and linux.os['version'] >= (6, 0):
            # Avoid "Can't locate Time/HiRes.pm in @INC"
            # with InnoDB Backup Utility v1.5.1-xtrabackup
            pkgmgr.installed('perl-Time-HiRes')         

        mgr = pkgmgr.package_mgr()
        if not 'percona' in mgr.repos():
            if linux.os['family'] in ('RedHat', 'Oracle'):
                url = 'http://www.percona.com/downloads/percona-release/percona-release-0.0-1.%s.rpm' % linux.os['arch']
                pkgmgr.YumPackageMgr().localinstall(url)
                if linux.os.amazon:
                    linux.system(("sed -i 's/\$releasever/latest/g' "
                                    "/etc/yum.repos.d/Percona.repo"), shell=True)
            else:
                try:
                    codename = linux.os['lsb_codename']
                except KeyError:
                    codename = linux.ubuntu_release_to_codename[linux.os['lsb_release']]
                pkgmgr.apt_source(
                        'percona.list', 
                        ['deb http://repo.percona.com/apt %s main' % codename],
                        gpg_keyserver='hkp://keys.gnupg.net',
                        gpg_keyid='CD2EFD2A')
            mgr.updatedb()
        if software.mysql_software_info().version < (5, 5):
            self.package = 'percona-xtrabackup-21'
        else:
            self.package = 'percona-xtrabackup'

        return super(PerconaExec, self).check()
开发者ID:chenleji,项目名称:scalarizr,代码行数:31,代码来源:mysql2.py


示例5: apt_source

def apt_source(name, sources, gpg_keyserver=None, gpg_keyid=None):
    '''
    @param sources: list of apt sources.list entries.
    Example:
            ['deb http://repo.percona.com/apt ${codename} main',
            'deb-src http://repo.percona.com/apt ${codename} main']
            All ${var} templates should be replaced with
            scalarizr.linux.os['var'] substitution
    if gpg_keyserver:
            apt-key adv --keyserver ${gpg_keyserver} --recv ${gpg_keyid}
    Creates file /etc/apt/sources.list.d/${name}
    '''
    if linux.os['family'] in ('RedHat', 'Oracle'):
        return

    def _vars(s):
        vars_ = re.findall('\$\{.+?\}', s)
        return map((lambda(name): name[2:-1]), vars_) #2 is len of '${'

    def _substitude(s):
        for var in _vars(s):
            s = s.replace('${'+var+'}', linux.os[var])
        return s

    prepared_sources = map(_substitude, sources)
    with open('/etc/apt/sources.list.d/' + name, 'w+') as fp:
        fp.write('\n'.join(prepared_sources))

    if gpg_keyserver and gpg_keyid:
        if gpg_keyid not in linux.system(('apt-key', 'list'))[0]:
            linux.system(('apt-key', 'adv',
                                      '--keyserver', gpg_keyserver,
                                      '--recv', gpg_keyid),
                                     raise_exc=False)
开发者ID:notbrain,项目名称:scalarizr,代码行数:34,代码来源:pkgmgr.py


示例6: on_start

 def on_start(self):
     if __node__['state'] == 'running':
         lfrp = bus.queryenv_service.list_farm_role_params(farm_role_id=__node__['farm_role_id'])['params']
         self._data = lfrp.get('router', {})
         if self._data:
             self._configure()
         else:
             linux.system('/etc/init.d/nginx start', shell=True, raise_exc=False)
开发者ID:chenleji,项目名称:scalarizr,代码行数:8,代码来源:router.py


示例7: rmloop

def rmloop(device):
    try:
        system((LOSETUP_EXEC, '-d', device))
    except LinuxError, e:
        if 'No such device or address' in e.err:
            ''' Silently pass non-existed loop removal '''
            pass
        else:
            raise
开发者ID:chenleji,项目名称:scalarizr,代码行数:9,代码来源:loop.py


示例8: setup

def setup(feat):
    if feat.name == FEATURE:
        p = mock.patch.multiple(s3.S3FileSystem,
                        _bucket_location=mock.Mock(return_value=''),
                        _get_connection=mock.Mock(side_effect=lambda: boto.connect_s3()))
        p.start()
        world.s3_patcher = p
        world.mysql_init = mysql_svc.MysqlInitScript()
        linux.system('mysqladmin create xtrabackup', shell=True, raise_exc=False)
开发者ID:AnyBucket,项目名称:scalarizr,代码行数:9,代码来源:percona_xtrabackup.py


示例9: rsync

def rsync(src, dst, **long_kwds):
    if not os.path.exists('/usr/bin/rsync'):
        pkgmgr.installed('rsync')
    system(['sync'])
    output = system(build_cmd_args(executable='/usr/bin/rsync',
                                   long=long_kwds,
                                   params=[src, dst],
                                   duplicate_keys=True))
    system(['sync'])
    return output
开发者ID:AnyBucket,项目名称:scalarizr,代码行数:10,代码来源:rsync.py


示例10: umount

def umount(device_or_mpoint, **long_kwds):
    args = linux.build_cmd_args(
            executable='/bin/umount',
            short=('-f', device_or_mpoint),
            long=long_kwds)
    try:
        linux.system(args, error_text='Cannot umount %s' % device_or_mpoint)
    except linux.LinuxError, e:
        if 'not mounted' in e.err or 'not found' in e.err:
            return
        raise
开发者ID:chenleji,项目名称:scalarizr,代码行数:11,代码来源:mount.py


示例11: _create_spec_devices

    def _create_spec_devices(self, root):
        nodes = (
                'console c 5 1',
                'null c 1 3',
                'zero c 1 5',
                'tty c 5 0',
        )

        for node in nodes:
            args = node.split()
            args[0] = os.path.join(root, 'dev', args[0])
            system(' '.join(['mknod'] + args), shell=True)
开发者ID:notbrain,项目名称:scalarizr,代码行数:12,代码来源:rebundle.py


示例12: mount

def mount(device, mpoint, *short_args, **long_kwds):
	args = linux.build_cmd_args(
		executable='/bin/mount',
		short=short_args, 
		long=long_kwds, 
		params=(device, mpoint)
	)
	try:
		msg = 'Cannot mount %s -> %s' % (device, mpoint)
		linux.system(args, error_text=msg)
	except linux.LinuxError, e:
		if 'you must specify the filesystem type' in e.err:
			raise NoFileSystem(device)
		raise
开发者ID:golovast,项目名称:scalarizr,代码行数:14,代码来源:mount.py


示例13: uninstall

    def uninstall(self):
        pid = None
        if not linux.os.windows:
            # Prevent scalr-upd-client restart when updating from old versions
            # package 'scalr-upd-client' replaced with 'scalarizr'
            pid_file = "/var/run/scalr-upd-client.pid"
            if os.path.exists(pid_file):
                with open(pid_file) as fp:
                    pid = fp.read().strip()
                with open(pid_file, "w") as fp:
                    fp.write("0")
        try:
            self.pkgmgr.removed(self.package)
            if not linux.os.windows:
                if linux.os.redhat_family:
                    installed_ver = self.pkgmgr.info("scalarizr")["installed"]
                    cmd = "rpm -e scalarizr"
                    if installed_ver and distutils.version.LooseVersion(installed_ver) < "0.7":
                        # On CentOS 5 there is a case when scalarizr-0.6.24-5 has error
                        # in preun scriplet and cannot be uninstalled
                        cmd += " --noscripts"
                    linux.system(cmd, shell=True, raise_exc=False)
                else:
                    self.pkgmgr.removed("scalarizr", purge=True)
                self.pkgmgr.removed("scalarizr-base", purge=True)  # Compatibility with BuildBot packaging
                updclient_pkginfo = self.pkgmgr.info("scalr-upd-client")
                if updclient_pkginfo["installed"]:
                    # Only latest package don't stop scalr-upd-client in postrm script
                    if updclient_pkginfo["candidate"]:
                        if linux.os.debian_family:
                            cmd = ("-o Dpkg::Options::=--force-confmiss " "install scalr-upd-client={0}").format(
                                updclient_pkginfo["candidate"]
                            )
                            self.pkgmgr.apt_get_command(cmd)
                        else:
                            self.pkgmgr.install("scalr-upd-client", updclient_pkginfo["candidate"])
                    try:
                        self.pkgmgr.removed("scalr-upd-client", purge=True)
                    except:
                        if linux.os.redhat_family:
                            linux.system("rpm -e --noscripts scalr-upd-client", shell=True, raise_exc=False)
                        else:
                            raise

        finally:
            if pid:
                with open(pid_file, "w+") as fp:
                    fp.write(pid)
开发者ID:chenleji,项目名称:scalarizr,代码行数:48,代码来源:api.py


示例14: innobackupex

def innobackupex(*params, **long_kwds):
	if not os.path.exists('/usr/bin/innobackupex'):
		pkgmgr.installed('percona-xtrabackup')
	return linux.system(linux.build_cmd_args(
			executable='/usr/bin/innobackupex', 
			long=long_kwds, 
			params=params))
开发者ID:golovast,项目名称:scalarizr,代码行数:7,代码来源:mysql2.py


示例15: dd

def dd(**kwds):
    short = []
    for k, v in kwds.items():
        short.append('%s=%s' % (k, v))
    return linux.system(linux.build_cmd_args(
                executable='/bin/dd',
                short=short))
开发者ID:chenleji,项目名称:scalarizr,代码行数:7,代码来源:coreutils.py


示例16: blkid

def blkid(device_path, **kwargs):
    if not os.path.exists(device_path):
        raise Exception("Device %s doesn't exist")

    ret = dict()

    args = ['/sbin/blkid']
    for k, v in kwargs.items():
        if type(v) == bool:
            args.append('-%s' % k)
        else:
            args.extend(['-%s' % k, str(v)])

    args.append(device_path)

    out = linux.system(args, raise_exc=False)[0]
    if out.strip():
        pairs = out.split()[1:]
        for line in pairs:
            line = line.strip()
            if line:
                k, v = line.split('=', 1)
                ret[k.lower()] = v[1:-1]

    return ret
开发者ID:chenleji,项目名称:scalarizr,代码行数:25,代码来源:coreutils.py


示例17: listloop

def listloop():
    ret = {}
    loop_lines = system((LOSETUP_EXEC, '-a'))[0].strip().splitlines()
    for loop_line in loop_lines:
        words = loop_line.split()
        ret[words[0][:-1]] = words[-1][1:-1]
    return ret
开发者ID:chenleji,项目名称:scalarizr,代码行数:7,代码来源:loop.py


示例18: mysqldump

def mysqldump(*databases, **long_kwds):
    output = long_kwds.pop("output", None)
    cmd = linux.build_cmd_args(executable="/usr/bin/mysqldump", long=long_kwds, params=databases)
    kwds = {}
    if output:
        kwds["stdout"] = open(output, "w+")
    return linux.system(cmd, **kwds)
开发者ID:pombredanne,项目名称:scalarizr,代码行数:7,代码来源:mysql2.py


示例19: on_init

    def on_init(self, *args, **kwargs):
        bus.on("before_hello", self.on_before_hello)
        bus.on("before_host_init", self.on_before_host_init)
        bus.on("before_restart", self.on_before_restart)
        bus.on("before_reboot_finish", self.on_before_reboot_finish)

        try:
            system(('ntpdate', '-u', '0.amazon.pool.ntp.org'))
        except:
            pass

        msg_service = bus.messaging_service
        producer = msg_service.get_producer()
        producer.on("before_send", self.on_before_message_send)

        if not os_dist.windows_family and not __node__['base'].get('hostname'):
            # Set the hostname to this instance's public hostname
            try:
                hostname_as_pubdns = int(__ec2__['hostname_as_pubdns'])
            except:
                hostname_as_pubdns = True

            if hostname_as_pubdns:
                pub_hostname = self._platform.get_public_hostname()
                self._logger.debug('Setting hostname to %s' % pub_hostname)
                system2("hostname " + pub_hostname, shell=True)

        if linux.os.ubuntu:
            # Ubuntu cloud-init scripts may disable root ssh login
            for path in ('/etc/ec2-init/ec2-config.cfg', '/etc/cloud/cloud.cfg'):
                if os.path.exists(path):
                    c = None
                    with open(path, 'r') as fp:
                        c = fp.read()
                    c = re.sub(re.compile(r'^disable_root[^:=]*([:=]).*', re.M), r'disable_root\1 0', c)
                    with open(path, 'w') as fp:
                        fp.write(c)

        if not linux.os.windows_family:
            # Add server ssh public key to authorized_keys
            ssh_key = self._platform.get_ssh_pub_key()
            if ssh_key:
                add_authorized_key(ssh_key)

            system2('mount -a', shell=True, raise_exc=False)
开发者ID:chenleji,项目名称:scalarizr,代码行数:45,代码来源:lifecycle.py


示例20: repos

 def repos(self):
     ret = []
     repo_re = re.compile(r'Repo-id\s+:\s(.*)')
     out = linux.system(('/usr/bin/yum', 'repolist', '--verbose'))[0]
     for line in out.splitlines():
         m = repo_re.search(line)
         if m:
             ret.append(m.group(1))
     return map(string.lower, ret)
开发者ID:notbrain,项目名称:scalarizr,代码行数:9,代码来源:pkgmgr.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python storage2.volume函数代码示例发布时间:2022-05-27
下一篇:
Python linux.build_cmd_args函数代码示例发布时间: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