Skip to content

Instantly share code, notes, and snippets.

@albertofwb
Last active August 23, 2023 04:42
Show Gist options
  • Save albertofwb/25f7932f6b88e786e6b7134fc8ab1916 to your computer and use it in GitHub Desktop.
Save albertofwb/25f7932f6b88e786e6b7134fc8ab1916 to your computer and use it in GitHub Desktop.
linux 系统以 root 权限运行系统命令
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner()
@singleton
class SudoPass:
def __init__(self):
self._passwd = None
def set_pass(self, password: str):
self._passwd = password
def get_pass(self) -> str:
return self._passwd
def is_set(self) -> bool:
return self._passwd is not None
def get_sudo_cmd(cmd: str) -> str:
# original cmd could be fine if we already started as root
if os.geteuid() == 0:
return cmd
elif not SudoPass.is_set():
return "{} 2>/dev/null".format(cmd)
sudo_cmd = "echo {} | sudo -S {} 2>/dev/null".format(SudoPass.get_pass(), cmd)
return sudo_cmd
def run_as_root(cmd: str):
# 使用本函数之前,请先调用 SudoPass.set_pass(your_password)
# 并确保当前用户具有 sudo 权限
sudo_cmd = get_sudo_cmd(cmd)
out = os.popen(sudo_cmd).read()
return out.strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment