Python2.x uses the commands module to execute the Linux shell Command, python2.xcommands

Source: Internet
Author: User

Python2.x uses the commands module to execute the Linux shell Command, python2.xcommands

When writing an O & M script using Python, you often need to execute the linux shell Command. The commands module in Python is used to call the Linux shell Command and return the status and result, the following are the three main functions of the commands module:

1. commands. getoutput ('Shell command ')

Run the shell command to return the result (string type)

Copy codeThe Code is as follows:
>>> Commands. getoutput ('pwd ')
'/Home/oracle'

2. commands. getstatus ('file ')

This function has been discarded by python and is not recommended. It returns the ls-ld file Result (String) (the returned result is so strange that it cannot be discarded)

Copy codeThe Code is as follows:
>>> Commands.getstatus('admin.tar ')
'-Rw-r -- 1 oracle 829440 Jan 29 admin.tar'

3. commands. getstatusoutput ('Shell command ')

Run the shell command to return the tuple (status, result) of the two elements. status indicates int type, and result indicates string type.

The cmd execution method is {cmd;} 2> & 1. Therefore, the returned results include standard output and standard errors.

Copy codeThe Code is as follows:
>>> Commands. getstatusoutput ('pwd ')
(0, '/home/oracle ')

The following script uses the commands module to detect disk usage and identifies a disk larger than 10% (the percentage can be adjusted according to the actual situation, which is generally set to 90%. In this example, we want to better describe the situation, set to 10% ):

import commandsthreshold = 10flag = Falsetitle=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_lv751G 14G 699G 2% /backup/dev/mapper/data-data_lv751G 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 = Trueif flag == True:#combine tile, chkDiskList, chkDisklist_2result = [title,]result.extend(chkDiskList)result.extend(chkDiskList_2)for line in result:print line

Assume that the current disk usage is as follows:

[oracle@lx200 ~/admin/python]$ df -hFilesystem 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% /boottmpfs 18G 0 18G 0% /dev/shm/dev/mapper/backup-backup_lv751G 14G 699G 2% /backup/dev/mapper/data-data_lv751G 174G 539G 25% /data 

The result of executing the script is as follows:

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_lv751G 14G 699G 2% /backup/dev/mapper/data-data_lv751G 174G 539G 25% /data ----Caution!!! space usage >= 10

How to Use the python Commands Module

To obtain the shell command output, you only need 'cmd,
To obtain the command execution status, you need to determine $? In Python, there is a module commands which can easily achieve the above effect.

Take a look at the three functions:

1). commands. getstatusoutput (cmd)

OS. popen () executes the command cmd and returns the tuples (status, result) of the two elements ). the cmd execution method is {cmd;} 2> & 1, so that the returned results will contain standard output and standard errors.

2). commands. getoutput (cmd)

Only the execution results are returned, and the returned values are ignored.

3). commands. getstatus (file)

Returns the result of ls-ld file Execution.

Let's take a look at the examples of these functions:

>>> 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'
Articles you may be interested in:
  • PHP webshell Check Tool python implementation code
  • Several Methods for passing python and shell variables to each other
  • Python method for calling shell
  • Example of executing a python script in a shell script and receiving its return value
  • Summary of several methods for executing shell commands in python
  • Methods and instances for calling system commands, Shell scripts, and Python scripts in Nodejs
  • Python calls PowerShell and remotely executes bat file instances.
  • Interactive execution of python file read/write operations and linux shell variable commands
  • Introduction to three ways of interaction between Python and shell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.