"""Local accounts on Windows as napalm-device-types' ``UserDict`` (NetOrk/netork#2889). :class:`WindowsOsUsersMixin` gives the driver ``get_os_users``. One script reads the accounts (``Get-LocalUser``), the local groups with their members (``Get-LocalGroupMember``) and the profiles' paths (``Win32_UserProfile``). Windows names an account by its security identifier, not a number: * ``uid`` is the relative identifier, the SID's last part: 500 for the built-in Administrator, 501 Guest, 1000 and up for accounts created. ``sid`` is the whole SID. * ``gid`` is 513, the primary group every local account has ("None"); Windows offers no other for them. * ``home`` is the profile's folder, empty for an account that never logged on and so has none; ``shell`` is empty. * ``groups`` are the local groups the account is a direct member of. A group whose members cannot be read -- ``Get-LocalGroupMember`` fails on a member SID it cannot resolve, and the ADSI fallback failed too -- names nobody. These are the host's own accounts. Who may log in and how (administrators, RDP rights, domain accounts) is the login accounts' contract, not this one. A domain controller has no local accounts -- ``Get-LocalUser`` would list the domain's -- and a host without the LocalAccounts module cannot list them; both raise ``NotImplementedError``. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from napalm_device_types.models import UserDict from napalm_windows._powershell import _as_list from napalm_windows._reading import json_object logger = logging.getLogger(__name__) _PS_OS_USERS = r""" $ErrorActionPreference = 'Stop' $role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole $local = [bool](Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue) $users = @() $groups = @() if ($role -lt 4 -and $local) { $homes = @{} Get-CimInstance -ClassName Win32_UserProfile | ForEach-Object { $homes[[string]$_.SID] = [string]$_.LocalPath } $users = @(Get-LocalUser | ForEach-Object { $sid = [string]$_.SID [pscustomobject]@{ name = [string]$_.Name; sid = $sid; home = $homes[$sid] } }) $groups = @(Get-LocalGroup | ForEach-Object { $group = $_ $members = $null try { $members = @(Get-LocalGroupMember -SID $group.SID | ForEach-Object { [string]$_.SID }) } catch { try { $adsi = [ADSI]"WinNT://$env:COMPUTERNAME/$($group.Name),group" $members = @($adsi.psbase.Invoke('Members') | ForEach-Object { $bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null) (New-Object System.Security.Principal.SecurityIdentifier($bytes, 0)).Value }) } catch { $members = $null } } [pscustomobject]@{ name = [string]$group.Name; members = $members } }) } ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{ domain_role = $role local_accounts = $local users = $users groups = $groups }) """ #: ``Win32_ComputerSystem.DomainRole`` of a backup and of a primary domain controller. _DOMAIN_CONTROLLER = 4 #: DOMAIN_GROUP_RID_USERS: the primary group of every local account. _PRIMARY_GROUP = 513 def _rid(sid: str) -> int: tail = sid.rsplit("-", 1)[-1] return int(tail) if tail.isdigit() else 0 def _memberships(groups: list[Any]) -> dict[str, list[str]]: """SID -> the names of the groups it is a direct member of, in the order read.""" member_of: dict[str, list[str]] = {} for group in groups: members = group.get("members") if members is None: logger.warning("the members of local group %r could not be read", group.get("name")) continue for sid in _as_list(members): member_of.setdefault(str(sid), []).append(str(group["name"])) return member_of def parse_os_users(raw: dict[str, Any]) -> list[UserDict]: """``_PS_OS_USERS``'s JSON as ``UserDict``s; see the module. :raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``. """ if int(raw.get("domain_role") or 0) >= _DOMAIN_CONTROLLER: raise NotImplementedError( "a domain controller has no local accounts; its accounts are the domain's" ) if not raw.get("local_accounts"): raise NotImplementedError("Get-LocalUser is not available on this host") member_of = _memberships(_as_list(raw.get("groups"))) users: list[UserDict] = [] for user in _as_list(raw.get("users")): sid = str(user.get("sid") or "") users.append( { "username": str(user["name"]), "uid": _rid(sid), "gid": _PRIMARY_GROUP, "home": str(user.get("home") or ""), "shell": "", "groups": member_of.get(sid, []), "sid": sid, } ) return users class WindowsOsUsersMixin: """``get_os_users`` from the LocalAccounts cmdlets; the driver carries the script.""" if TYPE_CHECKING: # pragma: no cover - declared for type checkers only def _run_raw(self, script: str) -> str: ... def get_os_users(self) -> list[UserDict]: """The host's local accounts; see the module. :raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``. :raises ValueError: when the reading came back empty. """ return parse_os_users(json_object(self._run_raw(_PS_OS_USERS), "local account"))