python类getoutput()的实例源码

rcommon.py 文件源码 项目:rtools 作者: malokch 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def getConfig(cfgname):
    cfg = globals()[cfgname]

    # Scan the ip of configuration
    if cfg:
        if cfg['host'].startswith('-cmd-'):
            cmd = cfg['host'][5:]
            cfg['host'] = commands.getoutput(cmd)

        elif cfg['host'].startswith('-func-'):
            func_name = cfg['host'][6:]
            func = globals()[func_name]
            cfg['host'] = func()

    print('IP[%s]: %s' % (cfgname,cfg['host']))

    return cfg
test_01_DomainManager.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def getChildren(parentPid):
    process_listing = commands.getoutput('ls /proc').split('\n')
    children = []
    for entry in process_listing:
        try:
            filename = '/proc/'+entry+'/status'
            fp = open(filename,'r')
            stuff=fp.read()
            fp.close()
            rows = stuff.split('\n')
            for row in rows:
                if row[:4]=='PPid':
                    PPid = int(row.split(':')[1][1:])
                    if PPid == parentPid:
                        children.append(int(entry))
                        break
        except:
            continue
    return children
test_01_DeviceManager.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def getChildren(parentPid):
    process_listing = commands.getoutput('ls /proc').split('\n')
    children = []
    for entry in process_listing:
        try:
            filename = '/proc/'+entry+'/status'
            fp = open(filename,'r')
            stuff=fp.read()
            fp.close()
            rows = stuff.split('\n')
            for row in rows:
                if row[:4]=='PPid':
                    PPid = int(row.split(':')[1][1:])
                    if PPid == parentPid:
                        children.append(int(entry))
                        break
        except:
            continue
    return children
test_04_ApplicationRegistrar.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def getChildren(parentPid):
    process_listing = commands.getoutput('ls /proc').split('\n')
    children = []
    for entry in process_listing:
        try:
            filename = '/proc/'+entry+'/status'
            fp = open(filename,'r')
            stuff=fp.read()
            fp.close()
            rows = stuff.split('\n')
            for row in rows:
                if row[:4]=='PPid':
                    PPid = int(row.split(':')[1][1:])
                    if PPid == parentPid:
                        children.append(int(entry))
                        break
        except:
            continue
    return children
test_04_ApplicationRegistrar.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getProcessName(pid):
    str_pid = str(pid)
    process_listing = commands.getoutput('ls /proc').split('\n')
    Name = ''
    for entry in process_listing:
        if entry == str_pid:
            try:
                filename = '/proc/'+entry+'/status'
                fp = open(filename,'r')
                stuff=fp.read()
                fp.close()
                lines = stuff.split('\n')
                for line in lines:
                    if line[:4]=='Name':
                        Name = line.split(':')[1][1:]
                        return Name
            except:
                continue
        else:
            continue
    return Name
test_04_ApplicationFactory.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getProcessName(pid):
    str_pid = str(pid)
    process_listing = commands.getoutput('ls /proc').split('\n')
    Name = ''
    for entry in process_listing:
        if entry == str_pid:
            try:
                filename = '/proc/'+entry+'/status'
                fp = open(filename,'r')
                stuff=fp.read()
                fp.close()
                lines = stuff.split('\n')
                for line in lines:
                    if line[:4]=='Name':
                        Name = line.split(':')[1][1:]
                        return Name
            except:
                continue
        else:
            continue
    return Name
test_09_HardFail.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def getChildren(parentPid):
    process_listing = commands.getoutput('ls /proc').split('\n')
    children = []
    for entry in process_listing:
        try:
            filename = '/proc/'+entry+'/status'
            fp = open(filename,'r')
            stuff=fp.read()
            fp.close()
            rows = stuff.split('\n')
            for row in rows:
                if row[:4]=='PPid':
                    PPid = int(row.split(':')[1][1:])
                    if PPid == parentPid:
                        children.append(int(entry))
                        break
        except:
            continue
    return children
