要使用Python脚本管理Linux用户,你可以使用os
和pwd
模块
import os
import pwd
username = "newuser"
password = "newpassword"
uid = pwd.getpwnam(username).pw_uid
gid = pwd.getpwnam(username).pw_gid
# 创建用户组
os.system(f"groupadd {username}")
# 将用户添加到用户组
os.system(f"usermod -aG {username} {username}")
# 设置密码
os.system(f"echo '{password}' | chpasswd")
# 启用用户
os.system(f"passwd -u {username}")
import os
import pwd
username = "username"
# 获取用户的UID
uid = pwd.getpwnam(username).pw_uid
# 删除用户组
os.system(f"groupdel {username}")
# 删除用户
os.system(f"userdel -r {username}")
import os
import pwd
username = "username"
new_password = "newpassword"
# 获取用户的UID
uid = pwd.getpwnam(username).pw_uid
# 设置新密码
os.system(f"echo '{new_password}' | chpasswd")
import os
import pwd
username = "username"
groupname = "groupname"
# 获取用户的UID和用户组的GID
uid = pwd.getpwnam(username).pw_uid
gid = pwd.getpwnam(groupname).pw_gid
# 将用户添加到用户组
os.system(f"usermod -aG {groupname} {username}")
import os
import pwd
username = "username"
groupname = "groupname"
# 获取用户的UID和用户组的GID
uid = pwd.getpwnam(username).pw_uid
gid = pwd.getpwnam(groupname).pw_gid
# 将用户从用户组中删除
os.system(f"gpasswd -d {username} {groupname}")
请注意,这些示例使用os.system()
执行命令,这可能会导致安全风险。在实际应用中,建议使用subprocess
模块以更安全的方式执行命令。