Create a local group with a new user

Introduction

The requirement: To create a new local group with a new user inside it.

Discussion

Depending on your security context, it's considered good practice to run long-running processes such as services under a controlled user with minimum privileges. It might make sense also to create a specific group for this and perhaps other users. The code below creates a simple group and a relatively unprivileged user. Obviously, you still need to secure resources for this user in particular.

Caveat Lector: I am not a security expert and this is example code

The Code

import win32net
import win32netcon

USER = "user"
GROUP = "group"

#
# Create a new user with minimum privs.
# If it exists already, drop it first.
#
user_info = dict (
  name = USER,
  password = "Passw0rd",
  priv = win32netcon.USER_PRIV_USER,
  home_dir = None,
  comment = None,
  flags = win32netcon.UF_SCRIPT,
  script_path = None
)

try:
  win32net.NetUserDel (None, USER)
except win32net.error, (number, context, message):
  if number <> 2221:
    raise
win32net.NetUserAdd (None, 1, user_info)

#
# Create a new group
# If it exists already, drop it first.
#
group_info = dict (
  name = GROUP
)

try:
  win32net.NetLocalGroupDel (None, GROUP)
except win32net.error, (number, context, message):
  if number <> 2220:
    raise
win32net.NetLocalGroupAdd (None, 0, group_info)

#
# Add the new user to the new group
#
user_group_info = dict (
  domainandname = USER
)

win32net.NetLocalGroupAddMembers (None, GROUP, 3, [user_group_info])