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之集合(set)
Sep 24 Python
零基础写python爬虫之urllib2使用指南
Nov 05 Python
python判断给定的字符串是否是有效日期的方法
May 13 Python
python 基础教程之Map使用方法
Jan 17 Python
浅谈终端直接执行py文件,不需要python命令
Jan 23 Python
python snownlp情感分析简易demo(分享)
Jun 04 Python
Python从单元素字典中获取key和value的实例
Dec 31 Python
Django实现发送邮件功能
Jul 18 Python
Django实现文章详情页面跳转代码实例
Sep 16 Python
python获取linux系统信息的三种方法
Oct 14 Python
Python中过滤字符串列表的方法
Dec 22 Python
详解Python调用系统命令的六种方法
Jan 28 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(1)
2006/10/09 PHP
数据库的日期格式转换
2006/10/09 PHP
php正则匹配html中带class的div并选取其中内容的方法
2015/01/13 PHP
Javascript实例教程(19) 使用HoTMetal(2)
2006/12/23 Javascript
javascript 在网页中的运用(asp.net)
2009/11/23 Javascript
JavaScript Event学习第二章 Event浏览器兼容性
2010/02/07 Javascript
Chrome中模态对话框showModalDialog返回值问题的解决方法
2010/05/25 Javascript
jQuery Ajax请求状态管理器打包
2012/05/03 Javascript
基于jQuery的input输入框下拉提示层(自动邮箱后缀名)
2012/06/14 Javascript
Javascript的严格模式strict mode详细介绍
2014/06/06 Javascript
谈谈vue中mixin的一点理解
2017/12/12 Javascript
vuex的使用及持久化state的方式详解
2018/01/23 Javascript
js中获取URL参数的共用方法getRequest()方法实例详解
2018/10/24 Javascript
Node.js 如何利用异步提升任务处理速度
2019/01/07 Javascript
Python日期操作学习笔记
2008/10/07 Python
Python中使用urllib2防止302跳转的代码例子
2014/07/07 Python
python中enumerate函数用法实例分析
2015/05/20 Python
python爬虫_自动获取seebug的poc实例
2017/08/05 Python
基于python历史天气采集的分析
2019/02/14 Python
python控制台实现tab补全和清屏的例子
2019/08/20 Python
Python对称的二叉树多种思路实现方法
2020/02/28 Python
pytorch 中的重要模块化接口nn.Module的使用
2020/04/02 Python
matlab、python中矩阵的互相导入导出方式
2020/06/01 Python
python3.4中清屏的处理方法
2020/07/06 Python
Elasticsearch py客户端库安装及使用方法解析
2020/09/14 Python
基于css3 animate制作绚丽的动画效果
2015/11/24 HTML / CSS
Spartoo比利时:欧洲时尚购物网站
2017/12/06 全球购物
美津浓美国官网:Mizuno美国
2018/08/07 全球购物
网络程序员自荐信
2014/01/25 职场文书
搞笑获奖感言
2014/01/30 职场文书
安全生产实施方案
2014/02/23 职场文书
莫言诺贝尔获奖感言(全文)
2015/07/31 职场文书
2017寒假社会实践心得体会范文
2016/01/14 职场文书
python机器学习创建基于规则聊天机器人过程示例详解
2021/11/02 Python
Redis之RedisTemplate配置方式(序列和反序列化)
2022/03/13 Redis
HTML实现仿Windows桌面主题特效的实现
2022/06/28 HTML / CSS