accounts – Users, Groups, SIDs &c.

All security in windows is handled via Security Principals. These can be a user (the most common case), a group of users, a computer, or something else. Security principals are uniquely identified by their SID: a binary code represented by a string S-a-b-cd-efg... where each of the segments represents an aspect of the security authorities involved. (A computer, a domain etc.). Certain of the SIDs are considered well-known such as the AuthenticatedUsers account on each machine which will always have the same SID.

Most of the access to this module will be via the principal() or me() functions. Although the module is designed to be used standalone, it is imported directly into the security module’s namespace so its functionality can also be accessed from there.

Functions

accounts.principal(principal, cls=<Unset>)[source]

Factory function for the Principal class. This is the most common way to create a Principal object:

from winsys import accounts
service_account = accounts.principal (accounts.WELL_KNOWN_SID.Service)
local_admin = accounts.principal ("Administrator")
domain_users = accounts.principal (r"DOMAIN\Domain Users")
Parameters:principal – any of None, a Principal, a PySID, a WELL_KNOWN_SID or a string
Returns:a Principal object corresponding to principal
accounts.user(name)[source]

If you know you’re after a user, use this. Particularly useful when a system user is defined as an alias type

accounts.group(name)[source]

If you know you’re after a group, use this. Particularly useful when a system group is defined as an alias type

accounts.me()[source]

Convenience function for the common case of getting the logged-on user’s account.

Classes

class accounts.Principal(sid, system=None)[source]

Object wrapping a Windows security principal, represented by a SID and, where possible, a name. Principal compares and hashes by SID so can be sorted and used as a dictionary key, set element, etc.

A Principal is its own context manager, impersonating the corresponding user:

from winsys import accounts
with accounts.principal("python"):
    print accounts.me()

Note, though, that this will prompt for a password using the Win32 password UI. To logon with a password, use the impersonate() context-managed function. TODO: allow password to be set securely.

Initialise a Principal from and (optionally) a system name. The sid must be a PySID and the system name, if present must be a security authority, eg a machine or a domain.

classmethod from_sid(sid, system=None)[source]

Return a Principal based on a sid and a security authority.

Parameters:
  • sid – a PySID
  • system_name – optional name of a security authority
Returns:

a Principal object for sid

classmethod from_string(string, system=None)[source]
Return a Principal based on a name and a

security authority. If string is blank, the logged-on user is assumed.

param string:name of an account in the form “domain
ame”. domain is optional so the simplest form is simply “name”
param system:name of a security authority (typically a machine or a domain)
returns:a Principal object for string
classmethod from_well_known(well_known, domain=None)[source]

Return a Principal based on one of the WELL_KNOWN_SID values.

Parameters:
impersonate(*args, **kwds)[source]

Context-managed function to impersonate this user and then revert:

from winsys import accounts, security
print accounts.me()
python = accounts.principal("python")
with python.impersonate("Pa55w0rd"):
    print accounts.me()
    open("temp.txt", "w").close()
print accounts.me()
security.security("temp.txt").owner == python

Note that the Principal class is also its own context manager but does not allow the password to be specified.

Parameters:
  • password – password for this account
  • logon_type – one of the LOGON values
logon(password=<Unset>, logon_type=<Unset>)[source]

Log on as an authenticated user, returning that user’s token. This is used by security.impersonate which wraps the token in a Token object and manages its lifetime in a context.

(EXPERIMENTAL) If no password is given, a UI pops up to ask for a password.

Parameters:
  • password – the password for this account
  • logon_type – one of the LOGON values
Returns:

a pywin32 handle to a token

classmethod me()[source]

Convenience factory method for the common case of referring to the logged-on user

pyobject()[source]

Return the internal representation of this object.

Returns:pywin32 SID
class accounts.User(sid, system=None)[source]

Initialise a Principal from and (optionally) a system name. The sid must be a PySID and the system name, if present must be a security authority, eg a machine or a domain.

classmethod create(username, password, system=None)[source]

Create a new user with username and password. Return a User for the new user.

Parameters:
  • username – username of the new user. Must not already exist on system
  • password – password for the new user. Must meet security policy on system
  • system – optional system name
Returns:

a User for username

