【问题标题】:How to get all Windows/Linux user and not only current user with python如何使用 python 获取所有 Windows/Linux 用户,而不仅仅是当前用户
【发布时间】:2019-05-24 23:29:54
【问题描述】:

我知道如何使用 os 或 getpass.getuser() 获取当前用户,但有没有办法获取所有用户的列表,而不仅仅是当前用户?阅读 os 和 getpass 文档,但我什么都没做。

【问题讨论】:

标签: python getpass


【解决方案1】:

这是特定于操作系统的。

在 Linux 中,请参阅 Python script to list users and groups

在 Windows 中:

  • 通过 WMI

    • 解析wmic UserAccount get Name的输出,或者
    • 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://docs.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
      
  • 通过NetUserEnum API

    • 解析net user的输出,或者
    • 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
      

【讨论】:

    【解决方案2】:

    针对特定于 Windows 的方法的两个想法:

    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)
    

    C:\Users 中的路径

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

    来自net user的输出

    【讨论】:

    • 第一个有缺陷:superuser.com/questions/608931/…
    • net user 输出不是原始列表,必须对其进行解析(如果名称包含不寻常和/或国家字符,可能会出现问题)。
    猜你喜欢
    • 2017-06-15
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2021-01-12
    • 2012-06-24
    • 1970-01-01
    • 2012-01-18
    相关资源
    最近更新 更多