# -*- coding: utf-8 -*-
import os
import subprocess
import signal
import pwd
import sys class MockLogger(object):
'''模拟日志类。方便单元测试。'''
def __init__(self):
self.info = self.error = self.critical = self.debug def debug(self, msg):
print "LOGGER:"+msg class Shell(object):
'''完成Shell脚本的包装。
执行结果存放在Shell.ret_code, Shell.ret_info, Shell.err_info中
run()为普通调用,会等待shell命令返回。
run_background()为异步调用,会立刻返回,不等待shell命令完成
异步调用时,可以使用get_status()查询状态,或使用wait()进入阻塞状态,
等待shell执行完成。
异步调用时,使用kill()强行停止脚本后,仍然需要使用wait()等待真正退出。
TODO 未验证Shell命令含有超大结果输出时的情况。
'''
def __init__(self, cmd):
self.cmd = cmd # cmd包括命令和参数
self.ret_code = None
self.ret_info = None
self.err_info = None
#使用时可替换为具体的logger
self.logger = MockLogger() def run_background(self):
'''以非阻塞方式执行shell命令(Popen的默认方式)。
'''
self.logger.debug("run %s"%self.cmd)
# Popen在要执行的命令不存在时会抛出OSError异常,但shell=True后,
# shell会处理命令不存在的错误,因此没有了OSError异常,故不用处理
self._process = subprocess.Popen(self.cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) #非阻塞 def run(self):
'''以阻塞方式执行shell命令。
'''
self.run_background()
self.wait() def run_cmd(self, cmd):
'''直接执行某条命令。方便一个实例重复使用执行多条命令。
'''
self.cmd = cmd
self.run() def wait(self):
'''等待shell执行完成。
'''
self.logger.debug("waiting %s"%self.cmd)
self.ret_info, self.err_info = self._process.communicate() #阻塞
# returncode: A negative value -N indicates that the child was
# terminated by signal N
self.ret_code = self._process.returncode
self.logger.debug("waiting %s done. return code is %d"%(self.cmd,
self.ret_code)) def get_status(self):
'''获取脚本运行状态(RUNNING|FINISHED)
'''
retcode = self._process.poll()
if retcode == None:
status = "RUNNING"
else:
status = "FINISHED"
self.logger.debug("%s status is %s"%(self.cmd, status))
return status # Python2.4的subprocess还没有send_signal,terminate,kill
# 所以这里要山寨一把,2.7可直接用self._process的kill()
def send_signal(self, sig):
self.logger.debug("send signal %s to %s"%(sig, self.cmd))
os.kill(self._process.pid, sig) def terminate(self):
self.send_signal(signal.SIGTERM) def kill(self):
self.send_signal(signal.SIGKILL) def print_result(self):
print "return code:", self.ret_code
print "return info:", self.ret_info
print " error info:", self.err_info class RemoteShell(Shell):
'''远程执行命令(ssh方式)。
XXX 含特殊字符的命令可能导致调用失效,如双引号,美元号$
NOTE 若cmd含有双引号,可使用RemoteShell2
'''
def __init__(self, cmd, ip):
ssh = ("ssh -o PreferredAuthentications=publickey -o "
"StrictHostKeyChecking=no -o ConnectTimeout=10")
# 不必检查IP有效性,也不必检查信任关系,有问题shell会报错
cmd = '%s %s "%s"'%(ssh, ip, cmd)
Shell.__init__(self, cmd) class RemoteShell2(RemoteShell):
'''与RemoteShell相同,只是变换了引号。
'''
def __init__(self, cmd, ip):
RemoteShell.__init__(self, cmd, ip)
self.cmd = "%s %s '%s'"%(ssh, ip, cmd) class SuShell(Shell):
'''切换用户执行命令(su方式)。
XXX 只适合使用root切换至其它用户。
因为其它切换用户后需要输入密码,这样程序会挂住。
XXX 含特殊字符的命令可能导致调用失效,如双引号,美元号$
NOTE 若cmd含有双引号,可使用SuShell2
'''
def __init__(self, cmd, user):
if os.getuid() != 0: # 非root用户直接报错
raise Exception('SuShell must be called by root user!')
cmd = 'su - %s -c "%s"'%(user, cmd)
Shell.__init__(self, cmd) class SuShell2(SuShell):
'''与SuShell相同,只是变换了引号。
'''
def __init__(self, cmd, user):
SuShell.__init__(self, cmd, user)
self.cmd = "su - %s -c '%s'"%(user, cmd) class SuShellDeprecated(Shell):
'''切换用户执行命令(setuid方式)。
执行的函数为run2,而不是run
XXX 以“不干净”的方式运行:仅切换用户和组,环境变量信息不变。
XXX 无法获取命令的ret_code, ret_info, err_info
XXX 只适合使用root切换至其它用户。
'''
def __init__(self, cmd, user):
self.user = user
Shell.__init__(self, cmd) def run2(self):
if os.getuid() != 0: # 非root用户直接报错
raise Exception('SuShell2 must be called by root user!')
child_pid = os.fork()
if child_pid == 0: # 子进程干活
uid, gid = pwd.getpwnam(self.user)[2:4]
os.setgid(gid) # 必须先设置组
os.setuid(uid)
self.run()
sys.exit(0) # 子进程退出,防止继续执行其它代码
else: # 父进程等待子进程退出
os.waitpid(child_pid, 0) if __name__ == "__main__":
'''test code'''
# 1. test normal
sa = Shell('who')
sa.run()
sa.print_result() # 2. test stderr
sb = Shell('ls /export/dir_should_not_exists')
sb.run()
sb.print_result() # 3. test background
sc = Shell('sleep 1')
sc.run_background()
print 'hello from parent process'
print "return code:", sc.ret_code
print "status:", sc.get_status()
sc.wait()
sc.print_result() # 4. test kill
import time
sd = Shell('sleep 2')
sd.run_background()
time.sleep(1)
sd.kill()
sd.wait() # NOTE, still need to wait
sd.print_result() # 5. test multiple command and uncompleted command output
se = Shell('pwd;sleep 1;pwd;pwd')
se.run_background()
time.sleep(1)
se.kill()
se.wait() # NOTE, still need to wait
se.print_result() # 6. test wrong command
sf = Shell('aaaaa')
sf.run()
sf.print_result() # 7. test instance reuse to run other command
sf.cmd = 'echo aaaaa'
sf.run()
sf.print_result() sg = RemoteShell('pwd', '127.0.0.1')
sg.run()
sg.print_result() # unreachable ip
sg2 = RemoteShell('pwd', '17.0.0.1')
sg2.run()
sg2.print_result() # invalid ip
sg3 = RemoteShell('pwd', '1711.0.0.1')
sg3.run()
sg3.print_result() # ip without trust relation
sg3 = RemoteShell('pwd', '10.145.132.247')
sg3.run()
sg3.print_result() sh = SuShell('pwd', 'ossuser')
sh.run()
sh.print_result() # wrong user
si = SuShell('pwd', 'ossuser123')
si.run()
si.print_result() # user need password
si = SuShell('pwd', 'root')
si.run()
si.print_result()

