在Python中,您不能直接使用sudo
命令來設置權限有效期
import os
import pwd
import grp
import time
def set_sudo_password(username, password, expiration_seconds=3600):
# 獲取用戶的UID和GID
uid = pwd.getpwnam(username).pw_uid
gid = grp.getgrnam(username).gr_gid
# 設置密碼和過期時間
sudoers_file = "/etc/sudoers"
password_hash = pwd.hashpw(password.encode('utf-8'), pwd.STD_PASSWORD_HASH)
expiration_time = time.time() + expiration_seconds
# 編輯sudoers文件
with open(sudoers_file, "r") as file:
lines = file.readlines()
with open(sudoers_file, "w") as file:
for line in lines:
if line.startswith("username ALL=(ALL) NOPASSWD:"):
line = f"{line.split()[0]} ALL=(ALL) NOPASSWD: /usr/bin/sudo -u {username} /usr/bin/su -c 'your-command' -- {expiration_time}\n"
file.write(line)
# 更新用戶的密碼
os.system(f"echo '{username}:{password_hash}' | chpasswd")
# 使用示例
set_sudo_password("username", "your-password", 3600) # 設置用戶名為username的用戶的密碼,并設置有效期為3600秒(1小時)
請注意,這個示例需要您具有root權限才能運行。此外,這個示例僅用于演示目的,實際應用中請確保正確處理異常和錯誤。