Python 执行Shell 外部命令

1、os.system()
此方法执行的外部程序,会将结果直接输出到标准输出。os.system的返回结果为执行shell 的 $? 值。
因此请执行没有输出结果的程序时适合使用此方法。如touch 、rm 一个文件等。

In [1]: import os
In [2]: os.system(‘touch test.txt‘)
Out[2]: 0
In [3]: os.system(‘rm -rf test.txt‘)
Out[3]: 0

2、os.popen()
此方法结合了os.system和 文件的特性。可以解决os.system那种无法获取程序执行结果的缺点
os.popen 返回了一个类似与文件句柄的东西。可以对这个返回的结果做一些类似于对文件的操作

In [6]: output = os.popen(‘cat /etc/passwd‘)

In [7]: for line in output.readlines():
   ...:     print line.strip()
   ...:     
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin

可以help(output) 获取相关帮助去操作这个output

3、commands 模块
这个模块主要提供了三个方法:
(1)、getoutput(cmd)
Return output (stdout or stderr) of executing cmd in a shell.
返回一个shell 命令的标准输出或者时错误输出

In [17]: commands.getoutput(‘ls /home -l‘)
Out[17]: ‘total 4\ndrwxr-xr-x 31 admin admin 4096  5\xe6\x9c\x88  3 09:48 admin‘

In [18]: commands.getoutput(‘ls /homeaaa -l‘)
Out[18]: ‘ls: cannot access /homeaaa: No such file or directory‘

(2)、getstatus(file)
Return output of "ls -ld <file>" in a string.
获取一个文件的状态。 相当于执行了 ls -ld file

In [25]: commands.getstatus(‘/bin/ls‘)
Out[25]: ‘-rwxr-xr-x 1 root root 110080  3\xe6\x9c\x88 24  2014 /bin/ls‘ // 相当于执行了 ls -ld /bin/ls

In [26]: os.system(‘ls -ld /bin/ls‘)
-rwxr-xr-x 1 root root 110080  3月 24  2014 /bin/ls

(3)、getstatusoutput(cmd)
Return (status, output) of executing cmd in a shell.
返回shell 的状态码和输出结果

In [20]: commands.getstatusoutput(‘ls /home -l‘)
Out[20]: (0, ‘total 4\ndrwxr-xr-x 31 admin admin 4096  5\xe6\x9c\x88  3 09:48 admin‘)

In [21]: commands.getstatusoutput(‘ls /homeaa -l‘)
Out[21]: (512, ‘ls: cannot access /homeaa: No such file or directory‘)

4、subprocess 相关模块.
从这个模块的帮助中可以看到。它的一个很主要的目的就是要替代掉os.system 、os.spawn*、os.popen*、popen2.* 、commands.*  这些模块的功能

subproces 模块中一个很强大的类Popen,我们的主要学习重点应该在于此
    class Popen(args, bufsize=0, executable=None,
                stdin=None, stdout=None, stderr=None,
                preexec_fn=None, close_fds=False, shell=False,
                cwd=None, env=None, universal_newlines=False,
                startupinfo=None, creationflags=0):

args: 可以是一个字符串 或者是一个序列(list | tuple )。其实字符串也是序列呀。呵呵,我们这里就讲序列认为时list 和 tuple 了吧。若是序列时,则第一个元素为可执行的命令

在unix 系统中, shell=Ture 和 shell=False(默认) 和 args 参数有一定的影响关系。

看一下下面的列子:
 subprocess.Popen(["cat","/etc/passwd"])
 subprocess.Popen("cat /etc/passwd")
 我们看看以上这两种写法是否OK

In [29]: subprocess.Popen(["cat","/etc/passwd"])
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

In [30]: subprocess.Popen("cat /etc/passwd")
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)

第一种写法OK。第二种写法不OK。这是什么原因呢?
主要时 shell=False(默认值) 这个参数搞的鬼。

在UNIX中, shell=False 时 subprocess.Popen() 使用os.execvp()去执行响应的子程序。
当 args 是一个字符串的时候,Popen 认为这个字符串是序列中的第一个元素(可执行的程序)。

调用 os.execvp()的时候 ,到$PATH 中去找这个可执行程序,没有找到,所以程序出现了异常。
不过这也分命令,若写成如下的形式:
subprocess.Popen("/bin/pwd")

