[Python] 利用commands模塊執行Linux shell命令


用Python寫運維腳本時,經常需要執行linux shell的命令,Python中的commands模塊專門用於調用Linux shell命令,並返回狀態和結果,下面是commands模塊的3個主要函數:

1. commands.getoutput('shell command')

執行shell命令,返回結果(string類型)

>>> commands.getoutput('pwd')  
'/home/oracle'  

 

 

2. commands.getstatusoutput('shell command')

執行shell命令, 返回兩個元素的元組tuple(status, result),status為int類型,result為string類型。

cmd的執行方式是{ cmd ; } 2>&1, 故返回結果包含標准輸出和標准錯誤.

 

>>> commands.getstatusoutput('pwd')  
(0, '/home/oracle')  

下面的一個腳本利用commands模塊檢測磁盤使用率,標識出大於10%的磁盤(百分比可根據實際情況調整,一般設為90%,本例為了更好的說明情況,設為10%):

 

import commands  
  
threshold = 10  
flag = False  
  
title=commands.getoutput("df -h|head -1")  
  
''''' 
Check sda disk space usage like below format: 
/dev/sda2              20G  2.3G   17G  13% / 
/dev/sda6              20G  306M   19G   2% /var 
/dev/sda3              49G  2.8G   44G   7% /home 
/dev/sda5              49G  4.5G   42G  10% /opt 
/dev/sda1             194M   12M  172M   7% /boot 
'''  
  
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: 
/dev/mapper/backup-backup_lv 
                      751G   14G  699G   2% /backup 
/dev/mapper/data-data_lv 
                      751G  172G  540G  25% /data 
'''        
  
          
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  

 

 

 

 

# !/usr/bin/env python
# -*- coding: utf-8 -*

import os
import commands
import sys

import json

def main():
    mode = sys.argv[1] if len(sys.argv) >= 2 else 'post'

    url = "http://127.0.0.1:5004/"

    if mode == 'post':
        body_value = "{'geo':{'lat':120.0,'lat':20.0}, 'devicetype':4,'osv':'3.1.2', 'w':1920, 'h':1280, 'orientation':1,'user':{'id':'321','yob':1990}}"

        cmd = 'curl -l -H "Content-type: application/json" -X POST -d \'{"phone":"13521389587","password":"test","geo":{"lat":120,"lat":20}}\' http://127.0.0.1:5004/'
    else:
        cmd = 'curl -v "%s"' % (url)


    status, ouput = commands.getstatusoutput(cmd)

    s = ('success' if status == 0 else 'fail') + '\n\n\n---->\n\n\n\n' + ouput + '\n\n\n'
    print s

    exit(0)


if __name__ == '__main__':
    main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM