簡體   English   中英

Python 同時作為用戶和 sudo 運行

[英]Python run both as user and sudo

我正在編寫一個 python 腳本,以便在每次創建 VM 時自動安裝一些工具,並且由於我不是 bash 粉絲,所以我正在使用 python 來完成它。 問題是apt安裝需要 sudo 權限,而pip安裝不需要。

在所有 apt 安裝之后,我正在尋找一種將我的權限降級回普通用戶的方法。

目前我嘗試了一個非常丑陋的單行器,比如os.system(f"su {user} && ...") subprocess.Popen(...)

有沒有靠譜的方法?

您可以將apt命令列表與subprocesspexpect 如果使用getpass未提供密碼,它也可以提示輸入密碼:

注意- 使用 Python 3.8.10 在 Ubuntu 20.04 上測試

注意- 更新為使用和測試管道。引用 - 謝謝,點!

import pipes
import shlex
import subprocess
from getpass import getpass

import pexpect

sudo_password = '********'
# First command in double quotes to test pipes.quote - Thx, pts!
commands = ["apt show python3 | grep 'Version'",
            'sudo -S apt show python3 | grep Version', ]

print('Using subprocess...')
for c in commands:
    c = str.format('bash -c {0}'.format(pipes.quote(c)))
    # Use sudo_password if not None or empty; else, prompt for a password
    sudo_password = (
            sudo_password + '\r'
    ) if sudo_password and sudo_password.strip() else getpass() + '\r'
    p = subprocess.Popen(shlex.split(c), stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, universal_newlines=True)
    output, error = p.communicate(sudo_password)
    rc = p.returncode
    if rc != 0:
        raise RuntimeError('Unable to execute command {0}: {1}'.format(
            c, error.strip()))
    else:
        print(output.strip())

print('\nUsing pexpect...')
for c in commands:
    c = str.format('bash -c {0}'.format(pipes.quote(c)))
    command_output, exitstatus = pexpect.run(
        c,
        # Use sudo_password if not None or empty; else, prompt for a password
        events={
            '(?i)password': (
                    sudo_password + '\r'
            ) if sudo_password and sudo_password.strip() else (
                    getpass() + '\r')
        },
        withexitstatus=True)
    if exitstatus != 0:
        raise RuntimeError('Unable to execute command {0}: {1}'.format(
            c, command_output))
    # For Python 2.x, use string_escape.
    # For Python 3.x, use unicode_escape.
    # Do not use utf-8; Some characters, such as backticks, may cause exceptions
    print(command_output.decode('unicode_escape').strip())

輸出:

Using subprocess...
Version: 3.8.2-0ubuntu2
Version: 3.8.2-0ubuntu2

Using pexpect (and getpass)...

Version: 3.8.2-0ubuntu2
[sudo] password for stack: 

Version: 3.8.2-0ubuntu2

Process finished with exit code 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM