首頁 >後端開發 >Python教學 >python巡檢腳本怎麼寫

python巡檢腳本怎麼寫

PHPz
PHPz轉載
2023-05-10 13:22:061630瀏覽

方法一、使用os模組的system方法

os.system(cmd),其回傳值是shell指令運行後傳回的狀態碼,
int類型,
0--表示shell指令成功執行,
256--表示shell找不到,
此方法適用於shell指令不需要輸出內容的場景。

python巡檢腳本怎麼寫

方法二、使用os.popen()

該方法以檔案的形式傳回shell指令執行後的結果,
需要取得內容時可使用read()或readlines()方法,舉例如下:

python巡檢腳本怎麼寫

python巡檢腳本怎麼寫

#方法三、使用commands模組,有三種方法可以使用

(1)commands.getstatusoutput(cmd),其以字串的形式傳回的是輸出結果和狀態碼,即(status,output)。

(2)commands.getoutput(cmd),傳回cmd的輸出結果。

(3)commands.getstatus(file),傳回ls -l file的執行結果字串,呼叫了getoutput,不建議使用此方法

python巡檢腳本怎麼寫

python巡檢腳本怎麼寫

方法四、subprocess模組

允許創建很多子進程,創建的時候能指定子進程和子進程的輸入、輸出、錯誤輸出管道,執行後可以獲取輸出結果和執行狀態。

(1)subprocess.run():python3.5新增的函數, 執行指定的指令, 等待指令執行完成後傳回一個包含執行結果的CompletedProcess類別的實例。

(2)subprocess.call():執行指定的指令,傳回指令執行狀態, 功能類似os.system(cmd)。

(3)subprocess.check_call():python2.5中新增的函數, 執行指定的指令, 如果執行成功則傳回狀態碼, 否則拋出例外。

說明: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 。否則預設已數組形式表示shell變量,如"ls","-l"。

當使用比較複雜的shell語句時,可以先使用shlex模組的shlex.split()方法來幫助格式化指令,然後在傳遞給run()方法或Popen。

python巡檢腳本怎麼寫

python巡檢腳本怎麼寫

附上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

以上是python巡檢腳本怎麼寫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除