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定时检查启动某个exe程序适合检测exe是否挂了
Jan 21 Python
分析Python编程时利用wxPython来支持多线程的方法
Apr 07 Python
使用Python的web.py框架实现类似Django的ORM查询的教程
May 02 Python
Python的Django框架下管理站点的基本方法
Jul 17 Python
通过5个知识点轻松搞定Python的作用域
Sep 09 Python
python使用xslt提取网页数据的方法
Feb 23 Python
使用Python的Django和layim实现即时通讯的方法
May 25 Python
python实现根据文件关键字进行切分为多个文件的示例
Dec 10 Python
python设计tcp数据包协议类的例子
Jul 23 Python
python飞机大战pygame游戏之敌机出场实现方法详解
Dec 17 Python
python实现移动木板小游戏
Oct 09 Python
Python 实现RSA加解密文本文件
Dec 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
Zerg基本策略
2020/03/14 星际争霸
php上传文件的增强函数
2010/07/21 PHP
PHP同时连接多个mysql数据库示例代码
2014/03/17 PHP
关于php支持分块与断点续传文件下载功能代码
2014/05/09 PHP
PHP中设置一个严格30分钟过期Session面试题的4种答案
2014/07/30 PHP
php利用反射实现插件机制的方法
2015/03/14 PHP
深入了解PHP中的Array数组和foreach
2016/11/06 PHP
使用WAMP搭建PHP本地开发环境
2017/05/10 PHP
PHP使用GD库制作验证码的方法(点击验证码或看不清会刷新验证码)
2017/08/15 PHP
Jquery实现简单的动画效果代码
2012/03/18 Javascript
js关于命名空间的函数实例
2015/02/05 Javascript
nodejs中的fiber(纤程)库详解
2015/03/24 NodeJs
JavaScript高级程序设计(第三版)学习笔记1~5章
2016/03/11 Javascript
vue 权限认证token的实现方法
2018/07/17 Javascript
微信小程序使用canvas的画图操作示例
2019/01/18 Javascript
在Web关闭页面时发送Ajax请求的实现方法
2019/03/07 Javascript
vue动态绘制四分之三圆环图效果
2019/09/03 Javascript
Django原生sql也能使用Paginator分页的示例代码
2017/11/15 Python
Python AES加密实例解析
2018/01/18 Python
python正向最大匹配分词和逆向最大匹配分词的实例
2018/11/14 Python
Django后台admin的使用详解
2019/07/08 Python
python实现微信自动回复机器人功能
2019/07/11 Python
python+Django+pycharm+mysql 搭建首个web项目详解
2019/11/29 Python
python读写Excel表格的实例代码(简单实用)
2019/12/19 Python
python 通过邮件控制实现远程控制电脑操作
2020/03/16 Python
python属于软件吗
2020/06/18 Python
Python自定义sorted排序实现方法详解
2020/09/18 Python
python 元组和列表的区别
2020/12/30 Python
GUESS Factory加拿大:牛仔裤、服装及配饰
2019/09/20 全球购物
西班牙Polo衫品牌:Polo Club
2020/08/09 全球购物
演讲稿开场白
2014/01/13 职场文书
数学国培研修感言
2014/02/13 职场文书
护理专业毕业生自荐书
2014/05/24 职场文书
自愿离婚协议书范文2014
2014/10/12 职场文书
领导干部学习心得体会
2016/01/23 职场文书
60句有关成长的名言
2019/09/04 职场文书