test_04_Net.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def getProcessName(pid):
    str_pid = str(pid)
    process_listing = commands.getoutput('ls /proc').split('\n')
    Name = ''
    for entry in process_listing:
        if entry == str_pid:
            try:
                filename = '/proc/'+entry+'/status'
                fp = open(filename,'r')
                stuff=fp.read()
                fp.close()
                lines = stuff.split('\n')
                for line in lines:
                    if line[:4]=='Name':
                        Name = line.split(':')[1][1:]
                        return Name
            except:
                continue
        else:
            continue
    return Name
airmode.py 文件源码 项目:airmode 作者: wi-fi-analyzer 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def slot_autoload_victim_clients(self):

        # clear
        self.combo_wep_mac_cfrag.clear()
        self.combo_wpa_mac_hand.clear()

        # check *.csv files
        if not glob.glob(config_dir + "*.csv"):
            self.output("no csv files in " + config_dir, 1)
            return

        # open dump file
        dump_file = commands.getoutput("cat " + config_dir + "*.csv | egrep -e '^[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}.+[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2},' | grep " + self.ac + " | tr ',' ' ' | awk ' { print $1 } '")
        dump_file = dump_file.split('\n')        

        for mac in dump_file:
            self.combo_wep_mac_cfrag.insertItem(0, mac)
            self.combo_wpa_mac_hand.insertItem(0, mac)

    #
    # Add cracked key to database
    #
airmode.py 文件源码 项目:airmode 作者: wi-fi-analyzer 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def slot_autoload_victim_clients(self):

        # clear
        self.combo_wep_mac_cfrag.clear()
        self.combo_wpa_mac_hand.clear()

        # check *.csv files
        if not glob.glob(config_dir + "*.csv"):
            self.output("no csv files in " + config_dir, 1)
            return

        # open dump file
        dump_file = commands.getoutput("cat " + config_dir + "*.csv | egrep -e '^[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}.+[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2}:[0-9a-fA-F]{2,2},' | grep " + self.ac + " | tr ',' ' ' | awk ' { print $1 } '")
        dump_file = dump_file.split('\n')        

        for mac in dump_file:
            self.combo_wep_mac_cfrag.insertItem(0, mac)
            self.combo_wpa_mac_hand.insertItem(0, mac)

    #
    # Add cracked key to database
    #
kyoyue.py 文件源码 项目:workflows.kyoyue 作者: wizyoung 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def ping_ip(idx, ip):
    ''' ping 3 ????ip, 3?????3s??????????
        ?? 3 ? ping ????

        param:
            idx: server??
            ip: ip??
    '''
    ping_info = commands.getoutput('ping -c 3 -t 3 ' + ip)
    connected = re.findall(r'\b(\d)\b packets received', ping_info)
    if connected[0] == '0':  # fail
        return [idx, float('inf'), '0']
    else:
        avg_time = float(re.findall(
            r'stddev = [\d|.]+/([\d|.]+)', ping_info)[0])
        return [idx, avg_time, connected[0]]
analize.py 文件源码 项目:mlnx-project-config 作者: Mellanox 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def main(log_dir='.'):

    # Check stack.sh status
    rm = 'stack_failed'
    log = "%s/%s/logs/stack.sh.log.gz" % ( log_dir, known_issues[rm]['file'])
    last_line = commands.getoutput('tail -n1 %s ' % log)
    if last_line.find(known_issues[rm]['pattern']) >= 0:
        send_email(rm)
    del known_issues[rm]


    for rm, details in known_issues.iteritems():
        try:
            log = "%s/%s" % ( log_dir, details['file'])
            print ("Checking %s for %s" % (log, details['pattern']))
            if details['pattern'] in open(log).read():
                print "RM#%s happened again in %s" % (rm, log_dir)
                send_email(rm)
        except Exception as e:
            print "Exception %s" % ( e )
            pass
xc_rsu_common.py 文件源码 项目:OpenXCAccessory 作者: openxc 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_chd_mac_addr(self):
        #get the ip address of cw-llc interface
        intf = 'cw-llc'
        #cmd_op = commands.getoutput("ifconfig | grep " + intf ).split()
        cmd_op = commands.getoutput("ifconfig | grep " + intf )
        if (cmd_op.find('HWaddr')) != -1:
          tokens = cmd_op.split()
          mac_addr = tokens[tokens.index('HWaddr') + 1]
          return mac_addr

        else:
          return None

