在Linux中,Python命令本身并不提供用户管理功能
- 创建新用户:
import pwd import spwd username = "newuser" password = "newpassword" uid = pwd.getpwnam(username).pw_uid gid = pwd.getpwnam(username).pw_gid spwd.setspnam(username, (uid, password, 0, 0, 0, 0, 0, 0, 0))
- 删除用户:
import pwd username = "newuser" uid = pwd.getpwnam(username).pw_uid # 删除用户主目录 import shutil shutil.rmtree(f"/home/{username}") # 从系统用户列表中删除用户 import pwd for entry in pwd.getpwall(): if entry.pw_uid == uid: pwd.delpwent(entry.pw_uid) break
- 修改用户密码:
import pwd import spwd username = "newuser" new_password = "newpassword" uid = pwd.getpwnam(username).pw_uid spwd.setspnam(username, (uid, new_password, 0, 0, 0, 0, 0, 0, 0))
- 将用户添加到某个用户组:
import pwd import grp username = "newuser" group_name = "newgroup" uid = pwd.getpwnam(username).pw_uid gid = grp.getgrnam(group_name).gr_gid # 将用户添加到用户组 import pwd pwd.getpwnam(username).pw_gid = gid
请注意,这些示例仅用于演示目的,实际应用中可能需要更严格的错误处理和安全性考虑。在执行这些操作之前,请确保你具有适当的权限,并遵循最佳实践。