Initial commit

This commit is contained in:
Alex committed 2026-11-02 22:54:14 +08:00
commit 57fc3525eb
7311 files changed
+1291398

No files matched your search

@@ -0,0 +1,119 @@
## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams
import ntsecuritycon
import pythoncom
import pywintypes
import win32api
import win32con
import win32file
import win32security
from win32com import storagecon
all_sd_info = (
win32security.DACL_SECURITY_INFORMATION
| win32security.DACL_SECURITY_INFORMATION
| win32security.OWNER_SECURITY_INFORMATION
| win32security.GROUP_SECURITY_INFORMATION
)
tempdir = win32api.GetTempPath()
tempfile = win32api.GetTempFileName(tempdir, "bkr")[0]
outfile = win32api.GetTempFileName(tempdir, "out")[0]
print("Filename:", tempfile, "Output file:", outfile)
f = open(tempfile, "w")
f.write("some random junk" + "x" * 100)
f.close()
## add a couple of alternate data streams
f = open(tempfile + ":streamdata", "w")
f.write("data written to alternate stream" + "y" * 100)
f.close()
f = open(tempfile + ":anotherstream", "w")
f.write("z" * 100)
f.close()
## add Summary Information, which is stored as a separate stream
m = storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE | storagecon.STGM_DIRECT
pss = pythoncom.StgOpenStorageEx(
tempfile, m, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage, None
)
ps = pss.Create(
pythoncom.FMTID_SummaryInformation,
pythoncom.IID_IPropertyStorage,
0,
storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE,
)
ps.WriteMultiple(
(storagecon.PIDSI_KEYWORDS, storagecon.PIDSI_COMMENTS), ("keywords", "comments")
)
ps = None
pss = None
## add a custom security descriptor to make sure we don't
## get a default that would always be the same for both files in temp dir
new_sd = pywintypes.SECURITY_DESCRIPTOR()
sid = win32security.LookupAccountName("", "EveryOne")[0]
acl = pywintypes.ACL()
acl.AddAccessAllowedAce(1, win32con.GENERIC_READ, sid)
acl.AddAccessAllowedAce(1, ntsecuritycon.FILE_APPEND_DATA, sid)
acl.AddAccessAllowedAce(1, win32con.GENERIC_WRITE, sid)
acl.AddAccessAllowedAce(1, ntsecuritycon.FILE_ALL_ACCESS, sid)
new_sd.SetSecurityDescriptorDacl(True, acl, False)
win32security.SetFileSecurity(tempfile, win32security.DACL_SECURITY_INFORMATION, new_sd)
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle = True
h = win32file.CreateFile(
tempfile,
win32con.GENERIC_ALL,
win32con.FILE_SHARE_READ,
sa,
win32con.OPEN_EXISTING,
win32file.FILE_FLAG_BACKUP_SEMANTICS,
None,
)
outh = win32file.CreateFile(
outfile,
win32con.GENERIC_ALL,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
sa,
win32con.OPEN_EXISTING,
win32file.FILE_FLAG_BACKUP_SEMANTICS,
None,
)
ctxt = 0
outctxt = 0
buf = None
readsize = 100
while 1:
bytes_read, buf, ctxt = win32file.BackupRead(h, readsize, buf, False, True, ctxt)
if bytes_read == 0:
break
bytes_written, outctxt = win32file.BackupWrite(
outh, bytes_read, buf, False, True, outctxt
)
print("Written:", bytes_written, "Context:", outctxt)
win32file.BackupRead(h, 0, buf, True, True, ctxt)
win32file.BackupWrite(outh, 0, b"", True, True, outctxt)
win32file.CloseHandle(h)
win32file.CloseHandle(outh)
assert open(tempfile).read() == open(outfile).read(), "File contents differ !"
assert open(tempfile + ":streamdata").read() == open(outfile + ":streamdata").read(), (
"streamdata contents differ !"
)
assert (
open(tempfile + ":anotherstream").read() == open(outfile + ":anotherstream").read()
), "anotherstream contents differ !"
assert (
memoryview(win32security.GetFileSecurity(tempfile, all_sd_info))[:]
== memoryview(win32security.GetFileSecurity(outfile, all_sd_info))[:]
), "Security descriptors are different !"
## also should check Summary Info programatically
@@ -0,0 +1,137 @@
## demonstrates using BackupSeek to enumerate data streams for a file
import struct
import pythoncom
import pywintypes
import win32api
import win32con
import win32file
from win32com import storagecon
stream_types = {
win32con.BACKUP_DATA: "Standard data",
win32con.BACKUP_EA_DATA: "Extended attribute data",
win32con.BACKUP_SECURITY_DATA: "Security descriptor data",
win32con.BACKUP_ALTERNATE_DATA: "Alternative data streams",
win32con.BACKUP_LINK: "Hard link information",
win32con.BACKUP_PROPERTY_DATA: "Property data",
win32con.BACKUP_OBJECT_ID: "Objects identifiers",
win32con.BACKUP_REPARSE_DATA: "Reparse points",
win32con.BACKUP_SPARSE_BLOCK: "Sparse file",
}
tempdir = win32api.GetTempPath()
tempfile = win32api.GetTempFileName(tempdir, "bkr")[0]
print("Filename:", tempfile)
f = open(tempfile, "w")
f.write("some random junk" + "x" * 100)
f.close()
f = open(tempfile + ":streamdata", "w")
f.write("data written to alternate stream" + "y" * 100)
f.close()
f = open(tempfile + ":anotherstream", "w")
f.write("z" * 200)
f.close()
## add Summary Information, which is stored as a separate stream
m = storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE | storagecon.STGM_DIRECT
pss = pythoncom.StgOpenStorageEx(
tempfile, m, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage, None
)
ps = pss.Create(
pythoncom.FMTID_SummaryInformation,
pythoncom.IID_IPropertyStorage,
0,
storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE,
)
ps.WriteMultiple(
(storagecon.PIDSI_KEYWORDS, storagecon.PIDSI_COMMENTS), ("keywords", "comments")
)
ps = None
pss = None
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle = False
h = win32file.CreateFile(
tempfile,
win32con.GENERIC_ALL,
win32con.FILE_SHARE_READ,
sa,
win32con.OPEN_EXISTING,
win32file.FILE_FLAG_BACKUP_SEMANTICS,
None,
)
""" stream header:
typedef struct _WIN32_STREAM_ID {
DWORD dwStreamId; DWORD dwStreamAttributes; LARGE_INTEGER Size;
DWORD dwStreamNameSize; WCHAR cStreamName[ANYSIZE_ARRAY];
}
"""
win32_stream_id_format = "LLQL"
win32_stream_id_size = struct.calcsize(win32_stream_id_format)
def parse_stream_header(h, ctxt, data):
stream_type, stream_attributes, stream_size, stream_name_size = struct.unpack(
win32_stream_id_format, data
)
print(
"\nType:",
stream_type,
stream_types[stream_type],
"Attributes:",
stream_attributes,
"Size:",
stream_size,
"Name len:",
stream_name_size,
)
if stream_name_size > 0:
## ??? sdk says this size is in characters, but it appears to be number of bytes ???
bytes_read, stream_name_buf, ctxt = win32file.BackupRead(
h, stream_name_size, None, False, True, ctxt
)
stream_name = pywintypes.UnicodeFromRaw(stream_name_buf[:])
else:
stream_name = "Unnamed"
print("Name:" + stream_name)
return (
ctxt,
stream_type,
stream_attributes,
stream_size,
stream_name_size,
stream_name,
)
ctxt = 0
win32_stream_id_buf = (
None ## gets rebound to a writable buffer on first call and reused
)
while 1:
bytes_read, win32_stream_id_buf, ctxt = win32file.BackupRead(
h, win32_stream_id_size, win32_stream_id_buf, False, True, ctxt
)
if bytes_read == 0:
break
(
ctxt,
stream_type,
stream_attributes,
stream_size,
stream_name_size,
stream_name,
) = parse_stream_header(h, ctxt, win32_stream_id_buf[:])
if stream_size > 0:
bytes_moved = win32file.BackupSeek(h, stream_size, ctxt)
print("Moved: ", bytes_moved)
win32file.BackupRead(h, win32_stream_id_size, win32_stream_id_buf, True, True, ctxt)
win32file.CloseHandle(h)
@@ -0,0 +1,57 @@
import win32api
import win32file
def ProgressRoutine(
TotalFileSize,
TotalBytesTransferred,
StreamSize,
StreamBytesTransferred,
StreamNumber,
CallbackReason,
SourceFile,
DestinationFile,
Data,
):
print(Data)
print(
TotalFileSize,
TotalBytesTransferred,
StreamSize,
StreamBytesTransferred,
StreamNumber,
CallbackReason,
SourceFile,
DestinationFile,
)
##if TotalBytesTransferred > 100000:
## return win32file.PROGRESS_STOP
return win32file.PROGRESS_CONTINUE
temp_dir = win32api.GetTempPath()
fsrc = win32api.GetTempFileName(temp_dir, "cfe")[0]
fdst = win32api.GetTempFileName(temp_dir, "cfe")[0]
print(fsrc, fdst)
f = open(fsrc, "w")
f.write("xxxxxxxxxxxxxxxx\n" * 32768)
f.close()
## add a couple of extra data streams
f = open(fsrc + ":stream_y", "w")
f.write("yyyyyyyyyyyyyyyy\n" * 32768)
f.close()
f = open(fsrc + ":stream_z", "w")
f.write("zzzzzzzzzzzzzzzz\n" * 32768)
f.close()
operation_desc = "Copying " + fsrc + " to " + fdst
win32file.CopyFileEx(
fsrc,
fdst,
ProgressRoutine,
Data=operation_desc,
Cancel=False,
CopyFlags=win32file.COPY_FILE_RESTARTABLE,
Transaction=None,
)
@@ -0,0 +1,122 @@
"""
This demonstrates the creation of miniversions of a file during a transaction.
The FSCTL_TXFS_CREATE_MINIVERSION control code saves any changes to a new
miniversion (effectively a savepoint within a transaction).
"""
import os
import struct
import win32api
import win32con
import win32file
import win32transaction
import winerror
import winioctlcon
def demo():
"""
Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION:
typedef struct _TXFS_CREATE_MINIVERSION_INFO{
USHORT StructureVersion;
USHORT StructureLength;
ULONG BaseVersion;
USHORT MiniVersion;}
"""
buf_fmt = "HHLH0L" ## buffer size must include struct padding
buf_size = struct.calcsize(buf_fmt)
tempdir = win32api.GetTempPath()
tempfile = win32api.GetTempFileName(tempdir, "cft")[0]
print("Demonstrating transactions on tempfile", tempfile)
f = open(tempfile, "w")
f.write("This is original file.\n")
f.close()
trans = win32transaction.CreateTransaction(
Description="Test creating miniversions of a file"
)
hfile = win32file.CreateFileW(
tempfile,
win32con.GENERIC_READ | win32con.GENERIC_WRITE,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
0,
None,
Transaction=trans,
)
win32file.WriteFile(hfile, b"This is first miniversion.\n")
buf = win32file.DeviceIoControl(
hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None
)
struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf)
win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN)
win32file.WriteFile(hfile, b"This is second miniversion!\n")
buf = win32file.DeviceIoControl(
hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None
)
struct_ver, struct_len, base_ver, ver_2 = struct.unpack(buf_fmt, buf)
hfile.Close()
## miniversions can't be opened with write access
hfile_0 = win32file.CreateFileW(
tempfile,
win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
0,
None,
Transaction=trans,
MiniVersion=base_ver,
)
print("version:", base_ver, win32file.ReadFile(hfile_0, 100))
hfile_0.Close()
hfile_1 = win32file.CreateFileW(
tempfile,
win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
0,
None,
Transaction=trans,
MiniVersion=ver_1,
)
print("version:", ver_1, win32file.ReadFile(hfile_1, 100))
hfile_1.Close()
hfile_2 = win32file.CreateFileW(
tempfile,
win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
0,
None,
Transaction=trans,
MiniVersion=ver_2,
)
print("version:", ver_2, win32file.ReadFile(hfile_2, 100))
hfile_2.Close()
## MiniVersions are destroyed when transaction is committed or rolled back
win32transaction.CommitTransaction(trans)
os.unlink(tempfile)
if __name__ == "__main__":
# When run on CI, this fails with NOT_SUPPORTED, so don't have that cause "failure"
try:
demo()
except win32file.error as e:
if e.winerror == winerror.ERROR_NOT_SUPPORTED:
print("These features are not supported by this filesystem.")
else:
raise
@@ -0,0 +1,83 @@
import sys
import win32evtlog
def main():
path = "System"
num_events = 5
if len(sys.argv) > 2:
path = sys.argv[1]
num_events = int(sys.argv[2])
elif len(sys.argv) > 1:
path = sys.argv[1]
query = win32evtlog.EvtQuery(path, win32evtlog.EvtQueryForwardDirection)
events = win32evtlog.EvtNext(query, num_events)
context = win32evtlog.EvtCreateRenderContext(win32evtlog.EvtRenderContextSystem)
for i, event in enumerate(events, 1):
result = win32evtlog.EvtRender(
event, win32evtlog.EvtRenderEventValues, Context=context
)
print(f"Event {i}")
level_value, level_variant = result[win32evtlog.EvtSystemLevel]
if level_variant != win32evtlog.EvtVarTypeNull:
if level_value == 1:
print(" Level: CRITICAL")
elif level_value == 2:
print(" Level: ERROR")
elif level_value == 3:
print(" Level: WARNING")
elif level_value == 4:
print(" Level: INFO")
elif level_value == 5:
print(" Level: VERBOSE")
else:
print(" Level: UNKNOWN")
time_created_value, time_created_variant = result[
win32evtlog.EvtSystemTimeCreated
]
if time_created_variant != win32evtlog.EvtVarTypeNull:
print(f" Timestamp: {time_created_value.isoformat()}")
computer_value, computer_variant = result[win32evtlog.EvtSystemComputer]
if computer_variant != win32evtlog.EvtVarTypeNull:
print(f" FQDN: {computer_value}")
provider_name_value, provider_name_variant = result[
win32evtlog.EvtSystemProviderName
]
if provider_name_variant != win32evtlog.EvtVarTypeNull:
print(f" Provider: {provider_name_value}")
try:
metadata = win32evtlog.EvtOpenPublisherMetadata(provider_name_value)
# pywintypes.error: (2, 'EvtOpenPublisherMetadata', 'The system cannot find the file specified.')
except Exception:
pass
else:
try:
message = win32evtlog.EvtFormatMessage(
metadata, event, win32evtlog.EvtFormatMessageEvent
)
# pywintypes.error: (15027, 'EvtFormatMessage: allocated 0, need buffer of size 0', 'The message resource is present but the message was not found in the message table.')
except Exception:
pass
else:
try:
print(f" Message: {message}")
except UnicodeEncodeError:
# Obscure error when run under subprocess.Popen(), presumably due to
# not knowing the correct encoding for the console.
# > UnicodeEncodeError: \'charmap\' codec can\'t encode character \'\\u200e\' in position 57: character maps to <undefined>\r\n'
# Can't reproduce when running manually, so it seems more a subprocess.Popen()
# than ours:
print(f" Failed to decode: {message!r}")
if __name__ == "__main__":
main()
@@ -0,0 +1,28 @@
## Demonstrates how to create a "pull" subscription
import win32con
import win32event
import win32evtlog
query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]'
h = win32event.CreateEvent(None, 0, 0, None)
s = win32evtlog.EvtSubscribe(
"System",
win32evtlog.EvtSubscribeStartAtOldestRecord,
SignalEvent=h,
Query=query_text,
)
while 1:
while 1:
events = win32evtlog.EvtNext(s, 10)
if len(events) == 0:
break
##for event in events:
## print(win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml))
print("retrieved %s events" % len(events))
while 1:
print("waiting...")
w = win32event.WaitForSingleObjectEx(h, 2000, True)
if w == win32con.WAIT_OBJECT_0:
break
@@ -0,0 +1,32 @@
## Demonstrates a "push" subscription with a callback function
from __future__ import annotations
from time import sleep
import win32evtlog
query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]'
def c(reason, context, evt):
if reason == win32evtlog.EvtSubscribeActionError:
print("EvtSubscribeActionError")
elif reason == win32evtlog.EvtSubscribeActionDeliver:
print("EvtSubscribeActionDeliver")
else:
print("??? Unknown action ???", reason)
context.append(win32evtlog.EvtRender(evt, win32evtlog.EvtRenderEventXml))
return 0
evttext: list[str] = []
s = win32evtlog.EvtSubscribe(
"System",
win32evtlog.EvtSubscribeStartAtOldestRecord,
Query="*",
Callback=c,
Context=evttext,
)
sleep(0.001)
print("\n".join(evttext))
@@ -0,0 +1,137 @@
# Contributed by Kelly Kranabetter.
import os
import sys
import ntsecuritycon
import pywintypes
import win32security
import winerror
# get security information
# name=r"c:\autoexec.bat"
# name= r"g:\!workgrp\lim"
name = sys.argv[0]
if not os.path.exists(name):
print(name, "does not exist!")
sys.exit()
print("On file ", name, "\n")
# get owner SID
print("OWNER")
try:
sd = win32security.GetFileSecurity(name, win32security.OWNER_SECURITY_INFORMATION)
sid = sd.GetSecurityDescriptorOwner()
print(" ", win32security.LookupAccountSid(None, sid))
except pywintypes.error as exc:
# in automation and network shares we see:
# pywintypes.error: (1332, 'LookupAccountName', 'No mapping between account names and security IDs was done.')
if exc.winerror != winerror.ERROR_NONE_MAPPED:
raise
print("No owner information is available")
# get group SID
try:
print("GROUP")
sd = win32security.GetFileSecurity(name, win32security.GROUP_SECURITY_INFORMATION)
sid = sd.GetSecurityDescriptorGroup()
print(" ", win32security.LookupAccountSid(None, sid))
except pywintypes.error as exc:
if exc.winerror != winerror.ERROR_NONE_MAPPED:
raise
print("No group information is available")
# get ACEs
sd = win32security.GetFileSecurity(name, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()
if dacl is None:
print("No Discretionary ACL")
else:
for ace_no in range(0, dacl.GetAceCount()):
ace = dacl.GetAce(ace_no)
print("ACE", ace_no)
print(" -Type")
for i in (
"ACCESS_ALLOWED_ACE_TYPE",
"ACCESS_DENIED_ACE_TYPE",
"SYSTEM_AUDIT_ACE_TYPE",
"SYSTEM_ALARM_ACE_TYPE",
):
if getattr(ntsecuritycon, i) == ace[0][0]:
print(" ", i)
print(" -Flags", hex(ace[0][1]))
for i in (
"OBJECT_INHERIT_ACE",
"CONTAINER_INHERIT_ACE",
"NO_PROPAGATE_INHERIT_ACE",
"INHERIT_ONLY_ACE",
"SUCCESSFUL_ACCESS_ACE_FLAG",
"FAILED_ACCESS_ACE_FLAG",
):
if getattr(ntsecuritycon, i) & ace[0][1] == getattr(ntsecuritycon, i):
print(" ", i)
print(" -mask", hex(ace[1]))
# files and directories do permissions differently
permissions_file = (
"DELETE",
"READ_CONTROL",
"WRITE_DAC",
"WRITE_OWNER",
"SYNCHRONIZE",
"FILE_GENERIC_READ",
"FILE_GENERIC_WRITE",
"FILE_GENERIC_EXECUTE",
"FILE_DELETE_CHILD",
)
permissions_dir = (
"DELETE",
"READ_CONTROL",
"WRITE_DAC",
"WRITE_OWNER",
"SYNCHRONIZE",
"FILE_ADD_SUBDIRECTORY",
"FILE_ADD_FILE",
"FILE_DELETE_CHILD",
"FILE_LIST_DIRECTORY",
"FILE_TRAVERSE",
"FILE_READ_ATTRIBUTES",
"FILE_WRITE_ATTRIBUTES",
"FILE_READ_EA",
"FILE_WRITE_EA",
)
permissions_dir_inherit = (
"DELETE",
"READ_CONTROL",
"WRITE_DAC",
"WRITE_OWNER",
"SYNCHRONIZE",
"GENERIC_READ",
"GENERIC_WRITE",
"GENERIC_EXECUTE",
"GENERIC_ALL",
)
if os.path.isfile(name):
permissions = permissions_file
else:
permissions = permissions_dir
# directories also contain an ACE that is inherited by children (files) within them
if (
ace[0][1] & ntsecuritycon.OBJECT_INHERIT_ACE
== ntsecuritycon.OBJECT_INHERIT_ACE
and ace[0][1] & ntsecuritycon.INHERIT_ONLY_ACE
== ntsecuritycon.INHERIT_ONLY_ACE
):
permissions = permissions_dir_inherit
calc_mask = 0 # calculate the mask so we can see if we are printing all of the permissions
for i in permissions:
if getattr(ntsecuritycon, i) & ace[1] == getattr(ntsecuritycon, i):
calc_mask |= getattr(ntsecuritycon, i)
print(" ", i)
print(" ", "Calculated Check Mask=", hex(calc_mask))
print(" -SID\n ", win32security.LookupAccountSid(None, ace[2]))
@@ -0,0 +1,43 @@
import os
import win32con
import win32gui
filter = "Python Scripts\0*.py;*.pyw;*.pys\0Text files\0*.txt\0"
customfilter = "Other file types\0*.*\0"
fname, customfilter, flags = win32gui.GetSaveFileNameW(
InitialDir=os.environ["temp"],
Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER,
File="somefilename",
DefExt="py",
Title="GetSaveFileNameW",
Filter=filter,
CustomFilter=customfilter,
FilterIndex=1,
)
print(f"save file names: {fname!r}")
print(f"filter used: {customfilter!r}")
print(f"Flags: {flags}")
for k, v in win32con.__dict__.items():
if k.startswith("OFN_") and flags & v:
print("\t" + k)
fname, customfilter, flags = win32gui.GetOpenFileNameW(
InitialDir=os.environ["temp"],
Flags=win32con.OFN_ALLOWMULTISELECT | win32con.OFN_EXPLORER,
File="somefilename",
DefExt="py",
Title="GetOpenFileNameW",
Filter=filter,
CustomFilter=customfilter,
FilterIndex=0,
)
print(f"open file names: {fname!r}")
print(f"filter used: {customfilter!r}")
print(f"Flags: {flags}")
for k, v in win32con.__dict__.items():
if k.startswith("OFN_") and flags & v:
print("\t" + k)
@@ -0,0 +1,124 @@
"""A demo of using win32net.NetValidatePasswordPolicy.
Example usage:
% NetValidatePasswordPolicy.py --password=foo change
which might return:
> Result of 'change' validation is 0: The operation completed successfully.
or depending on the policy:
> Result of 'change' validation is 2245: The password does not meet the
> password policy requirements. Check the minimum password length,
> password complexity and password history requirements.
Adding --user doesn't seem to change the output (even the PasswordLastSet seen
when '-f' is used doesn't depend on the username), but theoretically it will
also check the password history for the specified user.
% NetValidatePasswordPolicy.py auth
which always (with and without '-m') seems to return:
> Result of 'auth' validation is 2701: Password must change at next logon
"""
import optparse
import sys
from pprint import pprint
import win32api
import win32net
import win32netcon
def main():
parser = optparse.OptionParser(
"%prog [options] auth|change ...",
description="A win32net.NetValidatePasswordPolicy demo.",
)
parser.add_option(
"-u",
"--username",
action="store",
help="The username to pass to the function (only for the 'change' command)",
)
parser.add_option(
"-p",
"--password",
action="store",
help="The clear-text password to pass to the function "
"(only for the 'change' command)",
)
parser.add_option(
"-m",
"--password-matched",
action="store_false",
default=True,
help="Used to specify the password does NOT match (ie, "
"uses False for the PasswordMatch/PasswordMatched "
"arg, both 'auth' and 'change' commands)",
)
parser.add_option(
"-s",
"--server",
action="store",
help="The name of the server to execute the command on",
)
parser.add_option(
"-f",
"--show_fields",
action="store_true",
default=False,
help="Print the NET_VALIDATE_PERSISTED_FIELDS returned",
)
options, args = parser.parse_args()
if not args:
args = ["auth"]
for arg in args:
if arg == "auth":
input = {
"PasswordMatched": options.password_matched,
}
val_type = win32netcon.NetValidateAuthentication
elif arg == "change":
input = {
"ClearPassword": options.password,
"PasswordMatch": options.password_matched,
"UserAccountName": options.username,
}
val_type = win32netcon.NetValidatePasswordChange
else:
parser.error("Invalid arg - must be 'auth' or 'change'")
try:
fields, status = win32net.NetValidatePasswordPolicy(
options.server, None, val_type, input
)
except win32net.error as exc:
print("NetValidatePasswordPolicy failed: ", exc)
return 1
if options.show_fields:
print("NET_VALIDATE_PERSISTED_FIELDS fields:")
pprint(fields)
print(
f"Result of {arg!r} validation is {status}:",
win32api.FormatMessage(status).strip(),
)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,66 @@
import os
import win32api
import win32file
import winerror
def ReadCallback(input_buffer, data, buflen):
fnamein, fnameout, f = data
# print(fnamein, fnameout, buflen)
f.write(input_buffer)
return winerror.ERROR_SUCCESS
def WriteCallback(output_buffer, data, buflen):
fnamebackup, fnameout, f = data
file_data = f.read(buflen)
## returning 0 as len terminates WriteEncryptedFileRaw
output_len = len(file_data)
output_buffer[:output_len] = file_data
return winerror.ERROR_SUCCESS, output_len
tmp_dir = win32api.GetTempPath()
dst_dir = win32api.GetTempFileName(tmp_dir, "oef")[0]
os.remove(dst_dir)
os.mkdir(dst_dir)
print("Destination dir:", dst_dir)
## create an encrypted file
fname = win32api.GetTempFileName(dst_dir, "ref")[0]
print("orig file:", fname)
f = open(fname, "w")
f.write("xxxxxxxxxxxxxxxx\n" * 32768)
f.close()
## add a couple of extra data streams
f = open(fname + ":stream_y", "w")
f.write("yyyyyyyyyyyyyyyy\n" * 32768)
f.close()
f = open(fname + ":stream_z", "w")
f.write("zzzzzzzzzzzzzzzz\n" * 32768)
f.close()
win32file.EncryptFile(fname)
## backup raw data of encrypted file
bkup_fname = win32api.GetTempFileName(dst_dir, "bef")[0]
print("backup file:", bkup_fname)
f = open(bkup_fname, "wb")
ctxt = win32file.OpenEncryptedFileRaw(fname, 0)
try:
win32file.ReadEncryptedFileRaw(ReadCallback, (fname, bkup_fname, f), ctxt)
finally:
## if context is not closed, file remains locked even if calling process is killed
win32file.CloseEncryptedFileRaw(ctxt)
f.close()
## restore data from backup to new encrypted file
dst_fname = win32api.GetTempFileName(dst_dir, "wef")[0]
print("restored file:", dst_fname)
f = open(bkup_fname, "rb")
ctxtout = win32file.OpenEncryptedFileRaw(dst_fname, win32file.CREATE_FOR_IMPORT)
try:
win32file.WriteEncryptedFileRaw(WriteCallback, (bkup_fname, dst_fname, f), ctxtout)
finally:
win32file.CloseEncryptedFileRaw(ctxtout)
f.close()
@@ -0,0 +1,60 @@
import win32api
import win32con
import win32transaction
keyname = "Pywin32 test transacted registry functions"
subkeyname = "test transacted subkey"
classname = "Transacted Class"
trans = win32transaction.CreateTransaction(Description="test RegCreateKeyTransacted")
key, disp = win32api.RegCreateKeyEx(
win32con.HKEY_CURRENT_USER,
keyname,
samDesired=win32con.KEY_ALL_ACCESS,
Class=classname,
)
## clean up any existing keys
for subk in win32api.RegEnumKeyExW(key):
win32api.RegDeleteKey(key, subk[0])
## reopen key in transacted mode
transacted_key = win32api.RegOpenKeyTransacted(
Key=win32con.HKEY_CURRENT_USER,
SubKey=keyname,
Transaction=trans,
samDesired=win32con.KEY_ALL_ACCESS,
)
subkey, disp = win32api.RegCreateKeyEx(
transacted_key,
subkeyname,
Transaction=trans,
samDesired=win32con.KEY_ALL_ACCESS,
Class=classname,
)
## Newly created key should not be visible from non-transacted handle
subkeys = [s[0] for s in win32api.RegEnumKeyExW(key)]
assert subkeyname not in subkeys
transacted_subkeys = [s[0] for s in win32api.RegEnumKeyExW(transacted_key)]
assert subkeyname in transacted_subkeys
## Key should be visible to non-transacted handle after commit
win32transaction.CommitTransaction(trans)
subkeys = [s[0] for s in win32api.RegEnumKeyExW(key)]
assert subkeyname in subkeys
## test transacted delete
del_trans = win32transaction.CreateTransaction(
Description="test RegDeleteKeyTransacted"
)
win32api.RegDeleteKeyEx(key, subkeyname, Transaction=del_trans)
## subkey should still show up for non-transacted handle
subkeys = [s[0] for s in win32api.RegEnumKeyExW(key)]
assert subkeyname in subkeys
## ... and should be gone after commit
win32transaction.CommitTransaction(del_trans)
subkeys = [s[0] for s in win32api.RegEnumKeyExW(key)]
assert subkeyname not in subkeys
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, keyname)
@@ -0,0 +1,71 @@
import os
import ntsecuritycon
import win32api
import win32con
import win32security
import winnt
temp_dir = win32api.GetTempPath()
fname = win32api.GetTempFileName(temp_dir, "rsk")[0]
print(fname)
## file can't exist
os.remove(fname)
## enable backup and restore privs
required_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_BACKUP_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_RESTORE_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32con.TOKEN_READ | win32con.TOKEN_ADJUST_PRIVILEGES
)
adjusted_privs = win32security.AdjustTokenPrivileges(th, 0, required_privs)
try:
sa = win32security.SECURITY_ATTRIBUTES()
my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]
sa.SECURITY_DESCRIPTOR.SetSecurityDescriptorOwner(my_sid, 0)
k, disp = win32api.RegCreateKeyEx(
win32con.HKEY_CURRENT_USER,
"Python test key",
SecurityAttributes=sa,
samDesired=win32con.KEY_ALL_ACCESS,
Class="some class",
Options=0,
)
win32api.RegSetValue(k, None, win32con.REG_SZ, "Default value for python test key")
subk, disp = win32api.RegCreateKeyEx(
k,
"python test subkey",
SecurityAttributes=sa,
samDesired=win32con.KEY_ALL_ACCESS,
Class="some other class",
Options=0,
)
win32api.RegSetValue(subk, None, win32con.REG_SZ, "Default value for subkey")
win32api.RegSaveKeyEx(
k, fname, Flags=winnt.REG_STANDARD_FORMAT, SecurityAttributes=sa
)
restored_key, disp = win32api.RegCreateKeyEx(
win32con.HKEY_CURRENT_USER,
"Python test key(restored)",
SecurityAttributes=sa,
samDesired=win32con.KEY_ALL_ACCESS,
Class="restored class",
Options=0,
)
win32api.RegRestoreKey(restored_key, fname)
finally:
win32security.AdjustTokenPrivileges(th, 0, adjusted_privs)
@@ -0,0 +1,192 @@
import glob
import os
import time
import win32api
import win32con
import win32gui
for pname in (
## Set actions all take an unsigned int in pvParam
"SPI_GETMOUSESPEED",
"SPI_GETACTIVEWNDTRKTIMEOUT",
"SPI_GETCARETWIDTH",
"SPI_GETFOREGROUNDFLASHCOUNT",
"SPI_GETFOREGROUNDLOCKTIMEOUT",
## Set actions all take an unsigned int in uiParam
"SPI_GETWHEELSCROLLLINES",
"SPI_GETKEYBOARDDELAY",
"SPI_GETKEYBOARDSPEED",
"SPI_GETMOUSEHOVERHEIGHT",
"SPI_GETMOUSEHOVERWIDTH",
"SPI_GETMOUSEHOVERTIME",
"SPI_GETSCREENSAVETIMEOUT",
"SPI_GETMENUSHOWDELAY",
"SPI_GETBORDER",
"SPI_GETFONTSMOOTHINGCONTRAST",
"SPI_GETFONTSMOOTHINGTYPE",
"SPI_GETFOCUSBORDERHEIGHT",
"SPI_GETFOCUSBORDERWIDTH",
"SPI_GETMOUSECLICKLOCKTIME",
):
print(pname)
cget = getattr(win32con, pname)
cset = getattr(win32con, pname.replace("_GET", "_SET"))
orig_value = win32gui.SystemParametersInfo(cget)
print("\toriginal setting:", orig_value)
# Some values are clamped to an upper bound
# (like SPI_SETKEYBOARDDELAY, SPI_SETKEYBOARDSPEED, SPI_SETMOUSESPEED)
# SPI_SETMOUSESPEED specifically ranges [0-3]
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfoa#SPI_SETKEYBOARDDELAY
# Some values won't accept 0
new_value = orig_value + (1 if orig_value < 2 else -1)
win32gui.SystemParametersInfo(cset, new_value)
new_value = win32gui.SystemParametersInfo(cget)
print("\tnew value:", new_value)
assert new_value != orig_value
win32gui.SystemParametersInfo(cset, orig_value)
assert win32gui.SystemParametersInfo(cget) == orig_value
# change to opposite, check that it was changed and change back
for pname in (
# these take a boolean value in pvParam
"SPI_GETFLATMENU",
"SPI_GETDROPSHADOW",
"SPI_GETKEYBOARDCUES",
"SPI_GETMENUFADE",
"SPI_GETCOMBOBOXANIMATION",
"SPI_GETCURSORSHADOW",
"SPI_GETGRADIENTCAPTIONS",
"SPI_GETHOTTRACKING",
"SPI_GETLISTBOXSMOOTHSCROLLING",
"SPI_GETMENUANIMATION",
"SPI_GETSELECTIONFADE",
"SPI_GETTOOLTIPANIMATION",
"SPI_GETTOOLTIPFADE",
"SPI_GETUIEFFECTS",
"SPI_GETACTIVEWINDOWTRACKING",
"SPI_GETACTIVEWNDTRKZORDER",
# these take a boolean in uiParam
"SPI_GETFONTSMOOTHING",
"SPI_GETICONTITLEWRAP",
"SPI_GETBEEP",
"SPI_GETBLOCKSENDINPUTRESETS",
"SPI_GETKEYBOARDPREF",
"SPI_GETMENUDROPALIGNMENT",
"SPI_GETDRAGFULLWINDOWS",
"SPI_GETSHOWIMEUI",
# Can be changed, but will always return True,
# so don't include in demo since we can't know the value to revert
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfoa#SPI_GETSCREENSAVEACTIVE
# "SPI_GETSCREENSAVEACTIVE",
):
print(pname)
cget = getattr(win32con, pname)
cset = getattr(win32con, pname.replace("_GET", "_SET"))
orig_value = win32gui.SystemParametersInfo(cget)
print(orig_value)
win32gui.SystemParametersInfo(cset, not orig_value)
new_value = win32gui.SystemParametersInfo(cget)
print(new_value)
assert orig_value != new_value
win32gui.SystemParametersInfo(cset, orig_value)
assert win32gui.SystemParametersInfo(cget) == orig_value
print("SPI_GETICONTITLELOGFONT")
lf = win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)
orig_height = lf.lfHeight
orig_italic = lf.lfItalic
print("Height:", orig_height, "Italic:", orig_italic)
lf.lfHeight += 2
lf.lfItalic = not lf.lfItalic
win32gui.SystemParametersInfo(win32con.SPI_SETICONTITLELOGFONT, lf)
new_lf = win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)
print("New Height:", new_lf.lfHeight, "New Italic:", new_lf.lfItalic)
assert new_lf.lfHeight == orig_height + 2
assert new_lf.lfItalic != orig_italic
lf.lfHeight = orig_height
lf.lfItalic = orig_italic
win32gui.SystemParametersInfo(win32con.SPI_SETICONTITLELOGFONT, lf)
new_lf = win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)
assert new_lf.lfHeight == orig_height
assert new_lf.lfItalic == orig_italic
print("SPI_GETMOUSEHOVERWIDTH, SPI_GETMOUSEHOVERHEIGHT, SPI_GETMOUSEHOVERTIME")
w = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)
h = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)
t = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
print("w,h,t:", w, h, t)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERWIDTH, w + 1)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERHEIGHT, h + 2)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERTIME, t + 3)
new_w = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)
new_h = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)
new_t = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
print("new w,h,t:", new_w, new_h, new_t)
assert new_w == w + 1
assert new_h == h + 2
assert new_t == t + 3
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERWIDTH, w)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERHEIGHT, h)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERTIME, t)
new_w = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)
new_h = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)
new_t = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
assert new_w == w
assert new_h == h
assert new_t == t
print("SPI_SETDOUBLECLKWIDTH, SPI_SETDOUBLECLKHEIGHT")
x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
print("x,y:", x, y)
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x + 1)
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y + 2)
new_x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
new_y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
print("new x,y:", new_x, new_y)
assert new_x == x + 1
assert new_y == y + 2
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x)
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y)
new_x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
new_y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
assert new_x == x
assert new_y == y
print("SPI_SETDRAGWIDTH, SPI_SETDRAGHEIGHT")
dw = win32api.GetSystemMetrics(win32con.SM_CXDRAG)
dh = win32api.GetSystemMetrics(win32con.SM_CYDRAG)
print("dw,dh:", dw, dh)
win32gui.SystemParametersInfo(win32con.SPI_SETDRAGWIDTH, dw + 1)
win32gui.SystemParametersInfo(win32con.SPI_SETDRAGHEIGHT, dh + 2)
new_dw = win32api.GetSystemMetrics(win32con.SM_CXDRAG)
new_dh = win32api.GetSystemMetrics(win32con.SM_CYDRAG)
print("new dw,dh:", new_dw, new_dh)
assert new_dw == dw + 1
assert new_dh == dh + 2
win32gui.SystemParametersInfo(win32con.SPI_SETDRAGWIDTH, dw)
win32gui.SystemParametersInfo(win32con.SPI_SETDRAGHEIGHT, dh)
new_dw = win32api.GetSystemMetrics(win32con.SM_CXDRAG)
new_dh = win32api.GetSystemMetrics(win32con.SM_CYDRAG)
assert new_dw == dw
assert new_dh == dh
orig_wallpaper = win32gui.SystemParametersInfo(Action=win32con.SPI_GETDESKWALLPAPER)
print("Original: ", orig_wallpaper)
for bmp in glob.glob(os.path.join(os.environ["windir"], "*.bmp")):
print(bmp)
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, Param=bmp)
print(win32gui.SystemParametersInfo(Action=win32con.SPI_GETDESKWALLPAPER))
time.sleep(1)
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, Param=orig_wallpaper)
@@ -0,0 +1,26 @@
# A sample distutils script to show to build your own
# extension module which extends pywintypes or pythoncom.
#
# Use 'python -m build' to build this extension.
import os
from setuptools import Extension, setup
from sysconfig import get_paths
sources = ["win32_extension.cpp"]
lib_dir = get_paths()["platlib"]
# Specify the directory where the PyWin32 .h and .lib files are installed.
# If you are doing a win32com extension, you will also need to add
# win32com\Include and win32com\Libs.
ext = Extension(
"win32_extension",
sources,
include_dirs=[os.path.join(lib_dir, "win32", "include")],
library_dirs=[os.path.join(lib_dir, "win32", "libs")],
)
setup(
name="win32 extension sample",
version="0.1",
ext_modules=[ext],
)
@@ -0,0 +1,18 @@
# 'Request' example added jjk 11/20/98
import win32ui # isort: skip # Must be imported before dde !
import dde
server = dde.CreateServer()
server.Create("TestClient")
conversation = dde.CreateConversation(server)
conversation.ConnectTo("RunAny", "RunAnyCommand")
conversation.Exec("DoSomething")
conversation.Exec("DoSomethingElse")
conversation.ConnectTo("RunAny", "ComputeStringLength")
s = "abcdefghi"
sl = conversation.Request(s)
print(f'length of "{s}" is {sl}')
@@ -0,0 +1,42 @@
# 'Request' example added jjk 11/20/98
import win32ui # isort: skip # Must be imported before dde !
import dde
from pywin.mfc import object
class MySystemTopic(object.Object):
def __init__(self):
object.Object.__init__(self, dde.CreateServerSystemTopic())
def Exec(self, cmd):
print("System Topic asked to exec", cmd)
class MyOtherTopic(object.Object):
def __init__(self, topicName):
object.Object.__init__(self, dde.CreateTopic(topicName))
def Exec(self, cmd):
print("Other Topic asked to exec", cmd)
class MyRequestTopic(object.Object):
def __init__(self, topicName):
topic = dde.CreateTopic(topicName)
topic.AddItem(dde.CreateStringItem(""))
object.Object.__init__(self, topic)
def Request(self, aString):
print("Request Topic asked to compute length of:", aString)
return str(len(aString))
server = dde.CreateServer()
server.AddTopic(MySystemTopic())
server.AddTopic(MyOtherTopic("RunAnyCommand"))
server.AddTopic(MyRequestTopic("ComputeStringLength"))
server.Create("RunAny")
while 1:
win32ui.PumpWaitingMessages(0, -1)
@@ -0,0 +1,246 @@
# Demonstrates using a taskbar icon to create and navigate between desktops
import _thread
import io
import time
import traceback
import pywintypes
import win32api
import win32con
import win32gui
import win32process
import win32service
## "Shell_TrayWnd" is class of system tray window, broadcasts "TaskbarCreated" when initialized
def desktop_name_dlgproc(hwnd, msg, wparam, lparam):
"""Handles messages from the desktop name dialog box"""
if msg in (win32con.WM_CLOSE, win32con.WM_DESTROY):
win32gui.DestroyWindow(hwnd)
elif msg == win32con.WM_COMMAND:
if wparam == win32con.IDOK:
desktop_name = win32gui.GetDlgItemText(hwnd, 72)
print("new desktop name: ", desktop_name)
win32gui.DestroyWindow(hwnd)
create_desktop(desktop_name)
elif wparam == win32con.IDCANCEL:
win32gui.DestroyWindow(hwnd)
def get_new_desktop_name(parent_hwnd):
"""Create a dialog box to ask the user for name of desktop to be created"""
msgs = {
win32con.WM_COMMAND: desktop_name_dlgproc,
win32con.WM_CLOSE: desktop_name_dlgproc,
win32con.WM_DESTROY: desktop_name_dlgproc,
}
# dlg item [type, caption, id, (x,y,cx,cy), style, ex style
style = (
win32con.WS_BORDER
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
) ## |win32con.DS_SYSMODAL
h = win32gui.CreateDialogIndirect(
win32api.GetModuleHandle(None),
[
["One ugly dialog box !", (100, 100, 200, 100), style, 0],
[
"Button",
"Create",
win32con.IDOK,
(10, 10, 30, 20),
win32con.WS_VISIBLE
| win32con.WS_TABSTOP
| win32con.BS_HOLLOW
| win32con.BS_DEFPUSHBUTTON,
],
[
"Button",
"Never mind",
win32con.IDCANCEL,
(45, 10, 50, 20),
win32con.WS_VISIBLE | win32con.WS_TABSTOP | win32con.BS_HOLLOW,
],
["Static", "Desktop name:", 71, (10, 40, 70, 10), win32con.WS_VISIBLE],
["Edit", "", 72, (75, 40, 90, 10), win32con.WS_VISIBLE],
],
parent_hwnd,
msgs,
) ## parent_hwnd, msgs)
win32gui.EnableWindow(h, True)
hcontrol = win32gui.GetDlgItem(h, 72)
win32gui.EnableWindow(hcontrol, True)
win32gui.SetFocus(hcontrol)
def new_icon(hdesk, desktop_name):
"""Runs as a thread on each desktop to create a new tray icon and handle its messages"""
global id
id += 1
hdesk.SetThreadDesktop()
## apparently the threads can't use same hinst, so each needs its own window class
windowclassname = "PythonDesktopManager" + desktop_name
wc = win32gui.WNDCLASS()
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = windowclassname
wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW | win32con.CS_GLOBALCLASS
wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
wc.hbrBackground = win32con.COLOR_WINDOW
wc.lpfnWndProc = icon_wndproc
windowclass = win32gui.RegisterClass(wc)
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
hwnd = win32gui.CreateWindow(
windowclass,
"dm_" + desktop_name,
win32con.WS_SYSMENU,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0,
0,
wc.hInstance,
None,
)
win32gui.UpdateWindow(hwnd)
flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
notify_info = (
hwnd,
id,
flags,
win32con.WM_USER + 20,
hicon,
"Desktop Manager (%s)" % desktop_name,
)
window_info[hwnd] = notify_info
## wait for explorer to initialize system tray for new desktop
tray_found = 0
while not tray_found:
try:
tray_found = win32gui.FindWindow("Shell_TrayWnd", None)
except win32gui.error:
traceback.print_exc
time.sleep(0.5)
win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, notify_info)
win32gui.PumpMessages()
def create_desktop(desktop_name, start_explorer=1):
"""Creates a new desktop and spawns a thread running on it
Will also start a new icon thread on an existing desktop
"""
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle = 1
try:
hdesk = win32service.CreateDesktop(
desktop_name, 0, win32con.MAXIMUM_ALLOWED, sa
)
except win32service.error:
traceback.print_exc()
errbuf = io.StringIO()
traceback.print_exc(None, errbuf)
win32api.MessageBox(0, errbuf.getvalue(), "Desktop creation failed")
return
if start_explorer:
s = win32process.STARTUPINFO()
s.lpDesktop = desktop_name
prc_info = win32process.CreateProcess(
None,
"Explorer.exe",
None,
None,
True,
win32con.CREATE_NEW_CONSOLE,
None,
"c:\\",
s,
)
th = _thread.start_new_thread(new_icon, (hdesk, desktop_name))
hdesk.SwitchDesktop()
def icon_wndproc(hwnd, msg, wp, lp):
"""Window proc for the tray icons"""
if lp == win32con.WM_LBUTTONDOWN:
## popup menu won't disappear if you don't do this
win32gui.SetForegroundWindow(hwnd)
curr_desktop = win32service.OpenInputDesktop(0, True, win32con.MAXIMUM_ALLOWED)
curr_desktop_name = win32service.GetUserObjectInformation(
curr_desktop, win32con.UOI_NAME
)
winsta = win32service.GetProcessWindowStation()
desktops = winsta.EnumDesktops()
m = win32gui.CreatePopupMenu()
desktop_cnt = len(desktops)
## *don't* create an item 0
for d in range(1, desktop_cnt + 1):
mf_flags = win32con.MF_STRING
## if you switch to winlogon yourself, there's nothing there and you're stuck
if desktops[d - 1].lower() in ("winlogon", "disconnect"):
mf_flags |= win32con.MF_GRAYED | win32con.MF_DISABLED
if desktops[d - 1] == curr_desktop_name:
mf_flags |= win32con.MF_CHECKED
win32gui.AppendMenu(m, mf_flags, d, desktops[d - 1])
win32gui.AppendMenu(m, win32con.MF_STRING, desktop_cnt + 1, "Create new ...")
win32gui.AppendMenu(m, win32con.MF_STRING, desktop_cnt + 2, "Exit")
x, y = win32gui.GetCursorPos()
d = win32gui.TrackPopupMenu(
m,
win32con.TPM_LEFTBUTTON | win32con.TPM_RETURNCMD | win32con.TPM_NONOTIFY,
x,
y,
0,
hwnd,
None,
)
win32gui.PumpWaitingMessages()
win32gui.DestroyMenu(m)
if d == desktop_cnt + 1: ## Create new
get_new_desktop_name(hwnd)
elif d == desktop_cnt + 2: ## Exit
win32gui.PostQuitMessage(0)
win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, window_info[hwnd])
del window_info[hwnd]
origin_desktop.SwitchDesktop()
elif d > 0:
hdesk = win32service.OpenDesktop(
desktops[d - 1], 0, 0, win32con.MAXIMUM_ALLOWED
)
hdesk.SwitchDesktop()
return 0
else:
return win32gui.DefWindowProc(hwnd, msg, wp, lp)
window_info = {}
origin_desktop = win32service.OpenInputDesktop(0, True, win32con.MAXIMUM_ALLOWED)
origin_desktop_name = win32service.GetUserObjectInformation(
origin_desktop, win32service.UOI_NAME
)
hinst = win32api.GetModuleHandle(None)
try:
hicon = win32gui.LoadIcon(hinst, 1) ## python.exe and pythonw.exe
except win32gui.error:
hicon = win32gui.LoadIcon(hinst, 135) ## pythonwin's icon
id = 0
create_desktop(str(origin_desktop_name), 0)
## wait for first thread to initialize its icon
while not window_info:
time.sleep(1)
## exit when last tray icon goes away
while window_info:
win32gui.PumpWaitingMessages()
time.sleep(3)
@@ -0,0 +1,138 @@
import win32api # To translate NT Sids to account names.
import win32con
import win32evtlog
import win32evtlogutil
import win32security
def ReadLog(computer, logType="Application", dumpEachRecord=0):
# read the entire log back.
h = win32evtlog.OpenEventLog(computer, logType)
numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
# print(f"There are {numRecords} records")
num = 0
while 1:
objects = win32evtlog.ReadEventLog(
h,
win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ,
0,
)
if not objects:
break
for object in objects:
# get it for testing purposes, but don't print it.
msg = win32evtlogutil.SafeFormatMessage(object, logType)
if object.Sid is not None:
try:
domain, user, typ = win32security.LookupAccountSid(
computer, object.Sid
)
sidDesc = f"{domain}/{user}"
except win32security.error:
sidDesc = str(object.Sid)
user_desc = f"Event associated with user {sidDesc}"
else:
user_desc = None
if dumpEachRecord:
print(
"Event record from {!r} generated at {}".format(
object.SourceName, object.TimeGenerated.Format()
)
)
if user_desc:
print(user_desc)
try:
print(msg)
except UnicodeError:
print("(unicode error printing message: repr() follows...)")
print(repr(msg))
num += len(objects)
if numRecords == num:
print("Successfully read all", numRecords, "records")
else:
print(
"Couldn't get all records - reported %d, but found %d" % (numRecords, num)
)
print(
"(Note that some other app may have written records while we were running!)"
)
win32evtlog.CloseEventLog(h)
def usage():
print("Writes an event to the event log.")
print("-w : Don't write any test records.")
print("-r : Don't read the event log")
print("-c : computerName : Process the log on the specified computer")
print("-v : Verbose")
print("-t : LogType - Use the specified log - default = 'Application'")
def test():
import getopt
import sys
opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
computer = None
do_read = do_write = 1
logType = "Application"
verbose = 0
if len(args) > 0:
print("Invalid args")
usage()
return 1
for opt, val in opts:
if opt == "-t":
logType = val
if opt == "-c":
computer = val
if opt in ["-h", "-?"]:
usage()
return
if opt == "-r":
do_read = 0
if opt == "-w":
do_write = 0
if opt == "-v":
verbose += 1
if do_write:
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
win32evtlogutil.ReportEvent(
logType,
2,
strings=["The message text for event 2", "Another insert"],
data=b"Raw\0Data",
sid=my_sid,
)
win32evtlogutil.ReportEvent(
logType,
1,
eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
strings=["A warning", "An even more dire warning"],
data=b"Raw\0Data",
sid=my_sid,
)
win32evtlogutil.ReportEvent(
logType,
1,
eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
strings=["An info", "Too much info"],
data=b"Raw\0Data",
sid=my_sid,
)
print("Successfully wrote 3 records to the log")
if do_read:
ReadLog(computer, logType, verbose > 0)
if __name__ == "__main__":
test()
@@ -0,0 +1,33 @@
import os
import win32api
ver_strings = (
"Comments",
"InternalName",
"ProductName",
"CompanyName",
"LegalCopyright",
"ProductVersion",
"FileDescription",
"LegalTrademarks",
"PrivateBuild",
"FileVersion",
"OriginalFilename",
"SpecialBuild",
)
fname = os.environ["comspec"]
d = win32api.GetFileVersionInfo(fname, "\\")
## backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc
for n, v in d.items():
print(n, v)
pairs = win32api.GetFileVersionInfo(fname, "\\VarFileInfo\\Translation")
## \VarFileInfo\Translation returns list of available (language, codepage) pairs that can be used to retreive string info
## any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle two are language/codepage pair returned from above
for lang, codepage in pairs:
print("lang:", lang, "codepage:", codepage)
for ver_string in ver_strings:
str_info = f"\\StringFileInfo\\{lang:04X}{codepage:04X}\\{ver_string}"
# print(str_inf)
print(ver_string, repr(win32api.GetFileVersionInfo(fname, str_info)))
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