#-----------------------------------------------------------------------
# Get ip address for COHDA interface 
#-----------------------------------------------------------------------
xc_rsu_common.py 文件源码 项目:OpenXCAccessory 作者: openxc 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def modem_available(self):
         intf = 'cw-llc'
         intf_ip = commands.getoutput("ip address show dev " + intf).split()
         intf_ip = intf_ip[intf_ip.index('inet') + 1].split('/')[0]

         intf_ip = self.get_chd_ip_addr()


         if (not intf_ip is None):
       # JMA add dsrc_led
       self.dsrc_led.on()
           return 1
         else: 
           return 0

#-----------------------------------------------------------------------
# Connecto 801.110 modem and open UDP connections for Tx and Rx
#-----------------------------------------------------------------------
email.py 文件源码 项目:pipeline 作者: liorbenhorin 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def detect_desktop_environment():
        '''Checks for known desktop environments

        Return the desktop environments name, lowercase (kde, gnome, xfce)
        or "generic"

        '''

        desktop_environment = 'generic'

        if os.environ.get('KDE_FULL_SESSION') == 'true':
            desktop_environment = 'kde'
        elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
            desktop_environment = 'gnome'
        else:
            try:
                info = commands.getoutput('xprop -root _DT_SAVE_MODE')
                if ' = "xfce4"' in info:
                    desktop_environment = 'xfce'
            except (OSError, RuntimeError):
                pass

        return desktop_environment
bitmask.py 文件源码 项目:bitmask-dev 作者: leapcode 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def initial_run(context):
    if context.mode == 'virtualenv':
        cmd = commands.getoutput('which bitmaskctl')
        # print("CMD PATH", cmd)
        commands.getoutput('bitmaskctl stop')
        # TODO: fix bitmaskctl to only exit once bitmaskd has stopped
        time.sleep(2)
        _initialize_home_path()
        commands.getoutput('bitmaskctl start')
        time.sleep(1)
    elif context.mode in ('bundle', 'bundle-ci'):
        commands.getoutput(context.bundle_path)
        time.sleep(2)
    tokenpath = os.path.join(get_path_prefix(), 'leap', 'authtoken')
    token = open(tokenpath).read().strip()
    context.login_url = "http://localhost:7070/#%s" % token
tbench.py 文件源码 项目:avocado-misc-tests 作者: avocado-framework-tests 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test(self):
        # only supports combined server+client model at the moment
        # should support separate I suppose, but nobody uses it
        nprocs = self.params.get('nprocs', default=commands.getoutput("nproc"))
        args = self.params.get('args',  default=None)
        args = '%s %s' % (args, nprocs)
        pid = os.fork()
        if pid:                         # parent
            client = os.path.join(self.sourcedir, 'client.txt')
            args = '-c %s %s' % (client, args)
            cmd = os.path.join(self.sourcedir, "tbench") + " " + args
            # Standard output is verbose and merely makes our debug logs huge
            # so we don't retain it.  It gets parsed for the results.
            self.results = process.system_output(cmd, shell=True)
            os.kill(pid, signal.SIGTERM)    # clean up the server
        else:                           # child
            server = os.path.join(self.sourcedir, 'tbench_srv')
            os.execlp(server, server)
        pattern = re.compile(r"Throughput (.*?) MB/sec (.*?) procs")
        (throughput, procs) = pattern.findall(self.results)[0]
        self.log.info({'throughput': throughput, 'procs': procs})
pyScaf.py 文件源码 项目:pyScaf 作者: lpryszcz 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _check_dependencies(dependencies):
    """Return error if wrong software version"""
    warning = 0
    info = "[WARNING] Old version of %s: %s. Update to version %s+!\n"
    for cmd, version in dependencies.iteritems():
        out = _check_executable(cmd)
        if "not found" in out:
            warning = 1
            sys.stderr.write("[ERROR] %s\n"%out)
        elif version:
            out = commands.getoutput("%s --version"%cmd)
            curver = out.split()[-1]
            if not curver.isdigit():
                warning = 1
                sys.stderr.write("[WARNING] Problem checking %s version: %s\n"%(cmd, out))
            elif int(curver)<version:
                warning = 1
                sys.stderr.write(info%(cmd, curver, version))

    message = "Make sure you have installed all dependencies from https://github.com/lpryszcz/pyScaf#dependencies !"
    if warning:
        sys.stderr.write("\n%s\n\n"%message)
        sys.exit(1)