[蟒蛇菜谱] Python封装shell命令的更多相关文章

  1. python 调用 shell 命令方法

    python调用shell命令方法 1.os.system(cmd) 缺点:不能获取返回值 2.os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等   ...

  2. python 调用shell命令三种方法

    #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...

  3. python 调用 shell 命令

    记录 python 调用 shell 命令的方法 加载 os 模块, 使用 os 类 import os; os.system("ls /");

  4. 用Python调用Shell命令

    Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如下几种方式: 第一种 ...

  5. python执行shell命令

    1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如下命令,返回运行状态status os.system('cat /etc/passwdqc ...

  6. python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

  7. (转载)python调用shell命令之os 、commands、subprocess

    linux系统下进入python交互式环境: 一.os 模块 1.1.os模块的exec方法簇: python交互界面中: In [1]: import os In [2]: os.exec os.e ...

  8. python调用shell命令之三慷慨法

    preface: 忙于近期的任务,须要用到libsvm的一些命令.如在终端执行java svm_train train_file model_file. pythonsubset.py file tr ...

  9. python调用shell命令

    1.subprocess介绍 官方推荐 subprocess模块,os.system(command) 这个废弃了 亲测 os.system 使用sed需要进行字符转义,非常麻烦 python3 su ...

随机推荐

  1. 【转】 linux编程之GDB调试

    GDB是一套字符界面的程序集,可以用它在linux上调试C和C++程序,它提供了以下的功能: 1 在程序中设置断点,当程序运行到断点处暂停 2 显示变量的值,可以打印或者监视某个变量,将某个变量的值显 ...

  2. UINavigationController导航控制器初始化 导航控制器栈的push和pop跳转理解

    (1)导航控制器初始化的时候一般都有一个根视图控制器,导航控制器相当于一个栈,里面装的是视图控制器,最先进去的在最下面,最后进去的在最上面.在最上面的那个视图控制器的视图就是这个导航控制器对外展示的界 ...

  3. 习题 5: 更多的变量和打印 | 笨办法学 Python

    一. 简述 “格式化字符串(format string)” -  每一次你使用 ' ’ 或 " " 把一些文本引用起来,你就建立了一个字符串. 字符串是程序将信息展示给人的方式. ...

  4. Ridit分析

    对于有序分类资料,由于指标存在等级顺序,因此不能使用卡方检验,除了使用秩和检验之外,ridit检验也是分析有序分类资料的常用方法,属于非参数检验. ridit检验的基本做法是将一组有序分组资料转换成一 ...

  5. spring使用Email邮件系统

    1.提供邮件信息发送接收,附件绑定功能. 1.配置spring-email.xml文件 <context:property-placeholder location="classpat ...

  6. Dedecms有效防止采集的两个实用办法

    现在的采集真是无处不在,尤其是对一些原创性站点,真是烦透了这些采集的人们,如何预防和防止采集呢,站长们!今天先说一下dedecms防采集的办法. 1.随机模版 方法:你多复制N多模版,在body标记附 ...

  7. js判断是手机还是电脑访问网站

    js判断是手机还是电脑访问网站                               <script type="text/javascript"> <!- ...

  8. Webstorm 下的Angular2.0开发之路

    人一旦上了年纪,记忆力就变得越来越不好. 最近写了许多的博文,倒不是为了给谁看,而是方便自己来搜索,不然一下子又忘记了. 如果恰巧帮助到了你,也是我的荣幸~~~~~~~~~~~~ 废话不多说,看正题~ ...

  9. ASP.NET 教程(一)

    ASP.NET 是一个开发框架,用于通过 HTML.CSS.JavaScript 以及服务器脚本来构建网页和网站. ASP.NET 支持三种开发模式: Web Pages.MVC (Model Vie ...

  10. Excel函数汇总:

    /** *D1—要查找的目标值 *G:G—查找的单元格范围,G:G表示G列 *1—查找第一个匹配 *FALSE—找到结果即返回 */ VLOOKUP(D1,G:G,1,FALSE):返回查找到的单元格 ...