您现在的位置是:亿华云 > 域名

Python 执行 Linux 操作系统命令

亿华云2025-10-04 03:16:50【域名】6人已围观

简介在开发运维脚本过程中,经常需要执行一些操作系统命令,常用方法如下:1、使用 os.system>>> import os>>> cmd = ls />>

在开发运维脚本过程中,执行作系经常需要执行一些操作系统命令,统命常用方法如下:

1、执行作系使用 os.system

Python 执行 Linux 操作系统命令

>>> import os

Python 执行 Linux 操作系统命令

>>> cmd = ls /

Python 执行 Linux 操作系统命令

>>> res = os.system(cmd)

bin  boot  data  dev  etc  home  lib  lib64  media  mnt  opt  oracle  proc  root  run  sbin  srv  sys  tmp  usr  var

>>> print(res)

0

特点:

(1)Python 内置方法,统命执行成功返回 0,执行作系并在标准输出打印命令执行结果

(2)不能返回命令的统命运行结果

2、使用 commands.getstatusoutput

>>> import os commands

>>> cmd = ls /

>>> status,执行作系output = commands.getstatusoutput(cmd)

status 为命令执行的状态,成功返回 0 ,统命出错返回非 0 值;

output 是云服务器提供商执行作系命令的执行结果

特点:

(1)commands 只能在 Python2.x 版本使用,而且并不是统命每一个 Python2.x 版本 都自带了该模块;

(2)commands 包在 Python3 中已经废弃

3、使用 subprocess.Popen

>>> from subprocess import Popen,执行作系 PIPE

>>> process = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)

>>> stdout, stderr = process.communicate()

stdout 为命令执行结果,stderr 为命令错误信息。统命注意,执行作系某些命令即便执行成功,统命也会有错误提示信息,执行作系但不影响结果。亿华云计算

特点:

(1)Python2.x 和 Python3.x 内置模块

(2)可以同时返回命令执行结果和错误信息

(3)可以获取到命令的退出码

综上,推荐使用第三种方法。

一个执行操作系统命令的函数可以封装如下,支持基于互信的远程节点命令执行,返回标注输出、标注错误和退出码

from subprocess import Popen, PIPE

def exec_command(shell_cmd, hostname=None):

    if hostname:

        p = Popen(/usr/bin/ssh -Tq +hostname, shell=True, stdout=PIPE, stdin=PIPE)

        p.stdin.write(str.encode(shell_cmd))

        p.stdin.flush()

    else:

        p = Popen(shell_cmd, shell=True, stdout=PIPE, stdin=PIPE)

    stdout, stderr = p.communicate()

    if stdout:

        stdout = stdout.decode()

    if stderr:

        stderr = stderr.decode()

    return stdout, stderr, p.poll()

很赞哦!(6)