delete()[source]

Delete this user from system.

Parameters:system – optional security authority
groups()[source]

Yield the groups this user belongs to

Parameters:system – optional security authority
join(other_group)[source]

Add this user to a group

Parameters:other_group – anything accepted by group()
Returns:self
leave(other_group)[source]

Remove this user from a group

Parameters:other_group – anything accepted by group()
Returns:self
runas(command_line, password=<Unset>, load_profile=False)[source]

Run a command logged on as this user

Parameters:
  • command_line – command line to run, quoted as necessary
  • password – password; if not supplied, standard Windows prompt
  • with_profile – if True, HKEY_CURRENT_USER is loaded [False]
class accounts.Group(sid, system=None)[source]

Initialise a Principal from and (optionally) a system name. The sid must be a PySID and the system name, if present must be a security authority, eg a machine or a domain.

Constants

accounts.LOGON = <Constants: {'LOGON_NEW_CREDENTIALS': 9, 'LOGON_NETWORK_CLEARTEXT': 8, 'LOGON_UNLOCK': 7, 'LOGON_BATCH': 4, 'PROVIDER_WINNT40': 2, 'LOGON_NETWORK': 3, 'PROVIDER_WINNT50': 3, 'LOGON_INTERACTIVE': 2, 'LOGON_SERVICE': 5, 'PROVIDER_DEFAULT': 0, 'PROVIDER_WINNT35': 1}>

Types of logon used by LogonUser and related APIs

Name Val Win32
PROVIDER_DEFAULT 0x000 LOGON32_PROVIDER_DEFAULT
PROVIDER_WINNT35 0x001 LOGON32_PROVIDER_WINNT35
PROVIDER_WINNT40 0x002 LOGON32_PROVIDER_WINNT40
LOGON_INTERACTIVE 0x002 LOGON32_PROVIDER_WINNT40
LOGON_NETWORK 0x003 LOGON32_PROVIDER_WINNT50
PROVIDER_WINNT50 0x003 LOGON32_PROVIDER_WINNT50
LOGON_BATCH 0x004 LOGON32_LOGON_BATCH
LOGON_SERVICE 0x005 LOGON32_LOGON_SERVICE
LOGON_UNLOCK 0x007 LOGON32_LOGON_UNLOCK
LOGON_NETWORK_CLEARTEXT 0x008 LOGON32_LOGON_NETWORK_CLEARTEXT
LOGON_NEW_CREDENTIALS 0x009 LOGON32_LOGON_NEW_CREDENTIALS
accounts.EXTENDED_NAME = <Constants: {'UniqueId': 6, 'CanonicalEx': 9, 'DnsDomain': 12, 'Unknown': 0, 'ServicePrincipal': 10, 'UserPrincipal': 8, 'SamCompatible': 2, 'FullyQualifiedDN': 1, 'Display': 3, 'Canonical': 7}>

Extended display formats for usernames

