commands模块

用于执行Linux shell命令,要获得shell命令的输出只需要在后面参数写入('命令')就可以了。

需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands也很容易做到以上的效果。

看一下三个函数:

1). commands.getstatusoutput(命令)

执行shell命令, 返回两个元素的元组tuple(status, result),status为int类型,result为string类型。

cmd命令的执行方式是{ cmd ; } 2>&1, 故返回结果包含标准输出和标准错误.

>>> import commands

>>> commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

>>> commands.getstatusoutput('pwd')

(0, '/home/test')

>>> commands.getstatusoutput('cat /bin/junk')

(256, 'cat: /bin/junk: No such file or directory')

>>> commands.getstatusoutput('/bin/junk')

(256, 'sh: /bin/junk: not found')

2). commands.getoutput(cmd)

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

>>> commands.getoutput('ls /bin/ls')

'/bin/ls'

3). commands.getstatus(file) #现已被弃用

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

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

'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

例 1 :

获取系统最大文件描述符

#!/usr/bin/python

import os,sys,commands

_open_file=65533

try:

getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')

except Exception,e:

pass

if getulimit[0]==0:

host_open_file=int(getulimit[1])

if host_open_file = _open_file:

print "max_open_file is ok"

例 2 :

下面的一个脚本利用commands模块检测磁盘使用率,标识出大于10%的磁盘(百分比可根据实际情况调整,一般设为90%,本例为了更好的说明情况,设为10%):

#!/usr/bin/python

import commands

threshold = 10

flag = False

title=commands.getoutput("df -h|head -1")

'''

Check sda disk space usage like below format

'''

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:

'''

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

python commands用法_python之commands模块(执行Linux Shell命令)相关推荐

  1. python commands执行不连续_[Python] 利用commands模块执行Linux shell命令

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

  2. java 利用ganymed-ssh2 远程执行linux shell 命令

    早期的ganymed-ssh2包也可以实现远程调研linux shell 命令,但是这个包最新版本是2014年之后,就没有更新了,发现linux 操作系统安装 open-ssh 8.5及更高级版本,就 ...

  3. java执行Linux shell命令或者Window cmd命令

    执行Linux或者Window下的命令的代码: public static void runbat(String batFilePath) {       if(System.getProperty( ...

  4. python namedtuple用法_Python的collections模块中namedtuple结构使用示例

    namedtuple 就是命名的 tuple,比较像 C 语言中 struct.一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 inde ...

  5. java执行linux shell命令,并拿到返回值

    原文:http://www.cnblogs.com/enshrineZither/p/3793459.html 1 package com.pasier.xxx.util; 2 3 import ja ...

  6. linux打开python3_Python3 执行Linux Bash命令的方法

    和之前C++执行Linux Bash命令的方法 一样,Python依然支持system调用和popen()函数来执行linux bash命令. 方法一:system调用 #仅仅在一个子终端运行系统命令 ...

  7. Python3 执行Linux Bash命令

    和之前C++执行Linux Bash命令 一样,Python依然支持system调用和popen()函数来执行linux bash命令. 方法一:system调用 #仅仅在一个子终端运行系统命令,而不 ...

  8. 2021-07-08执行Linux的命令分析

    在进行深度学习实验时,GPU 的实时状态监测十分有必要. 执行Linux的命令: # /bin/bash 1. 查看CPU情况: 输入: lscpu 2. 查看GPU情况: 输入: nvidia-sm ...

  9. 解决java使用Runtime.exec执行linux复杂命令不成功问题

    解决java使用Runtime.exec执行linux复杂命令不成功问题 参考文章: (1)解决java使用Runtime.exec执行linux复杂命令不成功问题 (2)https://www.cn ...

最新文章

  1. phpstorm安装_PHPstorm设置浏览器打开代码
  2. 信号量的实现和应用实验报告_Java高级编程基础:原子信号量操作实现组线程执行管理...
  3. VScode修改快捷键,快捷键恢复默认设置,添加或取消注释
  4. vue-li 配置介绍
  5. sap.ca.scfld.md.ComponentBase.extend
  6. AttributeError: module 'cv2' has no attribute 'imread'
  7. leetcode907.SumofSubarrayMinimums
  8. 计算机基础知识真题模拟7,计算机一级考试计算机基础及Photoshop应用模拟试题(7)...
  9. input输入框[type=file]上传图片文件转base64数据
  10. Python 函数注释
  11. 带有vlan tag的报文与网卡的交互关系
  12. 泛微OA流程action 之 ACTION 封装
  13. 容器Docker学习系列五~命令学习history,save, import
  14. scikit-learn回归类库使用
  15. 钾肥认沽权证谢幕:揭密2007年股市第一奇案
  16. 2030年销售额突破200亿美元!瑞萨电子揭秘智能汽车版图
  17. java图片裁剪类似qq头像_Android实现类似换QQ头像功能(图片裁剪)
  18. 到底什么是数据湖?全面解读数据湖的缘起、特征、技术、案例和趋势
  19. 网格前后处理软件操作
  20. 概率密度估计--参数估计与非参数估计

热门文章

  1. 题解报告:hdu1205吃糖果(插空法)
  2. Stanford CoreNLP--Part of Speech
  3. Android 笔记
  4. Handbook of Constraints Programming——Chapter4 Backtracking Search Algorithms-Preliminaries
  5. [转载]上善若水,厚德载物
  6. SHELL编程Nginx源码多版本脚本
  7. AIX 关键系统文件被清空问题定位过程全记录
  8. 【Hive】解析字符串(类似array嵌套map结构)
  9. 【PL/SQL】触发器示例:记录加薪
  10. IIS 发布之后 您要找的资源已被删除、已更名或暂时不可用。 404.0 解决方法