alert.py 文件源码 项目:Sentences-analysis 作者: sungminoh 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def main():
    parser = argparse.ArgumentParser(description='email notification')
    parser.add_argument('--email', '-e', help='email address', required=True)
    parser.add_argument('--process', '-p', help='process', required=True)
    parser.add_argument('--title', '-t', help='email content', default='Your process is done')
    parser.add_argument('--content', '-c', help='email content')
    args = parser.parse_args()

    host = platform.node()
    process = args.process
    email = args.email
    title = args.title
    content = args.content if args.content else '{} is done'.format(process)

    print commands.getoutput('ps -ef | grep %s' % process).split('\n')
    while any([True if x.find('python %s' % process) >= 0 else False
               for x in commands.getoutput('ps -ef | grep %s' % process).split('\n')]):
        print 'sleep ...'
        sleep(300)
    send_email(title, host, email, content)
task_stacking_blocks.py 文件源码 项目:cu-perception-manipulation-stack 作者: correlllab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def cmmnd_FingerPosition(self, finger_value):
        commands.getoutput('rosrun kinova_demo fingers_action_client.py j2n6a300 percent -- {0} {1} {2}'.format(finger_value[0],finger_value[1],finger_value[2]))
        # fingers_action_client.getCurrentFingerPosition('j2n6a300_')
        #
        # finger_turn, finger_meter, finger_percent = fingers_action_client.unitParser('percent', finger_value, '-r')
        # finger_number = 3
        # finger_maxDist = 18.9/2/1000  # max distance for one finger in meter
        # finger_maxTurn = 6800  # max thread turn for one finger
        #
        # try:
        #     if finger_number == 0:
        #         print('Finger number is 0, check with "-h" to see how to use this node.')
        #         positions = []  # Get rid of static analysis warning that doesn't see the exit()
        #         exit()
        #     else:
        #         positions_temp1 = [max(0.0, n) for n in finger_turn]
        #         positions_temp2 = [min(n, finger_maxTurn) for n in positions_temp1]
        #         positions = [float(n) for n in positions_temp2]
        #
        #     print('Sending finger position ...')
        #     result = fingers_action_client.gripper_client(positions)
        #     print('Finger position sent!')
        #
        # except rospy.ROSInterruptException:
        #     print('program interrupted before completion')
task_5.py 文件源码 项目:cu-perception-manipulation-stack 作者: correlllab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def cmmnd_FingerPosition(self, finger_value):
        commands.getoutput('rosrun kinova_demo fingers_action_client.py j2n6a300 percent -- {0} {1} {2}'.format(finger_value[0],finger_value[1],finger_value[2]))
        # fingers_action_client.getCurrentFingerPosition('j2n6a300_')
        #
        # finger_turn, finger_meter, finger_percent = fingers_action_client.unitParser('percent', finger_value, '-r')
        # finger_number = 3
        # finger_maxDist = 18.9/2/1000  # max distance for one finger in meter
        # finger_maxTurn = 6800  # max thread turn for one finger
        #
        # try:
        #     if finger_number == 0:
        #         print('Finger number is 0, check with "-h" to see how to use this node.')
        #         positions = []  # Get rid of static analysis warning that doesn't see the exit()
        #         exit()
        #     else:
        #         positions_temp1 = [max(0.0, n) for n in finger_turn]
        #         positions_temp2 = [min(n, finger_maxTurn) for n in positions_temp1]
        #         positions = [float(n) for n in positions_temp2]
        #
        #     print('Sending finger position ...')
        #     result = fingers_action_client.gripper_client(positions)
        #     print('Finger position sent!')
        #
        # except rospy.ROSInterruptException:
        #     print('program interrupted before completion')