Name Val Win32
Unknown 0x000 NameUnknown
FullyQualifiedDN 0x001 NameFullyQualifiedDN
SamCompatible 0x002 NameSamCompatible
Display 0x003 NameDisplay
UniqueId 0x006 NameUniqueId
Canonical 0x007 NameCanonical
UserPrincipal 0x008 NameUserPrincipal
CanonicalEx 0x009 NameCanonicalEx
ServicePrincipal 0x00A NameServicePrincipal
DnsDomain 0x00C NameDnsDomain
accounts.WELL_KNOWN_SID = <Constants: {'AccountKrbtgt': 40, 'AccountDomainUsers': 42, 'BuiltinRemoteDesktopUsers': 36, 'Dialup': 8, 'Network': 9, 'BuiltinDCOMUsers': 61, 'AccountGuest': 39, 'Self': 16, 'BuiltinDomain': 25, 'CreatorGroup': 4, 'BuiltinPrintOperators': 32, 'CreatorOwner': 3, 'RemoteLogonId': 20, 'BuiltinAuthorizationAccess': 59, 'CreatorOwnerRights': 71, 'BuiltinBackupOperators': 33, 'EnterpriseControllers': 15, 'Local': 2, 'WriteRestrictedCode': 70, 'AccountEnterpriseAdmins': 48, 'DigestAuthentication': 52, 'BuiltinPowerUsers': 29, 'BuiltinUsers': 27, 'UntrustedLabel': 65, 'BuiltinIncomingForestTrustBuilders': 56, 'AccountSchemaAdmins': 47, 'Service': 12, 'BuiltinIUsers': 62, 'AccountDomainAdmins': 41, 'BuiltinAdministrators': 26, 'AccountRasAndIasServers': 50, 'Proxy': 14, 'Anonymous': 13, 'World': 1, 'BuiltinPerfLoggingUsers': 58, 'BuiltinCryptoOperators': 64, 'BuiltinPerfMonitoringUsers': 57, 'IUser': 63, 'BuiltinReplicator': 34, 'BuiltinTerminalServerLicenseServers': 60, 'LowLabel': 66, 'CreatorGroupServer': 6, 'OtherOrganization': 55, 'CreatorOwnerServer': 5, 'NetworkService': 24, 'SystemLabel': 69, 'NtAuthority': 7, 'BuiltinSystemOperators': 31, 'Batch': 10, 'MediumLabel': 67, 'LocalSystem': 22, 'NTLMAuthentication': 51, 'RestrictedCode': 18, 'LocalService': 23, 'AccountAdministrator': 38, 'TerminalServer': 19, 'LogonIds': 21, 'BuiltinAccountOperators': 30, 'Interactive': 11, 'BuiltinNetworkConfigurationOperators': 37, 'CacheablePrincipalsGroup': 72, 'EnterpriseReadonlyControllers': 74, 'AccountPolicyAdmins': 49, 'HighLabel': 68, 'BuiltinPreWindows2000CompatibleAccess': 35, 'AuthenticatedUser': 17, 'SChannelAuthentication': 53, 'ThisOrganization': 54, 'AccountDomainGuests': 43, 'BuiltinGuests': 28, 'AccountReadonlyControllers': 75, 'AccountControllers': 45, 'AccountCertAdmins': 46, 'Null': 0, 'AccountComputers': 44, 'NonCacheablePrincipalsGroup': 73}>

Well-known SIDs common to all computers

