我正在撰寫一個 python 腳本,以在每次創建 VM 時自動安裝一些工具,并且由于我不是 bash 粉絲,所以我使用 python 來完成它。問題是apt安裝需要 sudo 權限,而pip安裝不需要。
在所有 apt 安裝之后,我正在尋找一種將我的權限降級回普通用戶的方法。
目前我嘗試了一個非常丑陋的單線器,比如os.system(f"su {user} && ...")或subprocess.Popen(...)
有沒有靠譜的方法?
uj5u.com熱心網友回復:
您可以使用帶有或的apt命令串列。如果沒有提供密碼,它也可以提示輸入密碼:subprocesspexpectgetpass
注意- 使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480497.html
標籤:Python python-3.x linux 重击