task_7.py 文件源码 项目:cu-perception-manipulation-stack 作者: correlllab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def cmmnd_FingerPosition(self, finger_value):
        commands.getoutput('rosrun kinova_demo fingers_action_client.py j2n6a300 percent -- {0} {1} {2}'.format(finger_value[0],finger_value[1],finger_value[2]))
        # fingers_action_client.getCurrentFingerPosition('j2n6a300_')
        #
        # finger_turn, finger_meter, finger_percent = fingers_action_client.unitParser('percent', finger_value, '-r')
        # finger_number = 3
        # finger_maxDist = 18.9/2/1000  # max distance for one finger in meter
        # finger_maxTurn = 6800  # max thread turn for one finger
        #
        # try:
        #     if finger_number == 0:
        #         print('Finger number is 0, check with "-h" to see how to use this node.')
        #         positions = []  # Get rid of static analysis warning that doesn't see the exit()
        #         exit()
        #     else:
        #         positions_temp1 = [max(0.0, n) for n in finger_turn]
        #         positions_temp2 = [min(n, finger_maxTurn) for n in positions_temp1]
        #         positions = [float(n) for n in positions_temp2]
        #
        #     print('Sending finger position ...')
        #     result = fingers_action_client.gripper_client(positions)
        #     print('Finger position sent!')
        #
        # except rospy.ROSInterruptException:
        #     print('program interrupted before completion')
common.py 文件源码 项目:VolUtility 作者: kevthehermit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def hex_dump(hex_cmd):
    """
    return hexdump in html formatted data
    :param hex_cmd:
    :return: str
    """
    hex_string = getoutput(hex_cmd)

    # Format the data
    html_string = ''
    hex_rows = hex_string.split('\n')
    for row in hex_rows:
        if len(row) > 9:
            off_str = row[0:8]
            hex_str = row[9:58]
            asc_str = row[58:78]
            asc_str = asc_str.replace('"', '&quot;')
            asc_str = asc_str.replace('<', '&lt;')
            asc_str = asc_str.replace('>', '&gt;')
            html_string += '<div class="row"><span class="text-info mono">{0}</span> ' \
                           '<span class="text-primary mono">{1}</span> <span class="text-success mono">' \
                           '{2}</span></div>'.format(off_str, hex_str, asc_str)
    # return the data
    return html_string
on-modify.py 文件源码 项目:pomodoro-warriors 作者: cf020031308 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def main():
    inputs = utils.format_inputs()
    task = inputs['task']
    ret = [json.dumps(task)]
    if 'end' in task and 'end' not in inputs['prior']:
        timew = json.loads(commands.getoutput('timew get dom.tracked.1.json'))
        cmd = 'timew duration "%(uuid)s" from %(entry)s - %(end)s' % task
        if 'end' not in timew and task['uuid'] in timew['tags']:
            cmd = 'timew stop :quiet && ' + cmd
        if 'estimate' in task:
            ret.append(
                'Estimate Duration: %s' %
                utils.parse_duration(task['estimate']))
        ret.append('Total Duration: %s' % commands.getoutput(cmd))
    if len(ret) == 1:
        ret.append('')
    print('\n'.join(ret))
steg_brute.py 文件源码 项目:Steghide-Brute-Force-Tool 作者: Va5c0 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def Steg_brute(ifile, dicc):
    i = 0
    ofile = ifile.split('.')[0] + "_flag.txt"
    nlines = len(open(dicc).readlines())
    with open(dicc, 'r') as passFile:
        pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=nlines).start()
        for line in passFile.readlines():
            password = line.strip('\n')
            r = commands.getoutput("steghide extract -sf %s -p '%s' -xf %s" % (ifile, password, ofile))
            if not "no pude extraer" in r and not "could not extract" in r:
                print(color.GREEN + "\n\n " + r + color.ENDC)
                print("\n\n [+] " + color.INFO + "Information obtained with password:" + color.GREEN + " %s\n" % password + color.ENDC)
                if check_file(ofile):
                    with open(ofile, 'r') as outfile:
                        for line in outfile.readlines():
                            print(line)
                break
            pbar.update(i + 1)
            i += 1