Name Val Win32
Null 0x000 WinNullSid
World 0x001 WinWorldSid
Local 0x002 WinLocalSid
CreatorOwner 0x003 WinCreatorOwnerSid
CreatorGroup 0x004 WinCreatorGroupSid
CreatorOwnerServer 0x005 WinCreatorOwnerServerSid
CreatorGroupServer 0x006 WinCreatorGroupServerSid
NtAuthority 0x007 WinNtAuthoritySid
Dialup 0x008 WinDialupSid
Network 0x009 WinNetworkSid
Batch 0x00A WinBatchSid
Interactive 0x00B WinInteractiveSid
Service 0x00C WinServiceSid
Anonymous 0x00D WinAnonymousSid
Proxy 0x00E WinProxySid
EnterpriseControllers 0x00F WinEnterpriseControllersSid
Self 0x010 WinSelfSid
AuthenticatedUser 0x011 WinAuthenticatedUserSid
RestrictedCode 0x012 WinRestrictedCodeSid
TerminalServer 0x013 WinTerminalServerSid
RemoteLogonId 0x014 WinRemoteLogonIdSid
LogonIds 0x015 WinLogonIdsSid
LocalSystem 0x016 WinLocalSystemSid
LocalService 0x017 WinLocalServiceSid
NetworkService 0x018 WinNetworkServiceSid
BuiltinDomain 0x019 WinBuiltinDomainSid
BuiltinAdministrators 0x01A WinBuiltinAdministratorsSid
BuiltinUsers 0x01B WinBuiltinUsersSid
BuiltinGuests 0x01C WinBuiltinGuestsSid
BuiltinPowerUsers 0x01D WinBuiltinPowerUsersSid
BuiltinAccountOperators 0x01E WinBuiltinAccountOperatorsSid
BuiltinSystemOperators 0x01F WinBuiltinSystemOperatorsSid
BuiltinPrintOperators 0x020 WinBuiltinPrintOperatorsSid
BuiltinBackupOperators 0x021 WinBuiltinBackupOperatorsSid
BuiltinReplicator 0x022 WinBuiltinReplicatorSid
BuiltinPreWindows2000CompatibleAccess 0x023 WinBuiltinPreWindows2000CompatibleAccessSid
BuiltinRemoteDesktopUsers 0x024 WinBuiltinRemoteDesktopUsersSid
BuiltinNetworkConfigurationOperators 0x025 WinBuiltinNetworkConfigurationOperatorsSid
AccountAdministrator 0x026 WinAccountAdministratorSid
AccountGuest 0x027 WinAccountGuestSid
AccountKrbtgt 0x028 WinAccountKrbtgtSid
AccountDomainAdmins 0x029 WinAccountDomainAdminsSid
AccountDomainUsers 0x02A WinAccountDomainUsersSid
AccountDomainGuests 0x02B WinAccountDomainGuestsSid
AccountComputers 0x02C WinAccountComputersSid
AccountControllers 0x02D WinAccountControllersSid
AccountCertAdmins 0x02E WinAccountCertAdminsSid
AccountSchemaAdmins 0x02F WinAccountSchemaAdminsSid
AccountEnterpriseAdmins 0x030 WinAccountEnterpriseAdminsSid
AccountPolicyAdmins 0x031 WinAccountPolicyAdminsSid
AccountRasAndIasServers 0x032 WinAccountRasAndIasServersSid
NTLMAuthentication 0x033 WinNTLMAuthenticationSid
DigestAuthentication 0x034 WinDigestAuthenticationSid
SChannelAuthentication 0x035 WinSChannelAuthenticationSid
ThisOrganization 0x036 WinThisOrganizationSid
OtherOrganization 0x037 WinOtherOrganizationSid
BuiltinIncomingForestTrustBuilders 0x038 WinBuiltinIncomingForestTrustBuildersSid
BuiltinPerfMonitoringUsers 0x039 WinBuiltinPerfMonitoringUsersSid
BuiltinPerfLoggingUsers 0x03A WinBuiltinPerfLoggingUsersSid
BuiltinAuthorizationAccess 0x03B WinBuiltinAuthorizationAccessSid
BuiltinTerminalServerLicenseServers 0x03C WinBuiltinTerminalServerLicenseServersSid
BuiltinDCOMUsers 0x03D WinBuiltinDCOMUsersSid
BuiltinIUsers 0x03E WinBuiltinIUsersSid
IUser 0x03F WinIUserSid
BuiltinCryptoOperators 0x040 WinBuiltinCryptoOperatorsSid
UntrustedLabel 0x041 WinUntrustedLabelSid
LowLabel 0x042 WinLowLabelSid
MediumLabel 0x043 WinMediumLabelSid
HighLabel 0x044 WinHighLabelSid
SystemLabel 0x045 WinSystemLabelSid
WriteRestrictedCode 0x046 WinWriteRestrictedCodeSid
CreatorOwnerRights 0x047 WinCreatorOwnerRightsSid
CacheablePrincipalsGroup 0x048 WinCacheablePrincipalsGroupSid
NonCacheablePrincipalsGroup 0x049 WinNonCacheablePrincipalsGroupSid
EnterpriseReadonlyControllers 0x04A WinEnterpriseReadonlyControllersSid
AccountReadonlyControllers 0x04B WinAccountReadonlyControllersSid
accounts.USER_PRIV = <Constants: {u'ADMIN': 2, u'GUEST': 0, u'USER': 1}>

User-types for creating new users

Name Val Win32
GUEST 0x000 USER_PRIV_GUEST
USER 0x001 USER_PRIV_USER
ADMIN 0x002 USER_PRIV_ADMIN
accounts.UF = <Constants: {'ACCOUNT_TYPE_MASK': 15104, 'WORKSTATION_TRUST_ACCOUNT': 4096, 'INTERDOMAIN_TRUST_ACCOUNT': 2048, 'SCRIPT': 1, 'DONT_EXPIRE_PASSWD': 65536, 'MNS_LOGON_ACCOUNT': 131072, 'PASSWD_CANT_CHANGE': 64, 'HOMEDIR_REQUIRED': 8, 'SERVER_TRUST_ACCOUNT': 8192, 'PASSWD_NOTREQD': 32, 'LOCKOUT': 16, 'ACCOUNTDISABLE': 2, 'NORMAL_ACCOUNT': 512, 'SETTABLE_BITS': 211835, 'TEMP_DUPLICATE_ACCOUNT': 256, 'MACHINE_ACCOUNT_MASK': 14336}>

