python之commands模块(执行

发布时间:2019-08-27 08:02:02编辑:auto阅读(1576)

    commands模块

    用于执行Linux shell命令,要获得shell命令的输出只需要在后面参数写入('命令')就可以了。

    需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands也很容易做到以上的效果。


    看一下三个函数:
    1). commands.getstatusoutput(命令)

    执行shell命令, 返回两个元素的元组tuple(status, result),status为int类型,result为string类型。

    cmd命令的执行方式是{ cmd ; } 2>&1, 故返回结果包含标准输出和标准错误.

    >>> import commands

    >>> commands.getstatusoutput('ls /bin/ls')

    (0, '/bin/ls')

    >>> commands.getstatusoutput('pwd')  

    (0, '/home/test')  

    >>> commands.getstatusoutput('cat /bin/junk')

    (256, 'cat: /bin/junk: No such file or directory')

    >>> commands.getstatusoutput('/bin/junk')

    (256, 'sh: /bin/junk: not found')


    2). commands.getoutput(cmd)
    只返回执行的结果, 忽略返回值.

    >>> commands.getoutput('ls /bin/ls')

    '/bin/ls'


    3). commands.getstatus(file) #现已被弃用
    返回ls -ld file执行的结果.

    >>> commands.getstatus('/bin/ls')    #该函数已被python丢弃,不建议使用,它返回 ls -ld file 的结果(String)(返回结果太奇怪了,难怪被丢弃)

    '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'


    例 1 :

    获取系统最大文件描述符

    #!/usr/bin/python 

    import os,sys,commands 

      

    _open_file=65533 

    try: 

        getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')

    except Exception,e:

        pass

    if getulimit[0]==0:

        host_open_file=int(getulimit[1])

    if host_open_file = _open_file:

        print "max_open_file is ok"


    例 2 :

    下面的一个脚本利用commands模块检测磁盘使用率,标识出大于10%的磁盘(百分比可根据实际情况调整,一般设为90%,本例为了更好的说明情况,设为10%):


    #!/usr/bin/python

    import commands  

      

    threshold = 10  

    flag = False  

      

    title=commands.getoutput("df -h|head -1")  

      

    '''

    Check sda disk space usage like below format

    '''  

      

    chkDiskList=commands.getoutput("df -h|grep sda").split('\n')  

    usedPercents=commands.getoutput("df -h|grep sda|awk '{print $5}'|grep -Eo '[0-9]+'").split('\n')  

      

    for i in range(0,len(usedPercents)):  

      if int(usedPercents[i]) >= threshold:  

        chkDiskList[i] += '    ----Caution!!! space usage >= ' + str(threshold)  

        flag = True  

      

    '''

    Check disk space usage like below format: 

    '''        

      

              

    chkDiskList_2=commands.getoutput("df -h|grep -v sda|grep -v tmp|grep -v system").split('\n')  

    usedPercents_2=commands.getoutput("df -h|grep -v map|grep -v sda|grep -v tmp|grep -v system|awk '{print $4}'|grep -Eo '[0-9]+'").split('\n')  

      

    for i in range(0,len(usedPercents_2)):   

      if int(usedPercents_2[i]) >= threshold:  

        chkDiskList_2[i*2 + 1] += '    ----Caution!!! space usage >= ' + str(threshold)  

        flag = True  

      

    if flag == True:  

      #combine tile, chkDiskList, chkDisklist_2  

      result = [title,]  

      result.extend(chkDiskList)  

      result.extend(chkDiskList_2)  

      for line in result:  

        print line  



关键字