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实现SMTP发送邮件详细教程
Mar 02 Python
Python标准库06之子进程 (subprocess包) 详解
Dec 07 Python
Python读取properties配置文件操作示例
Mar 29 Python
浅谈Python Opencv中gamma变换的使用详解
Apr 02 Python
python修改txt文件中的某一项方法
Dec 29 Python
python读取txt文件并取其某一列数据的示例
Feb 19 Python
PyQt+socket实现远程操作服务器的方法示例
Aug 22 Python
python根据时间获取周数代码实例
Sep 30 Python
Python读取VOC中的xml目标框实例
Mar 10 Python
Python基于百度API识别并提取图片中文字
Jun 27 Python
pandas进行数据输入和输出的方法详解
Mar 23 Python
Python使用mitmproxy工具监控手机 下载手机小视频
Apr 18 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
文件上传程序的全部源码
2006/10/09 PHP
php删除页面记录 同时刷新页面 删除条件用GET方式获得
2012/01/10 PHP
微信开发之php表单微信中自动提交两次问题解决办法
2017/01/08 PHP
PHP聚合式迭代器接口IteratorAggregate用法分析
2017/12/28 PHP
PHP的RSA加密解密方法以及开发接口使用
2018/02/11 PHP
Laravel 将数据表的数据导出,并生成seeds种子文件的方法
2019/10/09 PHP
JavaScript高级程序设计
2006/12/29 Javascript
关于JS字符串函数String.replace()
2013/04/07 Javascript
js实现单一html页面两套css切换代码
2013/04/11 Javascript
JS中的THIS和WINDOW.EVENT.SRCELEMENT详解
2015/05/25 Javascript
jQuery toggle 代替方法
2016/03/22 Javascript
jQuery实现内容定时切换效果完整实例
2016/04/06 Javascript
关于数据与后端进行交流匹配(点亮星星)
2016/08/03 Javascript
axios学习教程全攻略
2017/03/26 Javascript
bootstrap是什么_动力节点Java学院整理
2017/07/14 Javascript
jQuery实现的事件绑定功能基本示例
2017/10/11 jQuery
JS加密插件CryptoJS实现的Base64加密示例
2020/08/16 Javascript
Vue.Draggable拖拽功能的配置使用方法
2020/07/29 Javascript
Easyui 关闭jquery-easui tab标签页前触发事件的解决方法
2019/04/28 jQuery
JS实现点击发送验证码 xx秒后重新发送功能
2019/07/30 Javascript
Vue 设置axios请求格式为form-data的操作步骤
2019/10/29 Javascript
Python标准模块--ContextManager上下文管理器的具体用法
2017/11/27 Python
Python生成器的使用方法和示例代码
2019/03/04 Python
python实现整数的二进制循环移位
2019/03/08 Python
python报错TypeError: ‘NoneType‘ object is not subscriptable的解决方法
2020/11/05 Python
英国最大的纸工艺品商店:CraftStash
2018/12/01 全球购物
软件测试笔试题
2012/10/25 面试题
办公室主任岗位职责
2013/11/08 职场文书
编辑找工作求职信范文
2013/12/16 职场文书
物业招聘计划书
2014/01/10 职场文书
初三学生个人自我评定
2014/04/06 职场文书
小班评语大全
2014/05/04 职场文书
大学生个人求职信
2014/06/02 职场文书
机械专业应届毕业生自荐书
2014/06/12 职场文书
2015年基层党建工作汇报材料
2015/06/25 职场文书
Nginx解决前端访问资源跨域问题的方法详解
2021/03/31 Servers