@@ -0,0 +1,101 @@
import os
import tempfile
import mmapfile
import win32api
import winerror
system_info = win32api.GetSystemInfo()
page_size = system_info[1]
alloc_size = system_info[7]
fname = tempfile.mktemp()
mapping_name = os.path.split(fname)[1]
fsize = 8 * page_size
print(fname, fsize, mapping_name)
m1 = mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize)
m1.seek(100)
m1.write_byte(b"?")
m1.seek(-1, 1)
assert m1.read_byte() == b"?"
## A reopened named mapping should have exact same size as original mapping
m2 = mmapfile.mmapfile(Name=mapping_name, File=None, MaximumSize=fsize * 2)
assert m2.size() == m1.size()
m1.seek(0, 0)
m1.write(fsize * b"s")
assert m2.read(fsize) == fsize * b"s"
move_src = 100
move_dest = 500
move_size = 150
m2.seek(move_src, 0)
assert m2.tell() == move_src
m2.write(b"m" * move_size)
m2.move(move_dest, move_src, move_size)
m2.seek(move_dest, 0)
assert m2.read(move_size) == b"m" * move_size
## m2.write('x'* (fsize+1))
m2.close()
m1.resize(fsize * 2)
assert m1.size() == fsize * 2
m1.seek(fsize)
m1.write(b"w" * fsize)
m1.flush()
m1.close()
os.remove(fname)
## Test a file with size larger than 32 bits
## need 10 GB free on drive where your temp folder lives
fname_large = tempfile.mktemp()
mapping_name = "Pywin32_large_mmap"
offsetdata = b"This is start of offset"
## Deliberately use odd numbers to test rounding logic
fsize = (1024 * 1024 * 1024 * 10) + 333
offset = (1024 * 1024 * 32) + 42
view_size = (1024 * 1024 * 16) + 111
## round mapping size and view size up to multiple of system page size
if fsize % page_size:
fsize += page_size - (fsize % page_size)
if view_size % page_size:
view_size += page_size - (view_size % page_size)
## round offset down to multiple of allocation granularity
offset -= offset % alloc_size
m1 = None
m2 = None
try:
try:
m1 = mmapfile.mmapfile(fname_large, mapping_name, fsize, 0, offset * 2)
except mmapfile.error as exc:
# if we don't have enough disk-space, that's OK.
if exc.winerror != winerror.ERROR_DISK_FULL:
raise
print("skipping large file test - need", fsize, "available bytes.")
else:
m1.seek(offset)
m1.write(offsetdata)
## When reopening an existing mapping without passing a file handle, you have
## to specify a positive size even though it's ignored
m2 = mmapfile.mmapfile(
File=None,
Name=mapping_name,
MaximumSize=1,
FileOffset=offset,
NumberOfBytesToMap=view_size,
)
assert m2.read(len(offsetdata)) == offsetdata
finally:
if m1 is not None:
m1.close()
if m2 is not None:
m2.close()
if os.path.exists(fname_large):
os.remove(fname_large)
@@ -0,0 +1,17 @@
"""cat.py
a version of unix cat, tweaked to show off runproc.py
"""
import sys
data = sys.stdin.read(1)
sys.stdout.write(data)
sys.stdout.flush()
while data:
data = sys.stdin.read(1)
sys.stdout.write(data)
sys.stdout.flush()
# Just here to have something to read from stderr.
sys.stderr.write("Blah...")
# end of cat.py
@@ -0,0 +1,114 @@
"""runproc.py
start a process with three inherited pipes.
Try to write to and read from those.
"""
import msvcrt
import os
import win32api
import win32con
import win32file
import win32pipe
import win32process
import win32security
class Process:
def run(self, cmdline):
# security attributes for pipes
sAttrs = win32security.SECURITY_ATTRIBUTES()
sAttrs.bInheritHandle = 1
# create pipes
hStdin_r, self.hStdin_w = win32pipe.CreatePipe(sAttrs, 0)
self.hStdout_r, hStdout_w = win32pipe.CreatePipe(sAttrs, 0)
self.hStderr_r, hStderr_w = win32pipe.CreatePipe(sAttrs, 0)
# set the info structure for the new process.
StartupInfo = win32process.STARTUPINFO()
StartupInfo.hStdInput = hStdin_r
StartupInfo.hStdOutput = hStdout_w
StartupInfo.hStdError = hStderr_w
StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
# Mark doesn't support wShowWindow yet.
# StartupInfo.dwFlags = StartupInfo.dwFlags | win32process.STARTF_USESHOWWINDOW
# StartupInfo.wShowWindow = win32con.SW_HIDE
# Create new output read handles and the input write handle. Set
# the inheritance properties to FALSE. Otherwise, the child inherits
# the these handles; resulting in non-closeable handles to the pipes
# being created.
pid = win32api.GetCurrentProcess()
tmp = win32api.DuplicateHandle(
pid,
self.hStdin_w,
pid,
0,
0, # non-inheritable!!
win32con.DUPLICATE_SAME_ACCESS,
)
# Close the inhertible version of the handle
win32file.CloseHandle(self.hStdin_w)
self.hStdin_w = tmp
tmp = win32api.DuplicateHandle(
pid,
self.hStdout_r,
pid,
0,
0, # non-inheritable!
win32con.DUPLICATE_SAME_ACCESS,
)
# Close the inhertible version of the handle
win32file.CloseHandle(self.hStdout_r)
self.hStdout_r = tmp
# start the process.
hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
None, # program
cmdline, # command line
None, # process security attributes
None, # thread attributes
1, # inherit handles, or USESTDHANDLES won't work.
# creation flags. Don't access the console.
0, # Don't need anything here.
# If you're in a GUI app, you should use
# CREATE_NEW_CONSOLE here, or any subprocesses
# might fall victim to the problem described in:
# KB article: Q156755, cmd.exe requires
# an NT console in order to perform redirection..
None, # no new environment
None, # current directory (stay where we are)
StartupInfo,
)
# normally, we would save the pid etc. here...
# Child is launched. Close the parents copy of those pipe handles
# that only the child should have open.
# You need to make sure that no handles to the write end of the
# output pipe are maintained in this process or else the pipe will
# not close when the child process exits and the ReadFile will hang.
win32file.CloseHandle(hStderr_w)
win32file.CloseHandle(hStdout_w)
win32file.CloseHandle(hStdin_r)
self.stdin = os.fdopen(msvcrt.open_osfhandle(self.hStdin_w, 0), "wb")
self.stdin.write("hmmmmm\r\n")
self.stdin.flush()
self.stdin.close()
self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb")
print(f"Read on stdout: {self.stdout.read()!r}")
self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb")
print(f"Read on stderr: {self.stderr.read()!r}")
if __name__ == "__main__":
p = Process()
exe = win32api.GetModuleFileName(0)
p.run(exe + " cat.py")
# end of runproc.py
@@ -0,0 +1,113 @@
import pywintypes
import win32api
import win32con
import win32gui
import win32print
pname = win32print.GetDefaultPrinter()
print(pname)
p = win32print.OpenPrinter(pname)
print("Printer handle: ", p)
print_processor = win32print.GetPrinter(p, 2)["pPrintProcessor"]
## call with last parm set to 0 to get total size needed for printer's DEVMODE
dmsize = win32print.DocumentProperties(0, p, pname, None, None, 0)
## dmDriverExtra should be total size - fixed size
driverextra = (
dmsize - pywintypes.DEVMODEType().Size
) ## need a better way to get DEVMODE.dmSize
dm = pywintypes.DEVMODEType(driverextra)
dm.Fields = dm.Fields | win32con.DM_ORIENTATION | win32con.DM_COPIES
dm.Orientation = win32con.DMORIENT_LANDSCAPE
dm.Copies = 2
win32print.DocumentProperties(
0, p, pname, dm, dm, win32con.DM_IN_BUFFER | win32con.DM_OUT_BUFFER
)
pDC = win32gui.CreateDC(print_processor, pname, dm)
printerwidth = win32print.GetDeviceCaps(pDC, win32con.PHYSICALWIDTH)
printerheight = win32print.GetDeviceCaps(pDC, win32con.PHYSICALHEIGHT)
hwnd = win32gui.GetDesktopWindow()
l, t, r, b = win32gui.GetWindowRect(hwnd)
desktopheight = b - t
desktopwidth = r - l
dDC = win32gui.GetWindowDC(hwnd)
dcDC = win32gui.CreateCompatibleDC(dDC)
dcBM = win32gui.CreateCompatibleBitmap(dDC, desktopwidth, desktopheight)
win32gui.SelectObject(dcDC, dcBM)
win32gui.StretchBlt(
dcDC,
0,
0,
desktopwidth,
desktopheight,
dDC,
0,
0,
desktopwidth,
desktopheight,
win32con.SRCCOPY,
)
pcDC = win32gui.CreateCompatibleDC(pDC)
pcBM = win32gui.CreateCompatibleBitmap(pDC, printerwidth, printerheight)
win32gui.SelectObject(pcDC, pcBM)
win32gui.StretchBlt(
pcDC,
0,
0,
printerwidth,
printerheight,
dcDC,
0,
0,
desktopwidth,
desktopheight,
win32con.SRCCOPY,
)
win32print.StartDoc(pDC, ("desktop.bmp", None, None, 0))
win32print.StartPage(pDC)
win32gui.StretchBlt(
pDC,
0,
0,
int(printerwidth * 0.9),
int(printerheight * 0.9),
pcDC,
0,
0,
printerwidth,
printerheight,
win32con.SRCCOPY,
)
font = win32gui.LOGFONT()
font.lfHeight = int(printerheight / 20)
font.lfWidth = font.lfHeight
font.lfWeight = 150
font.lfItalic = 1
font.lfUnderline = 1
hf = win32gui.CreateFontIndirect(font)
win32gui.SelectObject(pDC, hf)
win32gui.SetBkMode(pDC, win32con.TRANSPARENT)
win32gui.SetTextColor(pDC, win32api.RGB(0, 255, 0))
win32gui.DrawText(
pDC,
"Printed by Python!",
-1,
(0, 0, int(printerwidth * 0.9), int(printerheight * 0.9)),
win32con.DT_RIGHT | win32con.DT_BOTTOM | win32con.DT_SINGLELINE,
)
win32print.EndPage(pDC)
win32print.EndDoc(pDC)
win32print.ClosePrinter(p)
win32gui.DeleteObject(dcBM)
win32gui.DeleteObject(pcBM)
win32gui.DeleteObject(hf)
win32gui.DeleteDC(dDC)
win32gui.DeleteDC(dcDC)
win32gui.DeleteDC(pDC)
win32gui.DeleteDC(pcDC)
@@ -0,0 +1,168 @@
# rastest.py - test/demonstrate the win32ras module.
# Much of the code here contributed by Jethro Wright.
import os
import sys
import win32event
import win32ras
# Build a little dictionary of RAS states to decent strings.
# eg win32ras.RASCS_OpenPort -> "OpenPort"
stateMap = {
val: name[6:] for name, val in win32ras.__dict__.items() if name[:6] == "RASCS_"
}
# Use a lock so the callback can tell the main thread when it is finished.
callbackEvent = win32event.CreateEvent(None, 0, 0, None)
def Callback(hras, msg, state, error, exterror):
# print("Callback called with ", hras, msg, state, error, exterror)
stateName = stateMap.get(state, "Unknown state?")
print("Status is %s (%04lx), error code is %d" % (stateName, state, error))
finished = state in [win32ras.RASCS_Connected]
if finished:
win32event.SetEvent(callbackEvent)
if error != 0 or int(state) == win32ras.RASCS_Disconnected:
# we know for sure this is a good place to hangup....
print("Detected call failure: %s" % win32ras.GetErrorString(error))
HangUp(hras)
win32event.SetEvent(callbackEvent)
def ShowConnections():
print("All phone-book entries:")
for (name,) in win32ras.EnumEntries():
print(" ", name)
print("Current Connections:")
for con in win32ras.EnumConnections():
print(" ", con)
def EditEntry(entryName):
try:
win32ras.EditPhonebookEntry(0, None, entryName)
except win32ras.error as xxx_todo_changeme:
(rc, function, msg) = xxx_todo_changeme.args
print("Can not edit/find the RAS entry -", msg)
def HangUp(hras):
# trap potential, irrelevant errors from win32ras....
try:
win32ras.HangUp(hras)
except:
print("Tried to hang up gracefully on error, but didn't work....")
return None
def Connect(entryName, bUseCallback):
if bUseCallback:
theCallback = Callback
win32event.ResetEvent(callbackEvent)
else:
theCallback = None
# In order to *use* the username/password of a particular dun entry,
# one must explicitly get those params under Win95 ...
# It's unclear whether that's even still necessary.
try:
dp, b = win32ras.GetEntryDialParams(None, entryName)
except:
print("Couldn't find DUN entry: %s" % entryName)
else:
hras, rc = win32ras.Dial(
None, None, (entryName, "", "", dp[3], dp[4], ""), theCallback
)
# hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
# print(hras, rc)
if not bUseCallback and rc != 0:
print("Could not dial the RAS connection:", win32ras.GetErrorString(rc))
hras = HangUp(hras)
# don't wait here if there's no need to....
elif (
bUseCallback
and win32event.WaitForSingleObject(callbackEvent, 60000)
!= win32event.WAIT_OBJECT_0
):
print("Gave up waiting for the process to complete!")
# sdk docs state one must explicitly hangup, even if there's an error....
# https://learn.microsoft.com/en-us/windows/win32/api/ras/nf-ras-rasdialw#remarks
try:
cs = win32ras.GetConnectStatus(hras)
except:
# on error, attempt a hang up anyway....
hras = HangUp(hras)
else:
if int(cs[0]) == win32ras.RASCS_Disconnected:
hras = HangUp(hras)
return hras, rc
def Disconnect(rasEntry):
# Need to find the entry
name = rasEntry.lower()
for hcon, entryName, devName, devType in win32ras.EnumConnections():
if entryName.lower() == name:
win32ras.HangUp(hcon)
print("Disconnected from", rasEntry)
break
else:
print("Could not find an open connection to", entryName)
usage = """
Usage: %s [-s] [-l] [-c connection] [-d connection]
-l : List phone-book entries and current connections.
-s : Show status while connecting/disconnecting (uses callbacks)
-c : Connect to the specified phonebook name.
-d : Disconnect from the specified phonebook name.
-e : Edit the specified phonebook entry.
"""
def main():
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], "slc:d:e:")
except getopt.error as why:
print(why)
print(
usage
% (
os.path.basename(
sys.argv[0],
)
)
)
return
bCallback = 0
if args or not opts:
print(
usage
% (
os.path.basename(
sys.argv[0],
)
)
)
return
for opt, val in opts:
if opt == "-s":
bCallback = 1
if opt == "-l":
ShowConnections()
if opt == "-c":
hras, rc = Connect(val, bCallback)
if hras is not None:
print(f"hras: 0x{hras:8x}, rc: 0x{rc:04x}")
if opt == "-d":
Disconnect(val)
if opt == "-e":
EditEntry(val)
if __name__ == "__main__":
main()
@@ -0,0 +1,101 @@
"""Lists various types of information about current user's access token,
including UAC status."""
import win32api
import win32con
import win32security
from security_enums import (
SECURITY_IMPERSONATION_LEVEL,
TOKEN_ELEVATION_TYPE,
TOKEN_GROUP_ATTRIBUTES,
TOKEN_PRIVILEGE_ATTRIBUTES,
TOKEN_TYPE,
)
def dump_token(th):
token_type = win32security.GetTokenInformation(th, win32security.TokenType)
print("TokenType:", token_type, TOKEN_TYPE.lookup_name(token_type))
if token_type == win32security.TokenImpersonation:
imp_lvl = win32security.GetTokenInformation(
th, win32security.TokenImpersonationLevel
)
print(
"TokenImpersonationLevel:",
imp_lvl,
SECURITY_IMPERSONATION_LEVEL.lookup_name(imp_lvl),
)
print(
"TokenSessionId:",
win32security.GetTokenInformation(th, win32security.TokenSessionId),
)
privs = win32security.GetTokenInformation(th, win32security.TokenPrivileges)
print("TokenPrivileges:")
for priv_luid, priv_flags in privs:
flag_names, unk = TOKEN_PRIVILEGE_ATTRIBUTES.lookup_flags(priv_flags)
flag_desc = " ".join(flag_names)
if unk:
flag_desc += f"({unk})"
priv_name = win32security.LookupPrivilegeName("", priv_luid)
priv_desc = win32security.LookupPrivilegeDisplayName("", priv_name)
print("\t", priv_name, priv_desc, priv_flags, flag_desc)
print("TokenGroups:")
groups = win32security.GetTokenInformation(th, win32security.TokenGroups)
for group_sid, group_attr in groups:
flag_names, unk = TOKEN_GROUP_ATTRIBUTES.lookup_flags(group_attr)
flag_desc = " ".join(flag_names)
if unk:
flag_desc += f"({unk})"
if group_attr & TOKEN_GROUP_ATTRIBUTES.SE_GROUP_LOGON_ID:
sid_desc = "Logon sid"
else:
sid_desc = win32security.LookupAccountSid("", group_sid)
print("\t", group_sid, sid_desc, group_attr, flag_desc)
print(
"TokenElevation:",
win32security.GetTokenInformation(th, win32security.TokenElevation),
)
print(
"TokenHasRestrictions:",
win32security.GetTokenInformation(th, win32security.TokenHasRestrictions),
)
print(
"TokenMandatoryPolicy",
win32security.GetTokenInformation(th, win32security.TokenMandatoryPolicy),
)
print(
"TokenVirtualizationAllowed:",
win32security.GetTokenInformation(th, win32security.TokenVirtualizationAllowed),
)
print(
"TokenVirtualizationEnabled:",
win32security.GetTokenInformation(th, win32security.TokenVirtualizationEnabled),
)
elevation_type = win32security.GetTokenInformation(
th, win32security.TokenElevationType
)
print(
"TokenElevationType:",
elevation_type,
TOKEN_ELEVATION_TYPE.lookup_name(elevation_type),
)
if elevation_type != win32security.TokenElevationTypeDefault:
lt = win32security.GetTokenInformation(th, win32security.TokenLinkedToken)
print("TokenLinkedToken:", lt)
else:
lt = None
return lt
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.MAXIMUM_ALLOWED)
lt = dump_token(th)
if lt:
print("\n\nlinked token info:")
dump_token(lt)
@@ -0,0 +1,49 @@
import ntsecuritycon
import win32api
import win32con
import win32security
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_CREATE_PERMANENT_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", "SeEnableDelegationPrivilege"),
win32con.SE_PRIVILEGE_ENABLED,
), ##doesn't seem to be in ntsecuritycon.py ?
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32security.TOKEN_ALL_ACCESS
) ##win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
policy_handle = win32security.GetPolicyHandle("", win32security.POLICY_ALL_ACCESS)
tmp_sid = win32security.LookupAccountName("", "tmp")[0]
privs = [
ntsecuritycon.SE_DEBUG_NAME,
ntsecuritycon.SE_TCB_NAME,
ntsecuritycon.SE_RESTORE_NAME,
ntsecuritycon.SE_REMOTE_SHUTDOWN_NAME,
]
win32security.LsaAddAccountRights(policy_handle, tmp_sid, privs)
privlist = win32security.LsaEnumerateAccountRights(policy_handle, tmp_sid)
for priv in privlist:
print(priv)
privs = [ntsecuritycon.SE_DEBUG_NAME, ntsecuritycon.SE_TCB_NAME]
win32security.LsaRemoveAccountRights(policy_handle, tmp_sid, 0, privs)
privlist = win32security.LsaEnumerateAccountRights(policy_handle, tmp_sid)
for priv in privlist:
print(priv)
win32security.LsaClose(policy_handle)
@@ -0,0 +1,170 @@
import os
import ntsecuritycon
import win32api
import win32con
import win32security
from security_enums import ACCESS_MODE, ACE_FLAGS, TRUSTEE_FORM, TRUSTEE_TYPE
fname = os.path.join(win32api.GetTempPath(), "win32security_test.txt")
f = open(fname, "w")
f.write("Hello from Python\n")
f.close()
print("Testing on file", fname)
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SHUTDOWN_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_RESTORE_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_CREATE_PERMANENT_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", "SeEnableDelegationPrivilege"),
win32con.SE_PRIVILEGE_ENABLED,
), ##doesn't seem to be in ntsecuritycon.py ?
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32security.TOKEN_ALL_ACCESS
) ##win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
all_security_info = (
win32security.OWNER_SECURITY_INFORMATION
| win32security.GROUP_SECURITY_INFORMATION
| win32security.DACL_SECURITY_INFORMATION
| win32security.SACL_SECURITY_INFORMATION
)
sd = win32security.GetFileSecurity(fname, all_security_info)
old_sacl = sd.GetSecurityDescriptorSacl()
if old_sacl is None:
old_sacl = win32security.ACL()
old_dacl = sd.GetSecurityDescriptorDacl()
if old_dacl is None:
old_dacl = win32security.ACL()
my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]
tmp_sid = win32security.LookupAccountName("", "tmp")[0]
pwr_sid = win32security.LookupAccountName("", "Power Users")[0]
## MultipleTrustee,MultipleTrusteeOperation,TrusteeForm,TrusteeType,Identifier
## first two are ignored
my_trustee = {}
my_trustee["MultipleTrustee"] = None
my_trustee["MultipleTrusteeOperation"] = 0
my_trustee["TrusteeForm"] = TRUSTEE_FORM.TRUSTEE_IS_SID
my_trustee["TrusteeType"] = TRUSTEE_TYPE.TRUSTEE_IS_USER
my_trustee["Identifier"] = my_sid
tmp_trustee = {}
tmp_trustee["MultipleTrustee"] = None
tmp_trustee["MultipleTrusteeOperation"] = 0
tmp_trustee["TrusteeForm"] = TRUSTEE_FORM.TRUSTEE_IS_NAME
tmp_trustee["TrusteeType"] = TRUSTEE_TYPE.TRUSTEE_IS_USER
tmp_trustee["Identifier"] = "rupole\\tmp"
pwr_trustee = {}
pwr_trustee["MultipleTrustee"] = None
pwr_trustee["MultipleTrusteeOperation"] = 0
pwr_trustee["TrusteeForm"] = TRUSTEE_FORM.TRUSTEE_IS_SID
pwr_trustee["TrusteeType"] = TRUSTEE_TYPE.TRUSTEE_IS_USER
pwr_trustee["Identifier"] = pwr_sid
expl_list = []
expl_list.append(
{
"Trustee": my_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.SET_AUDIT_SUCCESS, ##|ACCESS_MODE.SET_AUDIT_FAILURE,
"AccessPermissions": win32con.GENERIC_ALL,
}
)
expl_list.append(
{
"Trustee": my_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.SET_AUDIT_FAILURE,
"AccessPermissions": win32con.GENERIC_ALL,
}
)
expl_list.append(
{
"Trustee": tmp_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.SET_AUDIT_SUCCESS,
"AccessPermissions": win32con.GENERIC_ALL,
}
)
expl_list.append(
{
"Trustee": tmp_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.SET_AUDIT_FAILURE,
"AccessPermissions": win32con.GENERIC_ALL,
}
)
old_sacl.SetEntriesInAcl(expl_list)
expl_list = []
expl_list.append(
{
"Trustee": tmp_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.DENY_ACCESS,
"AccessPermissions": win32con.DELETE,
}
)
expl_list.append(
{
"Trustee": tmp_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.GRANT_ACCESS,
"AccessPermissions": win32con.WRITE_OWNER,
}
)
expl_list.append(
{
"Trustee": pwr_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.GRANT_ACCESS,
"AccessPermissions": win32con.GENERIC_READ,
}
)
expl_list.append(
{
"Trustee": my_trustee,
"Inheritance": ACE_FLAGS.NO_INHERITANCE,
"AccessMode": ACCESS_MODE.GRANT_ACCESS,
"AccessPermissions": win32con.GENERIC_ALL,
}
)
old_dacl.SetEntriesInAcl(expl_list)
sd.SetSecurityDescriptorSacl(1, old_sacl, 1)
sd.SetSecurityDescriptorDacl(1, old_dacl, 1)
sd.SetSecurityDescriptorOwner(pwr_sid, 1)
win32security.SetFileSecurity(fname, all_security_info, sd)
@@ -0,0 +1,39 @@
import win32security
policy_handle = win32security.GetPolicyHandle("rupole", win32security.POLICY_ALL_ACCESS)
# mod_nbr, mod_time = win32security.LsaQueryInformationPolicy(policy_handle,win32security.PolicyModificationInformation)
# print(mod_nbr, mod_time)
(
domain_name,
dns_domain_name,
dns_forest_name,
domain_guid,
domain_sid,
) = win32security.LsaQueryInformationPolicy(
policy_handle, win32security.PolicyDnsDomainInformation
)
print(domain_name, dns_domain_name, dns_forest_name, domain_guid, domain_sid)
event_audit_info = win32security.LsaQueryInformationPolicy(
policy_handle, win32security.PolicyAuditEventsInformation
)
print(event_audit_info)
domain_name, sid = win32security.LsaQueryInformationPolicy(
policy_handle, win32security.PolicyPrimaryDomainInformation
)
print(domain_name, sid)
domain_name, sid = win32security.LsaQueryInformationPolicy(
policy_handle, win32security.PolicyAccountDomainInformation
)
print(domain_name, sid)
server_role = win32security.LsaQueryInformationPolicy(
policy_handle, win32security.PolicyLsaServerRoleInformation
)
print("server role: ", server_role)
win32security.LsaClose(policy_handle)
@@ -0,0 +1,35 @@
import ntsecuritycon
import win32api
import win32con
import win32security
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_CREATE_PERMANENT_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", "SeEnableDelegationPrivilege"),
win32con.SE_PRIVILEGE_ENABLED,
), ##doesn't seem to be in ntsecuritycon.py ?
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32security.TOKEN_ALL_ACCESS
) ##win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
policy_handle = win32security.GetPolicyHandle("", win32security.POLICY_ALL_ACCESS)
sidlist = win32security.LsaEnumerateAccountsWithUserRight(
policy_handle, ntsecuritycon.SE_RESTORE_NAME
)
for sid in sidlist:
print(win32security.LookupAccountSid("", sid))
win32security.LsaClose(policy_handle)
@@ -0,0 +1,70 @@
# A Python port of the MS knowledge base article Q157234
# "How to deal with localized and renamed user and group names"
# https://www.betaarchive.com/wiki/index.php?title=Microsoft_KB_Archive/157234
import sys
import pywintypes
from ntsecuritycon import (
DOMAIN_ALIAS_RID_ADMINS,
DOMAIN_USER_RID_ADMIN,
SECURITY_BUILTIN_DOMAIN_RID,
SECURITY_NT_AUTHORITY,
)
from win32net import NetUserModalsGet
from win32security import LookupAccountSid
def LookupAliasFromRid(TargetComputer, Rid):
# Sid is the same regardless of machine, since the well-known
# BUILTIN domain is referenced.
sid = pywintypes.SID()
sid.Initialize(SECURITY_NT_AUTHORITY, 2)
for i, r in enumerate((SECURITY_BUILTIN_DOMAIN_RID, Rid)):
sid.SetSubAuthority(i, r)
name, domain, typ = LookupAccountSid(TargetComputer, sid)
return name
def LookupUserGroupFromRid(TargetComputer, Rid):
# get the account domain Sid on the target machine
# note: if you were looking up multiple sids based on the same
# account domain, only need to call this once.
umi2 = NetUserModalsGet(TargetComputer, 2)
domain_sid = umi2["domain_id"]
SubAuthorityCount = domain_sid.GetSubAuthorityCount()
# create and init new sid with acct domain Sid + acct Rid
sid = pywintypes.SID()
sid.Initialize(domain_sid.GetSidIdentifierAuthority(), SubAuthorityCount + 1)
# copy existing subauthorities from account domain Sid into
# new Sid
for i in range(SubAuthorityCount):
sid.SetSubAuthority(i, domain_sid.GetSubAuthority(i))
# append Rid to new Sid
sid.SetSubAuthority(SubAuthorityCount, Rid)
name, domain, typ = LookupAccountSid(TargetComputer, sid)
return name
def main():
if len(sys.argv) == 2:
targetComputer = sys.argv[1]
else:
targetComputer = None
name = LookupUserGroupFromRid(targetComputer, DOMAIN_USER_RID_ADMIN)
print(f"'Administrator' user name = {name}")
name = LookupAliasFromRid(targetComputer, DOMAIN_ALIAS_RID_ADMINS)
print(f"'Administrators' local group/alias name = {name}")
if __name__ == "__main__":
main()
@@ -0,0 +1,14 @@
import win32event
import win32security
evt = win32event.CreateEvent(None, 0, 0, None)
win32security.LsaRegisterPolicyChangeNotification(
win32security.PolicyNotifyAuditEventsInformation, evt
)
print("Waiting for you change Audit policy in Management console ...")
ret_code = win32event.WaitForSingleObject(evt, 1000000000)
## should come back when you change Audit policy in Management console ...
print(ret_code)
win32security.LsaUnregisterPolicyChangeNotification(
win32security.PolicyNotifyAuditEventsInformation, evt
)
@@ -0,0 +1,12 @@
import win32security
policy_handle = win32security.GetPolicyHandle("", win32security.POLICY_ALL_ACCESS)
privatedata = "some sensitive data"
keyname = "tmp"
win32security.LsaStorePrivateData(policy_handle, keyname, privatedata)
retrieveddata = win32security.LsaRetrievePrivateData(policy_handle, keyname)
assert retrieveddata == privatedata
## passing None deletes key
win32security.LsaStorePrivateData(policy_handle, keyname, None)
win32security.LsaClose(policy_handle)
@@ -0,0 +1,25 @@
import win32api
import win32security
import winerror
from ntsecuritycon import TOKEN_QUERY, TokenUser
# This is a Python implementation of win32api.GetDomainName()
def GetDomainName():
try:
tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1)
except win32api.error as details:
if details[0] != winerror.ERROR_NO_TOKEN:
raise
# attempt to open the process token, since no thread token
# exists
tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(), TOKEN_QUERY)
sid, attr = win32security.GetTokenInformation(tok, TokenUser)
win32api.CloseHandle(tok)
name, dom, typ = win32security.LookupAccountSid(None, sid)
return dom
if __name__ == "__main__":
print("Domain name is", GetDomainName())
@@ -0,0 +1,61 @@
fname = "h:\\tmp.reg"
import os
import ntsecuritycon
import pywintypes
import win32api
import win32con
import win32security
## regsave will not overwrite a file
if os.path.isfile(fname):
os.remove(fname)
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_TCB_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_BACKUP_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_RESTORE_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32security.TOKEN_ALL_ACCESS | win32con.TOKEN_ADJUST_PRIVILEGES
)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]
hklm = win32api.RegOpenKey(
win32con.HKEY_LOCAL_MACHINE, None, 0, win32con.KEY_ALL_ACCESS
)
skey = win32api.RegOpenKey(hklm, "SYSTEM", 0, win32con.KEY_ALL_ACCESS)
sa = pywintypes.SECURITY_ATTRIBUTES()
sd = pywintypes.SECURITY_DESCRIPTOR()
sa.SECURITY_DESCRIPTOR = sd
acl = pywintypes.ACL()
pwr_sid = win32security.LookupAccountName("", "Power Users")[0]
acl.AddAccessAllowedAce(
win32con.ACL_REVISION,
win32con.GENERIC_READ | win32con.ACCESS_SYSTEM_SECURITY,
my_sid,
)
sd.SetSecurityDescriptorDacl(1, acl, 0)
sd.SetSecurityDescriptorOwner(pwr_sid, 0)
sa.bInheritHandle = 1
assert sa.SECURITY_DESCRIPTOR is sd
win32api.RegSaveKey(skey, fname, sa)
@@ -0,0 +1,36 @@
import ntsecuritycon
import win32api
import win32con
import win32security
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_TCB_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
)
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
ph, win32security.TOKEN_ALL_ACCESS | win32con.TOKEN_ADJUST_PRIVILEGES
)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
hkey = win32api.RegOpenKey(
win32con.HKEY_LOCAL_MACHINE, None, 0, win32con.KEY_ALL_ACCESS
)
win32api.RegCreateKey(hkey, "SYSTEM\\NOTMP")
notmpkey = win32api.RegOpenKey(
hkey, "SYSTEM\\notmp", 0, win32con.ACCESS_SYSTEM_SECURITY
)
tmp_sid = win32security.LookupAccountName("", "tmp")[0]
sacl = win32security.ACL()
sacl.AddAuditAccessAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, tmp_sid, 1, 1)
sd = win32security.SECURITY_DESCRIPTOR()
sd.SetSecurityDescriptorSacl(1, sacl, 1)
win32api.RegSetKeySecurity(notmpkey, win32con.SACL_SECURITY_INFORMATION, sd)
Loaded 100 of 7311 files, more files were not shown because too many files have changed in this diff. Show more