溫馨提示×

python sudo命令如何設置權限有效期

小樊
93
2024-12-12 01:16:38
欄目: 編程語言

在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權限才能運行。此外,這個示例僅用于演示目的,實際應用中請確保正確處理異常和錯誤。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女