In [32]: subprocess.Popen("/bin/pwd")
/home/dexin/python/tcollector

以上这个就无所谓了。

不过就是想让 subprocess.Popen("cat /etc/passwd") 能够正确的去执行,应该怎么办呢? 设置 shell=True .这样当再执行类似的程序时,会调用相应的shell 去做  shell -c "cat /etc/passwd"

 subprocess.Popen("cat /etc/passwd",shell=True)
Out[33]: <subprocess.Popen at 0x7f922a6b2350>

In [34]: root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
时间: 2024-07-29 11:50:08

Python 执行Shell 外部命令的相关文章

python执行shell命令

python执行shell命令 #!/usr/bin/python2.7 #coding=utf-8 import shlex import datetime import subprocess import time def execute_command(cmdstring, cwd=None, timeout=None, shell=False): # 执行一个SHELL命令 ## 封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr ## 参数:

python 执行shell 命令,自动化添加攻击IP地址到iptables

通过python执行shell命令的方法有4种,在这里介绍一种常用的. os.system. os.popen. commands. subprocess 接下来介绍subprocess的使用 通过python 日志分析,获取到攻击源IP地址,收集写入到mysql数据库中 mysql如下: iptables.py 脚本 #!/usr/bin/env python # -*- coding:utf-8 -*- import os import MySQLdb import subprocess t

python执行shell获取硬件参数写入mysql

最近要获取服务器各种参数,包括cpu.内存.磁盘.型号等信息.试用了Hyperic HQ.Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy. 于是乎想到用python执行shell获取这些信息,python执行shell脚本有以下三种方法: 1. os.system() os.system('ls')#返回结果0或者1,不能得到命令的输出 2. os.popen() output = os.popen('ls') print output.read()#打印出的

Linux编程 10 (shell外部命令与内建命令,alias ,type命令)

一.  内部命令 Linux命令有内部命令(内建命令)和外部命令之分,内部命令和外部命令功能基本相同,但也有些细微差别.内部命令不需要使用子进程来执行,它们已经和shell编译成一体,作为shell工具的组成部分存在.不需要借助外部程序文件来运行.它们是一些比较简单的linux系统命令,如exit,history,cd,echo等. 要分区是外部命令还是内部命令可以使用type  来查看,如下图查看cd是内部还是外部命令: 1.1命令别名 alias 命令也是一个内建命令,允许你为常用的命令和参

Linux中执行shell脚本命令的4种方法总结

bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在的目录(此时,称为工作目录)执行shell脚本: 复制代码 代码如下: cd /data/shell ./hello.sh ./的意思是说在当前的工作目录下执行hello.sh.如果不加上./,bash可能会响应找到不到hello.sh的错误信息.因为目前的工作目录(/data/shell)可能不在

Linux 定时执行shell脚本命令之crontab

crontab可以在指定的时间执行一个shell脚本以及执行一系列Linux命令 例如:服务器管理员定时备份数据库数据.日志等 详解: 常用命令: crontab –e //修改 crontab 文件,如果文件不存在会自动创建. crontab –l //显示 crontab 文件. crontab -r //删除 crontab 文件. crontab -ir //删除 crontab 文件前提醒用户. service crond status //查看crontab服务状态 service

python执行shell指令的几种方法

1.os.system() 优点:简单,linux&widnows等平台均可用,只需要判断返回结果是0还是1即可判断是否执行成功. 缺点:无法获取返回输出. 例子: os.system('ls') 2.os.popen() 优点:可获取输出结果 缺点:无法获取执行结果,需要根据输出结果做判断处理 例子: output = os.popen('ls') print output.read() 3.commands.getstatusoutput() 优点:可同时获取执行结果及返回结果 缺点:win

java执行shell/cmd命令

try { Process p =Runtime.getRuntime().exec("chmod 777 /home/bomb/MoveToy/WebRoot/a.sh " ); p.waitFor(); Process pro = Runtime.getRuntime().exec(" /home/bomb/MoveToy/WebRoot/./a.sh " + num); pro.waitFor(); System.out.println("run&q

python执行shell实时输出,并返回code

import subprocess def run_shell(shell): cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1) # 实时输出 while True: line = cmd.stdout.readline() print(line, e