Python2.x利用commands模块执行Linux shell命令


Posted in Python onMarch 11, 2016

用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands模块的3个主要函数:

1. commands.getoutput('shell command')

执行shell命令,返回结果(string类型)

>>> commands.getoutput('pwd')

'/home/oracle'

2. commands.getstatus('file')

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

>>> commands.getstatus('admin.tar')

'-rw-rw-r-- 1 oracle oracle 829440 Jan 29 10:36 admin.tar'

3. 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

假设当前的磁盘使用率如下:

[oracle@lx200 ~/admin/python]$ df -h
Filesystem Size Used Avail Use% Mounted on
/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
tmpfs 18G 0 18G 0% /dev/shm
/dev/mapper/backup-backup_lv
751G 14G 699G 2% /backup
/dev/mapper/data-data_lv
751G 174G 539G 25% /data

执行该脚本后的结果如下:

Filesystem Size Used Avail Use% Mounted on
/dev/sda2 20G 2.3G 17G 13% / ----Caution!!! space usage >= 10
/dev/sda6 20G 306M 19G 2% /var
/dev/sda3 49G 2.8G 44G 7% /home
/dev/sda5 49G 4.5G 42G 10% /opt ----Caution!!! space usage >= 10
/dev/sda1 194M 12M 172M 7% /boot
/dev/mapper/backup-backup_lv
751G 14G 699G 2% /backup
/dev/mapper/data-data_lv
751G 174G 539G 25% /data ----Caution!!! space usage >= 10

python Commands模块 使用方法

要获得shell命令的输出只需要`cmd`就可以了,
需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands也很容易做到以上的效果.

看一下三个函数:

1). commands.getstatusoutput(cmd)

用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result). cmd执行的方式是{ cmd ; } 2>&1, 这样返回结果里面就会包含标准输出和标准错误.

2). commands.getoutput(cmd)

只返回执行的结果, 忽略返回值.

3). commands.getstatus(file)

返回ls -ld file执行的结果.

看一下这些函数使用的例子:

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
Python 相关文章推荐
Python中的map、reduce和filter浅析
Apr 26 Python
使用Python中的greenlet包实现并发编程的入门教程
Apr 16 Python
python 获取list特定元素下标的实例讲解
Apr 09 Python
Python实现绘制双柱状图并显示数值功能示例
Jun 23 Python
Python 从列表中取值和取索引的方法
Dec 25 Python
python仿抖音表白神器
Apr 08 Python
Python画图高斯分布的示例
Jul 10 Python
python爬取百度贴吧前1000页内容(requests库面向对象思想实现)
Aug 10 Python
python函数定义和调用过程详解
Feb 09 Python
ansible-playbook实现自动部署KVM及安装python3的详细教程
May 11 Python
python实现图片素描效果
Sep 26 Python
python爬虫调度器用法及实例代码
Nov 30 Python
Python实现列表转换成字典数据结构的方法
Mar 11 #Python
python中enumerate函数遍历元素用法分析
Mar 11 #Python
python实现class对象转换成json/字典的方法
Mar 11 #Python
Windows下Python的Django框架环境部署及应用编写入门
Mar 10 #Python
深入学习python的yield和generator
Mar 10 #Python
Python中random模块生成随机数详解
Mar 10 #Python
python生成器表达式和列表解析
Mar 10 #Python
You might like
php session和cookie使用说明
2010/04/07 PHP
PHP+ajax分页实例简析
2015/12/07 PHP
在WordPress的文章编辑器中设置默认内容的方法
2015/12/29 PHP
[原创]php正则删除img标签的方法示例
2017/05/27 PHP
[原创]PHP实现生成vcf vcard文件功能类定义与使用方法详解【附demo源码下载】
2017/09/02 PHP
使用PHP访问RabbitMQ消息队列的方法示例
2018/06/06 PHP
Javascript SHA-1:Secure Hash Algorithm
2006/12/20 Javascript
Code: write(s,d) 输出连续字符串
2007/08/19 Javascript
ajax 同步请求和异步请求的差异分析
2011/07/04 Javascript
JavaScript中的数值范围介绍
2014/12/29 Javascript
JS返回iframe中frameBorder属性值的方法
2015/04/01 Javascript
JavaScript中的call方法和apply方法使用对比
2015/08/12 Javascript
JS组件Bootstrap实现弹出框效果代码
2016/04/26 Javascript
基于vue2.0+vuex+localStorage开发的本地记事本示例
2017/02/28 Javascript
JavaScript中Object值合并方法详解
2017/12/22 Javascript
axios对请求各种异常情况处理的封装方法
2018/09/25 Javascript
Vue开发中常见的套路和技巧总结
2020/11/24 Vue.js
JS实现鼠标移动拖尾
2020/12/27 Javascript
vue二选一tab栏切换新做法实现
2021/01/19 Vue.js
[01:51]2018年度CS GO最具人气外援-完美盛典
2018/12/16 DOTA
使用python获取CPU和内存信息的思路与实现(linux系统)
2014/01/03 Python
Python实现的简单模板引擎功能示例
2017/09/02 Python
python smtplib模块自动收发邮件功能(二)
2018/05/22 Python
解决python3 HTMLTestRunner测试报告中文乱码的问题
2018/12/17 Python
python简单实现AES加密和解密
2019/03/28 Python
python抓取多种类型的页面方法实例
2019/11/20 Python
PYQT5开启多个线程和窗口,多线程与多窗口的交互实例
2019/12/13 Python
Python pymsql模块的使用
2020/09/07 Python
Myprotein葡萄牙官方网站:英国优质运动营养品牌
2016/09/12 全球购物
Regatta官网:英国最受欢迎的户外服装和鞋类品牌
2019/05/01 全球购物
实习生个人的自我评价
2013/12/08 职场文书
献爱心捐款倡议书
2014/05/14 职场文书
2014乡镇机关党员个人对照检查材料思想汇报
2014/10/09 职场文书
师德先进个人事迹材料
2014/12/19 职场文书
市场部岗位职责范本
2015/04/15 职场文书
《攀登者》:“海拔8000米以上,你不能指望任何人”
2019/11/25 职场文书