task.py 文件源码 项目:webkvmmgr 作者: crazw 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def task_download_report(self, task_item):
        uri = task_item.data['uri']
        #size = task_item.data['size']
        #file_format = task_item.data['format']
        md5 = task_item.data['md5']
        save_path = task_item.data['save_path']

        def report(count, blockSize, totalSize):
            #update percent
            task_item.percent = ("%.2f" % (count*blockSize*100/totalSize))
            task_item.consuming = int(time.time() - self.begin_handle_time)
            pass
        filename = commands.getoutput('basename %s' % uri)
        file_abs_path = save_path + '/' + filename
        urllib.urlretrieve(uri, file_abs_path, reporthook=report)

        this_md5 = commands.getoutput("md5sum %s | awk '{print $1}' " % file_abs_path)
        if this_md5 == md5:
            return {"status_code": 0, "msg":"OK"}
        else:
            #os.system("rm -f %s" % file_abs_path)
            return {"status_code": -1, "msg":"md5 doesn't match"}
host.py 文件源码 项目:webkvmmgr 作者: crazw 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_sw_info(self):
        ret = {}
        hv_ver = self.conn.getVersion()
        major = hv_ver / 1000000
        minor = hv_ver % 1000000 / 1000
        release = hv_ver % 1000
        hv_ver = str(major)+'.'+str(minor)+'.'+str(release)

        lib_ver = self.conn.getLibVersion()
        major = lib_ver / 1000000
        minor = lib_ver % 1000000 / 1000
        release = lib_ver % 1000
        lib_ver = str(major)+'.'+str(minor)+'.'+str(release)

        abspath = os.path.dirname(os.path.abspath(__file__))
        cli_ver = open(abspath + "/VERSION").readline().rstrip('\r\n')

        cmd = "uname -r"
        os_ver = commands.getoutput(cmd)

        ret['version'] = cli_ver
        ret['libvirt_version'] = lib_ver
        ret['hv_version'] = hv_ver
        ret['os_version'] = os_ver
        return ret
host.py 文件源码 项目:webkvmmgr 作者: crazw 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_rx_tx(self, itface):
        try:
            cmd_rx = "cat /sys/class/net/%s/statistics/rx_bytes" % itface
            cmd_tx = "cat /sys/class/net/%s/statistics/tx_bytes" % itface
            data_rx_prev = commands.getoutput(cmd_rx)
            data_tx_prev = commands.getoutput(cmd_tx)

            time.sleep(1)
            data_rx_now = commands.getoutput(cmd_rx)
            data_tx_now = commands.getoutput(cmd_tx)

            rx = (float(data_rx_now) - float(data_rx_prev))/1024
            rx = ("%.2f" % rx)
            tx = (float(data_tx_now) - float(data_tx_prev))/1024
            tx = ("%.2f" % tx)

        except Exception, e:
            logger.exception(e)
            return None

        return {"in" : rx, "out" : tx}
kalipi.py 文件源码 项目:Kali-Pi 作者: Re4son 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def kill_process(proc, file=":"):
    try:
        check = "ps auxww | grep [" + proc[0] + "]" + proc[1:] + " | grep " + file
        status = commands.getoutput(check)
        #print(status)
        if status:
            #Process exists, kill it
            kill = "kill $(" + check + " | awk '{print $2}')"
            commands.getoutput(kill)
            return True
        else:
            return False
    except:
        return False

#This function is used to check individual processes, not services.
HTMLPrettify.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_output(cmd):
    if int(sublime.version()) < 3000:
      if sublime.platform() != "windows":
        # Handle Linux and OS X in Python 2.
        run = '"' + '" "'.join(cmd) + '"'
        return commands.getoutput(run)
      else:
        # Handle Windows in Python 2.
        # Prevent console window from showing.
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        return subprocess.Popen(cmd, \
          stdout=subprocess.PIPE, \
          startupinfo=startupinfo).communicate()[0]
    else:
      # Handle all OS in Python 3.
      run = '"' + '" "'.join(cmd) + '"'
      return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)


问题


面经


文章

微信
公众号

扫码关注公众号