Python封裝shell命令實(shí)例分析
本文實(shí)例講述了Python封裝shell命令的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
# -*- coding: utf-8 -*- import os import subprocess import signal import pwd import sys class MockLogger(object): '''模擬日志類。方便單元測(cè)試。''' def __init__(self): self.info = self.error = self.critical = self.debug def debug(self, msg): print "LOGGER:"+msg class Shell(object): '''完成Shell腳本的包裝。 執(zhí)行結(jié)果存放在Shell.ret_code, Shell.ret_info, Shell.err_info中 run()為普通調(diào)用,會(huì)等待shell命令返回。 run_background()為異步調(diào)用,會(huì)立刻返回,不等待shell命令完成 異步調(diào)用時(shí),可以使用get_status()查詢狀態(tài),或使用wait()進(jìn)入阻塞狀態(tài), 等待shell執(zhí)行完成。 異步調(diào)用時(shí),使用kill()強(qiáng)行停止腳本后,仍然需要使用wait()等待真正退出。 TODO 未驗(yàn)證Shell命令含有超大結(jié)果輸出時(shí)的情況。 ''' def __init__(self, cmd): self.cmd = cmd # cmd包括命令和參數(shù) self.ret_code = None self.ret_info = None self.err_info = None #使用時(shí)可替換為具體的logger self.logger = MockLogger() def run_background(self): '''以非阻塞方式執(zhí)行shell命令(Popen的默認(rèn)方式)。 ''' self.logger.debug("run %s"%self.cmd) # Popen在要執(zhí)行的命令不存在時(shí)會(huì)拋出OSError異常,但shell=True后, # shell會(huì)處理命令不存在的錯(cuò)誤,因此沒有了OSError異常,故不用處理 self._process = subprocess.Popen(self.cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #非阻塞 def run(self): '''以阻塞方式執(zhí)行shell命令。 ''' self.run_background() self.wait() def run_cmd(self, cmd): '''直接執(zhí)行某條命令。方便一個(gè)實(shí)例重復(fù)使用執(zhí)行多條命令。 ''' self.cmd = cmd self.run() def wait(self): '''等待shell執(zhí)行完成。 ''' 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): '''獲取腳本運(yùn)行狀態(tài)(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): '''遠(yuǎn)程執(zhí)行命令(ssh方式)。 XXX 含特殊字符的命令可能導(dǎo)致調(diào)用失效,如雙引號(hào),美元號(hào)$ NOTE 若cmd含有雙引號(hào),可使用RemoteShell2 ''' def __init__(self, cmd, ip): ssh = ("ssh -o PreferredAuthentications=publickey -o " "StrictHostKeyChecking=no -o ConnectTimeout=10") # 不必檢查IP有效性,也不必檢查信任關(guān)系,有問題shell會(huì)報(bào)錯(cuò) cmd = '%s %s "%s"'%(ssh, ip, cmd) Shell.__init__(self, cmd) class RemoteShell2(RemoteShell): '''與RemoteShell相同,只是變換了引號(hào)。 ''' def __init__(self, cmd, ip): RemoteShell.__init__(self, cmd, ip) self.cmd = "%s %s '%s'"%(ssh, ip, cmd) class SuShell(Shell): '''切換用戶執(zhí)行命令(su方式)。 XXX 只適合使用root切換至其它用戶。 因?yàn)槠渌袚Q用戶后需要輸入密碼,這樣程序會(huì)掛住。 XXX 含特殊字符的命令可能導(dǎo)致調(diào)用失效,如雙引號(hào),美元號(hào)$ NOTE 若cmd含有雙引號(hào),可使用SuShell2 ''' def __init__(self, cmd, user): if os.getuid() != 0: # 非root用戶直接報(bào)錯(cuò) raise Exception('SuShell must be called by root user!') cmd = 'su - %s -c "%s"'%(user, cmd) Shell.__init__(self, cmd) class SuShell2(SuShell): '''與SuShell相同,只是變換了引號(hào)。 ''' def __init__(self, cmd, user): SuShell.__init__(self, cmd, user) self.cmd = "su - %s -c '%s'"%(user, cmd) class SuShellDeprecated(Shell): '''切換用戶執(zhí)行命令(setuid方式)。 執(zhí)行的函數(shù)為run2,而不是run XXX 以“不干凈”的方式運(yùn)行:僅切換用戶和組,環(huán)境變量信息不變。 XXX 無(wú)法獲取命令的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用戶直接報(bào)錯(cuò) raise Exception('SuShell2 must be called by root user!') child_pid = os.fork() if child_pid == 0: # 子進(jìn)程干活 uid, gid = pwd.getpwnam(self.user)[2:4] os.setgid(gid) # 必須先設(shè)置組 os.setuid(uid) self.run() sys.exit(0) # 子進(jìn)程退出,防止繼續(xù)執(zhí)行其它代碼 else: # 父進(jìn)程等待子進(jìn)程退出 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()
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
- 從零學(xué)python系列之淺談pickle模塊封裝和拆封數(shù)據(jù)對(duì)象的方法
- 基于python3 類的屬性、方法、封裝、繼承實(shí)例講解
- Python數(shù)據(jù)操作方法封裝類實(shí)例
- Python的動(dòng)態(tài)重新封裝的教程
- Python面向?qū)ο笾^承和組合用法實(shí)例分析
- Python面向?qū)ο笾涌?、抽象類與多態(tài)詳解
- Python面向?qū)ο笾o態(tài)屬性、類方法與靜態(tài)方法分析
- Python面向?qū)ο笾瓷?自省機(jī)制實(shí)例分析
- Python封裝原理與實(shí)現(xiàn)方法詳解
相關(guān)文章
利用Rust實(shí)現(xiàn)Python加速的技巧分享
這篇文章主要想來和大家一起探討一下關(guān)于使用Rust對(duì)Python計(jì)算進(jìn)行加速的問題,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-09-09Python內(nèi)置模塊Collections的使用教程詳解
collections 是 Python 的一個(gè)內(nèi)置模塊,所謂內(nèi)置模塊的意思是指 Python 內(nèi)部封裝好的模塊,無(wú)需安裝即可直接使用。本文將詳解介紹Collections的使用方式,需要的可以參考一下2022-03-03Python數(shù)據(jù)結(jié)構(gòu)之圖的存儲(chǔ)結(jié)構(gòu)詳解
本篇章主要介紹圖,包括圖的定義、相關(guān)術(shù)語(yǔ)、性質(zhì)及存儲(chǔ)結(jié)構(gòu),并用Python代碼實(shí)現(xiàn),需要的朋友可以參考下2021-06-06pandas實(shí)現(xiàn)數(shù)據(jù)讀取&清洗&分析的項(xiàng)目實(shí)踐
近期因工作需要,需對(duì)幾十萬(wàn)條商品和訂單數(shù)據(jù)進(jìn)行初步的數(shù)據(jù)分析,本文主要pandas實(shí)現(xiàn)數(shù)據(jù)讀取&清洗&分析的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2022-05-05Django模型層實(shí)現(xiàn)多表關(guān)系創(chuàng)建和多表操作
使用django ORM可以創(chuàng)建多表關(guān)系,并且也支持多張表之間的操作,以創(chuàng)建表關(guān)系和查詢兩部分說明django ORM的多表操作,本文就詳細(xì)的介紹一下,感興趣的可以了解一下2021-07-07scikit-learn線性回歸,多元回歸,多項(xiàng)式回歸的實(shí)現(xiàn)
這篇文章主要介紹了scikit-learn線性回歸,多元回歸,多項(xiàng)式回歸的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08如何在windows下安裝Pycham2020軟件(方法步驟詳解)
這篇文章主要介紹了在windows下安裝Pycham2020軟件方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05使用Python的OpenCV模塊識(shí)別滑動(dòng)驗(yàn)證碼的缺口(推薦)
這篇文章主要介紹了使用Python的OpenCV模塊識(shí)別滑動(dòng)驗(yàn)證碼的缺口,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05Python面向?qū)ο笾惡蛯?duì)象屬性的增刪改查操作示例
這篇文章主要介紹了Python面向?qū)ο笾惡蛯?duì)象屬性的增刪改查操作,結(jié)合實(shí)例形式分析了Python面向?qū)ο笙嚓P(guān)的類與對(duì)象屬性常見操作技巧,需要的朋友可以參考下2018-12-12Python必備技巧之Pandas數(shù)據(jù)合并函數(shù)
Pandas中一共有五個(gè)數(shù)據(jù)合并函數(shù),分別為:concat、append、merge、join、combine,本文詳細(xì)講解這五個(gè)函數(shù)的使用方法,需要的可以參考一下2022-03-03