python 巡檢腳本的項目實踐
方法一、使用os模塊的system方法
os.system(cmd),其返回值是shell指令運行后返回的狀態(tài)碼,
int類型,
0--表示shell指令成功執(zhí)行,
256--表示shell未找到,
該方法適用于shell命令不需要輸出內(nèi)容的場景。

方法二、使用os.popen()
該方法以文件的形式返回shell指令運行后的結(jié)果,
需要獲取內(nèi)容時可使用read()或readlines()方法,舉例如下:


方法三、使用commands模塊,有三個方法可以使用
(1)commands.getstatusoutput(cmd),其以字符串的形式返回的是輸出結(jié)果和狀態(tài)碼,即(status,output)。
(2)commands.getoutput(cmd),返回cmd的輸出結(jié)果。
(3)commands.getstatus(file),返回ls -l file的執(zhí)行結(jié)果字符串,調(diào)用了getoutput,不建議使用此方法


方法四、subprocess模塊
允許創(chuàng)建很多子進(jìn)程,創(chuàng)建的時候能指定子進(jìn)程和子進(jìn)程的輸入、輸出、錯誤輸出管道,執(zhí)行后能獲取輸出結(jié)果和執(zhí)行狀態(tài)。
(1)subprocess.run():python3.5中新增的函數(shù), 執(zhí)行指定的命令, 等待命令執(zhí)行完成后返回一個包含執(zhí)行結(jié)果的CompletedProcess類的實例。
(2)subprocess.call():執(zhí)行指定的命令, 返回命令執(zhí)行狀態(tài), 功能類似os.system(cmd)。
(3)subprocess.check_call():python2.5中新增的函數(shù), 執(zhí)行指定的命令, 如果執(zhí)行成功則返回狀態(tài)碼, 否則拋出異常。
說明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
args:表示shell指令,若以字符串形式給出shell指令,如"ls -l "則需要使shell = Ture。否則默認(rèn)已數(shù)組形式表示shell變量,如"ls","-l"。
當(dāng)使用比較復(fù)雜的shell語句時,可以先使用shlex模塊的shlex.split()方法來幫助格式化命令,然后在傳遞給run()方法或Popen。


附上python2.7中的subprocess模塊源碼供理解(pycharm查看方法源碼,ctrl+左鍵)。
# Stubs for subprocess
# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub
from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text
_FILE = Union[None, int, IO[Any]]
_TXT = Union[bytes, Text]
_CMD = Union[_TXT, Sequence[_TXT]]
_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]
# Same args as Popen.__init__
def call(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stdout: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> int: ...
def check_call(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stdout: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> int: ...
# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> bytes: ...
PIPE = ... # type: int
STDOUT = ... # type: int
class CalledProcessError(Exception):
returncode = 0
# morally: _CMD
cmd = ... # type: Any
# morally: Optional[bytes]
output = ... # type: Any
def __init__(self,
returncode: int,
cmd: _CMD,
output: Optional[bytes] = ...) -> None: ...
class Popen:
stdin = ... # type: Optional[IO[Any]]
stdout = ... # type: Optional[IO[Any]]
stderr = ... # type: Optional[IO[Any]]
pid = 0
returncode = 0
def __init__(self,
args: _CMD,
bufsize: int = ...,
executable: Optional[_TXT] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[_TXT] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...) -> None: ...
def poll(self) -> int: ...
def wait(self) -> int: ...
# morally: -> Tuple[Optional[bytes], Optional[bytes]]
def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ...
def send_signal(self, signal: int) -> None: ...
def terminate(self) -> None: ...
def kill(self) -> None: ...
def __enter__(self) -> 'Popen': ...
def __exit__(self, type, value, traceback) -> bool: ...
# Windows-only: STARTUPINFO etc.
STD_INPUT_HANDLE = ... # type: Any
STD_OUTPUT_HANDLE = ... # type: Any
STD_ERROR_HANDLE = ... # type: Any
SW_HIDE = ... # type: Any
STARTF_USESTDHANDLES = ... # type: Any
STARTF_USESHOWWINDOW = ... # type: Any
CREATE_NEW_CONSOLE = ... # type: Any
CREATE_NEW_PROCESS_GROUP = ... # type: Any到此這篇關(guān)于python 巡檢腳本的項目實踐的文章就介紹到這了,更多相關(guān)python 巡檢腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python Socket網(wǎng)絡(luò)編程實現(xiàn)C/S模式和P2P
這篇文章主要介紹了python Socket網(wǎng)絡(luò)編程實現(xiàn)C/S模式和P2P,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
numpy存取數(shù)據(jù)(tofile/fromfile)的實現(xiàn)
本文主要介紹了numpy存取數(shù)據(jù)(tofile/fromfile)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
python通過pillow識別動態(tài)驗證碼的示例代碼
在上網(wǎng)時,經(jīng)常會遇到驗證碼,本次試驗將帶領(lǐng)大家認(rèn)識驗證碼的一些特性,并利用 Python 中的 pillow 庫完成對驗證碼的破解。感興趣的可以了解一下2021-11-11
基于python的opencv圖像處理實現(xiàn)對斑馬線的檢測示例
這篇文章主要介紹了基于python的opencv圖像處理實現(xiàn)對斑馬線的檢測示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Python?Django教程之實現(xiàn)新聞應(yīng)用程序
Django是一個用Python編寫的高級框架,它允許我們創(chuàng)建服務(wù)器端Web應(yīng)用程序。在本文中,我們將了解如何使用Django創(chuàng)建新聞應(yīng)用程序,感興趣的可以嘗試一下2022-10-10
Python?BeautifulSoup4實現(xiàn)數(shù)據(jù)解析與提取
Beautiful?Soup是一個Python的庫,用于解析HTML和XML文檔,提供了方便的數(shù)據(jù)提取和操作功能,下面小編就來和大家詳細(xì)聊聊如何利用BeautifulSoup4實現(xiàn)數(shù)據(jù)解析與提取吧2023-10-10