Flags for creating new users

Name Val Win32
SCRIPT 0x000001 UF_SCRIPT
ACCOUNTDISABLE 0x000002 UF_ACCOUNTDISABLE
HOMEDIR_REQUIRED 0x000008 UF_HOMEDIR_REQUIRED
LOCKOUT 0x000010 UF_LOCKOUT
PASSWD_NOTREQD 0x000020 UF_PASSWD_NOTREQD
PASSWD_CANT_CHANGE 0x000040 UF_PASSWD_CANT_CHANGE
TEMP_DUPLICATE_ACCOUNT 0x000100 UF_TEMP_DUPLICATE_ACCOUNT
NORMAL_ACCOUNT 0x000200 UF_NORMAL_ACCOUNT
INTERDOMAIN_TRUST_ACCOUNT 0x000800 UF_INTERDOMAIN_TRUST_ACCOUNT
WORKSTATION_TRUST_ACCOUNT 0x001000 UF_WORKSTATION_TRUST_ACCOUNT
SERVER_TRUST_ACCOUNT 0x002000 UF_SERVER_TRUST_ACCOUNT
MACHINE_ACCOUNT_MASK 0x003800 UF_MACHINE_ACCOUNT_MASK
ACCOUNT_TYPE_MASK 0x003B00 UF_ACCOUNT_TYPE_MASK
DONT_EXPIRE_PASSWD 0x010000 UF_DONT_EXPIRE_PASSWD
MNS_LOGON_ACCOUNT 0x020000 UF_MNS_LOGON_ACCOUNT
SETTABLE_BITS 0x033B7B UF_SETTABLE_BITS
accounts.SID_NAME_USE = <Constants: {'Domain': 3, 'Group': 2, 'Unknown': 8, 'Invalid': 7, 'Label': 10, 'Alias': 4, 'DeletedAccount': 6, 'Computer': 9, 'User': 1, 'WellKnownGroup': 5}>

Types of accounts for which SIDs exist

Name Val Win32
User 0x001 SidTypeUser
Group 0x002 SidTypeGroup
Domain 0x003 SidTypeDomain
Alias 0x004 SidTypeAlias
WellKnownGroup 0x005 SidTypeWellKnownGroup
DeletedAccount 0x006 SidTypeDeletedAccount
Invalid 0x007 SidTypeInvalid
Unknown 0x008 SidTypeUnknown
Computer 0x009 SidTypeComputer
Label 0x00A SidTypeLabel
accounts.FILTER = <Constants: {'WORKSTATION_TRUST_ACCOUNT': 16, 'INTERDOMAIN_TRUST_ACCOUNT': 8, 'TEMP_DUPLICATE_ACCOUNT': 1, 'SERVER_TRUST_ACCOUNT': 32, 'NORMAL_ACCOUNT': 2}>

Filters when enumerating users

Name Val Win32
TEMP_DUPLICATE_ACCOUNT 0x001 FILTER_TEMP_DUPLICATE_ACCOUNT
NORMAL_ACCOUNT 0x002 FILTER_NORMAL_ACCOUNT
INTERDOMAIN_TRUST_ACCOUNT 0x008 FILTER_INTERDOMAIN_TRUST_ACCOUNT
WORKSTATION_TRUST_ACCOUNT 0x010 FILTER_WORKSTATION_TRUST_ACCOUNT
SERVER_TRUST_ACCOUNT 0x020 FILTER_SERVER_TRUST_ACCOUNT

Exceptions

exception accounts.x_accounts(errno=None, errctx=None, errmsg=None)[source]

Base for all accounts-related exceptions

References

See also

Using the accounts module
Cookbook examples of using the accounts module

To Do

  • LSA & Credentials functionality

Table Of Contents

Previous topic

exc – Exceptions

Next topic

dialogs – Dialog boxes

This Page