2

I know how to get the current user using os or getpass.getuser(), but is there a way to get a list of all user and not only the current one? Read os and getpass documentations but i didn't thing anything.

Arus
  • 21
  • 1
  • 3

2 Answers2

1

This is OS-specific.

In Linux, see Python script to list users and groups.

In Windows:

  • via WMI

    • parse the output of wmic UserAccount get Name, or
    • make the same call with the wmi module:

      import wmi
      w=wmi.WMI()
      # The argument (field filter) is only really needed if browsing a large domain
      # as per the warning at https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-useraccount
      # Included it for the sake of completeness
      for u in w.Win32_UserAccount(["Name"]): #Net
          print u.Name
      del u
      
  • via the NetUserEnum API

    • parse the output of net user, or
    • make the same call with pywin32:

      import win32net, win32netcon
      names=[]; resumeHandle=0
      while True:
          data,_,resumeHandle=win32net.NetUserEnum(None,0,
                  win32netcon.FILTER_NORMAL_ACCOUNT,resumeHandle)
          names.extend(e["name"] for e in data)
          if not resumeHandle: break
      del data,resumeHandle
      print names
      
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
0

Two ideas for methods that are Windows-specific:

from pathlib import Path
users = [x.name for x in Path(r'C:\Users').glob('*') if x.name not in ['Default', 'Default User', 'Public', 'All Users'] and x.is_dir()]
print(users)

Paths in C:\Users

import os
os.system('net user > users.txt')
users = Path('./users.txt').read_text()
print(users)

Output from net user

Simon
  • 5,464
  • 6
  • 49
  • 85
  • 1
    The 1st one is defective: https://superuser.com/questions/608931/list-all-user-accounts-on-a-windows-system-via-command-line – ivan_pozdeev May 24 '19 at 23:58
  • `net user` output is not the raw list and will have to be parsed (with possible problems if names have unusual and/or national characters). – ivan_pozdeev Jun 05 '19 at 15:58