Python封装shell命令实例分析
本文实例讲述了Python封装shell命令的方法。分享给大家供大家参考。具体实现方法如下:
#-*-coding:utf-8-*-
importos
importsubprocess
importsignal
importpwd
importsys
classMockLogger(object):
'''模拟日志类。方便单元测试。'''
def__init__(self):
self.info=self.error=self.critical=self.debug
defdebug(self,msg):
print"LOGGER:"+msg
classShell(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()
defrun_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)#非阻塞
defrun(self):
'''以阻塞方式执行shell命令。
'''
self.run_background()
self.wait()
defrun_cmd(self,cmd):
'''直接执行某条命令。方便一个实例重复使用执行多条命令。
'''
self.cmd=cmd
self.run()
defwait(self):
'''等待shell执行完成。
'''
self.logger.debug("waiting%s"%self.cmd)
self.ret_info,self.err_info=self._process.communicate()#阻塞
#returncode:Anegativevalue-Nindicatesthatthechildwas
#terminatedbysignalN
self.ret_code=self._process.returncode
self.logger.debug("waiting%sdone.returncodeis%d"%(self.cmd,
self.ret_code))
defget_status(self):
'''获取脚本运行状态(RUNNING|FINISHED)
'''
retcode=self._process.poll()
ifretcode==None:
status="RUNNING"
else:
status="FINISHED"
self.logger.debug("%sstatusis%s"%(self.cmd,status))
returnstatus
#Python2.4的subprocess还没有send_signal,terminate,kill
#所以这里要山寨一把,2.7可直接用self._process的kill()
defsend_signal(self,sig):
self.logger.debug("sendsignal%sto%s"%(sig,self.cmd))
os.kill(self._process.pid,sig)
defterminate(self):
self.send_signal(signal.SIGTERM)
defkill(self):
self.send_signal(signal.SIGKILL)
defprint_result(self):
print"returncode:",self.ret_code
print"returninfo:",self.ret_info
print"errorinfo:",self.err_info
classRemoteShell(Shell):
'''远程执行命令(ssh方式)。
XXX含特殊字符的命令可能导致调用失效,如双引号,美元号$
NOTE若cmd含有双引号,可使用RemoteShell2
'''
def__init__(self,cmd,ip):
ssh=("ssh-oPreferredAuthentications=publickey-o"
"StrictHostKeyChecking=no-oConnectTimeout=10")
#不必检查IP有效性,也不必检查信任关系,有问题shell会报错
cmd='%s%s"%s"'%(ssh,ip,cmd)
Shell.__init__(self,cmd)
classRemoteShell2(RemoteShell):
'''与RemoteShell相同,只是变换了引号。
'''
def__init__(self,cmd,ip):
RemoteShell.__init__(self,cmd,ip)
self.cmd="%s%s'%s'"%(ssh,ip,cmd)
classSuShell(Shell):
'''切换用户执行命令(su方式)。
XXX只适合使用root切换至其它用户。
因为其它切换用户后需要输入密码,这样程序会挂住。
XXX含特殊字符的命令可能导致调用失效,如双引号,美元号$
NOTE若cmd含有双引号,可使用SuShell2
'''
def__init__(self,cmd,user):
ifos.getuid()!=0:#非root用户直接报错
raiseException('SuShellmustbecalledbyrootuser!')
cmd='su-%s-c"%s"'%(user,cmd)
Shell.__init__(self,cmd)
classSuShell2(SuShell):
'''与SuShell相同,只是变换了引号。
'''
def__init__(self,cmd,user):
SuShell.__init__(self,cmd,user)
self.cmd="su-%s-c'%s'"%(user,cmd)
classSuShellDeprecated(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)
defrun2(self):
ifos.getuid()!=0:#非root用户直接报错
raiseException('SuShell2mustbecalledbyrootuser!')
child_pid=os.fork()
ifchild_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__":
'''testcode'''
#1.testnormal
sa=Shell('who')
sa.run()
sa.print_result()
#2.teststderr
sb=Shell('ls/export/dir_should_not_exists')
sb.run()
sb.print_result()
#3.testbackground
sc=Shell('sleep1')
sc.run_background()
print'hellofromparentprocess'
print"returncode:",sc.ret_code
print"status:",sc.get_status()
sc.wait()
sc.print_result()
#4.testkill
importtime
sd=Shell('sleep2')
sd.run_background()
time.sleep(1)
sd.kill()
sd.wait()#NOTE,stillneedtowait
sd.print_result()
#5.testmultiplecommandanduncompletedcommandoutput
se=Shell('pwd;sleep1;pwd;pwd')
se.run_background()
time.sleep(1)
se.kill()
se.wait()#NOTE,stillneedtowait
se.print_result()
#6.testwrongcommand
sf=Shell('aaaaa')
sf.run()
sf.print_result()
#7.testinstancereusetorunothercommand
sf.cmd='echoaaaaa'
sf.run()
sf.print_result()
sg=RemoteShell('pwd','127.0.0.1')
sg.run()
sg.print_result()
#unreachableip
sg2=RemoteShell('pwd','17.0.0.1')
sg2.run()
sg2.print_result()
#invalidip
sg3=RemoteShell('pwd','1711.0.0.1')
sg3.run()
sg3.print_result()
#ipwithouttrustrelation
sg3=RemoteShell('pwd','10.145.132.247')
sg3.run()
sg3.print_result()
sh=SuShell('pwd','ossuser')
sh.run()
sh.print_result()
#wronguser
si=SuShell('pwd','ossuser123')
si.run()
si.print_result()
#userneedpassword
si=SuShell('pwd','root')
si.run()
si.print_result()
希望本文所述对大家的Python程序设计有所帮助。