Uploaded Test files

This commit is contained in:
Batuhan Berk Başoğlu 2020-11-12 11:05:57 -05:00
parent f584ad9d97
commit 2e81cb7d99
16627 changed files with 2065359 additions and 102444 deletions

View file

@ -0,0 +1,81 @@
## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams
import win32file, win32api, win32con, win32security, ntsecuritycon
from win32com import storagecon
import pythoncom, pywintypes
import struct, traceback
from pywin32_testutil import str2bytes, ob2memory
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, str2bytes(''), 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 ob2memory(win32security.GetFileSecurity(tempfile,all_sd_info))[:]== \
ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !"
## also should check Summary Info programatically

View file

@ -0,0 +1,85 @@
## demonstrates using BackupSeek to enumerate data streams for a file
import win32file, win32api, win32con
from win32com import storagecon
import pythoncom, pywintypes
import struct, traceback
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)

View file

@ -0,0 +1,30 @@
import win32file, win32api
import os
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)

View file

@ -0,0 +1,81 @@
"""
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 win32file, win32api, win32transaction, winerror
import win32con, winioctlcon
import struct
import os
from pywin32_testutil import str2bytes # py3k-friendly helper
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, str2bytes('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, str2bytes('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

View file

@ -0,0 +1,67 @@
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(('Event {}'.format(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((' Timestamp: {}'.format(time_created_value.isoformat())))
computer_value, computer_variant = result[win32evtlog.EvtSystemComputer]
if computer_variant != win32evtlog.EvtVarTypeNull:
print((' FQDN: {}'.format(computer_value)))
provider_name_value, provider_name_variant = result[win32evtlog.EvtSystemProviderName]
if provider_name_variant != win32evtlog.EvtVarTypeNull:
print((' Provider: {}'.format(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:
print((' Message: {}'.format(message)))
if __name__=='__main__':
main()

View file

@ -0,0 +1,21 @@
## Demonstrates how to create a "pull" subscription
import win32evtlog, win32event, win32con
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

View file

@ -0,0 +1,16 @@
## Demonstrates a "push" subscription with a callback function
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=[]
s=win32evtlog.EvtSubscribe('System', win32evtlog.EvtSubscribeStartAtOldestRecord, Query='*', Callback=c, Context=evttext)

View file

@ -0,0 +1,68 @@
# Contributed by Kelly Kranabetter.
import os, sys
import win32security, ntsecuritycon
# 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")
sd= win32security.GetFileSecurity(name, win32security.OWNER_SECURITY_INFORMATION)
sid= sd.GetSecurityDescriptorOwner()
print(" ", win32security.LookupAccountSid(None, sid))
# get group SID
print("GROUP")
sd= win32security.GetFileSecurity(name, win32security.GROUP_SECURITY_INFORMATION)
sid= sd.GetSecurityDescriptorGroup()
print(" ", win32security.LookupAccountSid(None, sid))
# get ACEs
sd= win32security.GetFileSecurity(name, win32security.DACL_SECURITY_INFORMATION)
dacl= sd.GetSecurityDescriptorDacl()
if dacl == 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= calc_mask | getattr(ntsecuritycon, i)
print(" ", i)
print(" ", "Calculated Check Mask=", hex(calc_mask))
print(" -SID\n ", win32security.LookupAccountSid(None, ace[2]))

View file

@ -0,0 +1,36 @@
import win32gui, win32con, os
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('save file names:', repr(fname))
print('filter used:', repr(customfilter))
print('Flags:', flags)
for k,v in list(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('open file names:', repr(fname))
print('filter used:', repr(customfilter))
print('Flags:', flags)
for k,v in list(win32con.__dict__.items()):
if k.startswith('OFN_') and flags & v:
print('\t'+k)

View file

@ -0,0 +1,101 @@
"""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 sys
import win32api
import win32net, win32netcon
import optparse
from pprint import pprint
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 NotImplementedError:
print("NetValidatePasswordPolicy not implemented on this platform.")
return 1
except win32net.error as exc:
print("NetValidatePasswordPolicy failed: ", exc)
return 1
if options.show_fields:
print("NET_VALIDATE_PERSISTED_FIELDS fields:")
pprint(fields)
print("Result of %r validation is %d: %s" % \
(arg, status, win32api.FormatMessage(status).strip()))
return 0
if __name__=='__main__':
sys.exit(main())

View file

@ -0,0 +1,64 @@
import win32file, win32api, winerror
import os
def ReadCallback(input_buffer, data, buflen):
fnamein, fnameout, f = data
## print fnamein, fnameout, buflen
f.write(input_buffer)
## python 2.3 throws an error if return value is a plain int
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()

View file

@ -0,0 +1,43 @@
import win32api, win32con, 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)

View file

@ -0,0 +1,38 @@
import win32api, win32security
import win32con, ntsecuritycon, winnt
import os
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)

View file

@ -0,0 +1,180 @@
import win32gui, win32con, win32api, time, os, glob
## some of these tests will fail for systems prior to XP
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_GETLOWPOWERTIMEOUT", "SPI_GETPOWEROFFTIMEOUT", "SPI_GETBORDER",
## below are winxp only:
"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)
win32gui.SystemParametersInfo(cset, orig_value+1)
new_value=win32gui.SystemParametersInfo(cget)
print('\tnew value:',new_value)
# On Vista, some of these values seem to be ignored. So only "fail" if
# the new value isn't what we set or the original
if new_value!=orig_value+1:
assert new_value == orig_value
print("Strange - setting %s seems to have been ignored" % (pname,))
win32gui.SystemParametersInfo(cset, orig_value)
assert win32gui.SystemParametersInfo(cget)==orig_value
# these take a boolean value in pvParam
# change to opposite, check that it was changed and change back
for pname in ("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"):
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
# these take a boolean in uiParam
# could combine with above section now that SystemParametersInfo only takes a single parameter
for pname in ("SPI_GETFONTSMOOTHING","SPI_GETICONTITLEWRAP","SPI_GETBEEP","SPI_GETBLOCKSENDINPUTRESETS",
"SPI_GETKEYBOARDPREF","SPI_GETSCREENSAVEACTIVE","SPI_GETMENUDROPALIGNMENT",
"SPI_GETDRAGFULLWINDOWS", "SPI_GETSHOWIMEUI"):
cget=getattr(win32con,pname)
cset=getattr(win32con,pname.replace('_GET','_SET'))
orig_value=win32gui.SystemParametersInfo(cget)
win32gui.SystemParametersInfo(cset, not orig_value)
new_value=win32gui.SystemParametersInfo(cget)
# Some of these also can't be changed (eg, SPI_GETSCREENSAVEACTIVE) so
# don't actually get upset.
if orig_value!=new_value:
print("successfully toggled", pname, "from", orig_value, "to", new_value)
else:
print("couldn't toggle", pname, "from", orig_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)

View file

@ -0,0 +1,23 @@
# A sample distutils script to show to build your own
# extension module which extends pywintypes or pythoncom.
#
# Use 'python setup.py build' to build this extension.
import os
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_lib
sources = ["win32_extension.cpp"]
# 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(get_python_lib(), "win32", "Include")],
library_dirs = [os.path.join(get_python_lib(), "win32", "Libs")],
)
setup(
name="win32 extension sample",
version="0.1",
ext_modules=[ext],
)

View file

@ -0,0 +1,213 @@
# A demo of the Windows CE Remote API
#
# This connects to a CE device, and interacts with it.
import wincerapi
import win32event
import win32api
import win32con
import os
import sys
import getopt
def DumpPythonRegistry():
try:
h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver)
except win32api.error:
print("The remote device does not appear to have Python installed")
return 0
path, typ = wincerapi.CeRegQueryValueEx(h, None)
print("The remote PythonPath is '%s'" % (str(path), ))
h.Close()
return 1
def DumpRegistry(root, level=0):
# A recursive dump of the remote registry to test most functions.
h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None)
level_prefix = " " * level
index = 0
# Enumerate values.
while 1:
try:
name, data, typ = wincerapi.CeRegEnumValue(root, index)
except win32api.error:
break
print("%s%s=%s" % (level_prefix, name, repr(str(data))))
index = index+1
# Now enumerate all keys.
index=0
while 1:
try:
name, klass = wincerapi.CeRegEnumKeyEx(root, index)
except win32api.error:
break
print("%s%s\\" % (level_prefix, name))
subkey = wincerapi.CeRegOpenKeyEx(root, name)
DumpRegistry(subkey, level+1)
index = index+1
def DemoCopyFile():
# Create a file on the device, and write a string.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
wincerapi.CeWriteFile(cefile, "Hello from Python")
cefile.Close()
# reopen the file and check the data.
cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
if wincerapi.CeReadFile(cefile, 100) != "Hello from Python":
print("Couldnt read the data from the device!")
cefile.Close()
# Delete the test file
wincerapi.CeDeleteFile("TestPython")
print("Created, wrote to, read from and deleted a test file!")
def DemoCreateProcess():
try:
hp, ht, pid, tid = wincerapi.CeCreateProcess("Windows\\Python.exe", "", None, None, 0, 0, None, "", None)
# Not necessary, except to see if handle closing raises an exception
# (if auto-closed, the error is suppressed)
hp.Close()
ht.Close()
print("Python is running on the remote device!")
except win32api.error as xxx_todo_changeme1:
(hr, fn, msg) = xxx_todo_changeme1.args
print("Couldnt execute remote process -", msg)
def DumpRemoteMachineStatus():
ACLineStatus, BatteryFlag, BatteryLifePercent, BatteryLifeTime, BatteryFullLifeTime, BackupBatteryFlag, BackupBatteryLifePercent, BackupBatteryLifeTime, BackupBatteryLifeTime = \
wincerapi.CeGetSystemPowerStatusEx()
if ACLineStatus:
power = "AC"
else:
power = "battery"
if BatteryLifePercent==255:
batPerc = "unknown"
else:
batPerc = BatteryLifePercent
print("The batteries are at %s%%, and is currently being powered by %s" % (batPerc, power))
memLoad, totalPhys, availPhys, totalPage, availPage, totalVirt, availVirt = \
wincerapi.CeGlobalMemoryStatus()
print("The memory is %d%% utilized." % (memLoad))
print("%-20s%-10s%-10s" % ("", "Total", "Avail"))
print("%-20s%-10s%-10s" % ("Physical Memory", totalPhys, availPhys))
print("%-20s%-10s%-10s" % ("Virtual Memory", totalVirt, availVirt))
print("%-20s%-10s%-10s" % ("Paging file", totalPage, availPage))
storeSize, freeSize = wincerapi.CeGetStoreInformation()
print("%-20s%-10s%-10s" % ("File store", storeSize, freeSize))
print("The CE temp path is", wincerapi.CeGetTempPath())
print("The system info for the device is", wincerapi.CeGetSystemInfo())
def DumpRemoteFolders():
# Dump all special folders possible.
for name, val in list(wincerapi.__dict__.items()):
if name[:6]=="CSIDL_":
try:
loc = str(wincerapi.CeGetSpecialFolderPath(val))
print("Folder %s is at %s" % (name, loc))
except win32api.error as details:
pass
# Get the shortcut targets for the "Start Menu"
print("Dumping start menu shortcuts...")
try:
startMenu = str(wincerapi.CeGetSpecialFolderPath(wincerapi.CSIDL_STARTMENU))
except win32api.error as details:
print("This device has no start menu!", details)
startMenu = None
if startMenu:
for fileAttr in wincerapi.CeFindFiles(os.path.join(startMenu, "*")):
fileName = fileAttr[8]
fullPath = os.path.join(startMenu, str(fileName))
try:
resolved = wincerapi.CeSHGetShortcutTarget(fullPath)
except win32api.error as xxx_todo_changeme:
(rc, fn, msg) = xxx_todo_changeme.args
resolved = "#Error - %s" % msg
print("%s->%s" % (fileName, resolved))
# print "The start menu is at",
# print wincerapi.CeSHGetShortcutTarget("\\Windows\\Start Menu\\Shortcut to Python.exe.lnk")
def usage():
print("Options:")
print("-a - Execute all demos")
print("-p - Execute Python process on remote device")
print("-r - Dump the remote registry")
print("-f - Dump all remote special folder locations")
print("-s - Dont dump machine status")
print("-y - Perform asynch init of CE connection")
def main():
async_init = bStartPython = bDumpRegistry = bDumpFolders = 0
bDumpStatus = 1
try:
opts, args = getopt.getopt(sys.argv[1:], "apr")
except getopt.error as why:
print("Invalid usage:", why)
usage()
return
for o, v in opts:
if o=="-a":
bStartPython = bDumpRegistry = bDumpStatus = bDumpFolders = asynch_init = 1
if o=="-p":
bStartPython=1
if o=="-r":
bDumpRegistry=1
if o=="-s":
bDumpStatus=0
if o=="-f":
bDumpFolders = 1
if o=="-y":
print("Doing asynch init of CE connection")
async_init = 1
if async_init:
event, rc = wincerapi.CeRapiInitEx()
while 1:
rc = win32event.WaitForSingleObject(event, 500)
if rc==win32event.WAIT_OBJECT_0:
# We connected.
break
else:
print("Waiting for Initialize to complete (picture a Cancel button here :)")
else:
wincerapi.CeRapiInit()
print("Connected to remote CE device.")
try:
verinfo = wincerapi.CeGetVersionEx()
print("The device is running windows CE version %d.%d - %s" % (verinfo[0], verinfo[1], verinfo[4]))
if bDumpStatus:
print("Dumping remote machine status")
DumpRemoteMachineStatus()
if bDumpRegistry:
print("Dumping remote registry...")
DumpRegistry(win32con.HKEY_LOCAL_MACHINE)
if bDumpFolders:
print("Dumping remote folder information")
DumpRemoteFolders()
DemoCopyFile()
if bStartPython:
print("Starting remote Python process")
if DumpPythonRegistry():
DemoCreateProcess()
else:
print("Not trying to start Python, as it's not installed")
finally:
wincerapi.CeRapiUninit()
print("Disconnected")
if __name__=='__main__':
main()

View file

@ -0,0 +1,19 @@
# 'Request' example added jjk 11/20/98
import win32ui
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('length of "%s" is %s'%(s,sl))

View file

@ -0,0 +1,38 @@
# 'Request' example added jjk 11/20/98
import win32ui
from pywin.mfc import object
import dde
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)

View file

@ -0,0 +1,166 @@
# Demonstrates using a taskbar icon to create and navigate between desktops
import win32api, win32con, win32gui, win32service, win32process
import pywintypes
import traceback, _thread, time
import io
## "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=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(.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=mf_flags|win32con.MF_GRAYED|win32con.MF_DISABLED
if desktops[d-1]==curr_desktop_name:
mf_flags=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)

View file

@ -0,0 +1,111 @@
import win32evtlog
import win32api
import win32con
import win32security # To translate NT Sids to account names.
import win32evtlogutil
def ReadLog(computer, logType="Application", dumpEachRecord = 0):
# read the entire log back.
h=win32evtlog.OpenEventLog(computer, logType)
numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
# print "There are %d records" % numRecords
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 dont print it.
msg = win32evtlogutil.SafeFormatMessage(object, logType)
if object.Sid is not None:
try:
domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
sidDesc = "%s/%s" % (domain, user)
except win32security.error:
sidDesc = str(object.Sid)
user_desc = "Event associated with user %s" % (sidDesc,)
else:
user_desc = None
if dumpEachRecord:
print("Event record from %r generated at %s" % (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 = 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 : Dont write any test records.")
print("-r : Dont 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():
# check if running on Windows NT, if not, display notice and terminate
if win32api.GetVersion() & 0x80000000:
print("This sample only runs on NT")
return
import sys, getopt
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 = 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 = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
strings=["A warning","An even more dire warning"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
strings=["An info","Too much info"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
print("Successfully wrote 3 records to the log")
if do_read:
ReadLog(computer, logType, verbose > 0)
if __name__=='__main__':
test()

View file

@ -0,0 +1,21 @@
import os, 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='\\StringFileInfo\\%04X%04X\\%s' %(lang,codepage,ver_string)
## print str_info
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

View file

@ -0,0 +1,95 @@
import win32api, mmapfile
import winerror
import tempfile, os
from pywin32_testutil import str2bytes
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(str2bytes('?'))
m1.seek(-1,1)
assert m1.read_byte()==str2bytes('?')
## 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*str2bytes('s'))
assert m2.read(fsize)==fsize*str2bytes('s')
move_src=100
move_dest=500
move_size=150
m2.seek(move_src,0)
assert m2.tell()==move_src
m2.write(str2bytes('m')*move_size)
m2.move(move_dest, move_src, move_size)
m2.seek(move_dest, 0)
assert m2.read(move_size) == str2bytes('m') * move_size
## m2.write('x'* (fsize+1))
m2.close()
m1.resize(fsize*2)
assert m1.size()==fsize * 2
m1.seek(fsize)
m1.write(str2bytes('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=str2bytes('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)

View file

@ -0,0 +1,16 @@
'''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

View file

@ -0,0 +1,110 @@
'''runproc.py
start a process with three inherited pipes.
Try to write to and read from those.
'''
import win32api
import win32pipe
import win32file
import win32process
import win32security
import win32con
import msvcrt
import os
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("Read on stdout: ", repr(self.stdout.read()))
self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb")
print("Read on stderr: ", repr(self.stderr.read()))
if __name__ == '__main__':
p = Process()
exe = win32api.GetModuleFileName(0)
p.run(exe + ' cat.py')
# end of runproc.py

View file

@ -0,0 +1,67 @@
import win32print, pywintypes, win32con, win32gui, win32api
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*.9), int(printerheight*.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*.9), int(printerheight*.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)

View file

@ -0,0 +1,136 @@
# rastest.py - test/demonstrate the win32ras module.
# Much of the code here contributed by Jethro Wright.
import sys
import os
import win32ras
# Build a little dictionary of RAS states to decent strings.
# eg win32ras.RASCS_OpenPort -> "OpenPort"
stateMap = {}
for name, val in list(win32ras.__dict__.items()):
if name[:6]=="RASCS_":
stateMap[val] = name[6:]
# Use a lock so the callback can tell the main thread when it is finished.
import win32event
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....
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 explcitly hangup, even if there's an error....
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 != None:
print("hras: 0x%8lx, rc: 0x%04x" % ( hras, rc ))
if opt=="-d":
Disconnect(val)
if opt=="-e":
EditEntry(val)
if __name__=='__main__':
main()

View file

@ -0,0 +1,73 @@
""" Lists various types of information about current user's access token,
including UAC status on Vista
"""
import pywintypes, win32api, win32security
import win32con, winerror
from security_enums import TOKEN_GROUP_ATTRIBUTES, TOKEN_PRIVILEGE_ATTRIBUTES, \
SECURITY_IMPERSONATION_LEVEL, TOKEN_TYPE, TOKEN_ELEVATION_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 += '(' + str(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 += '(' + str(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)
## Vista token information types, will throw (87, 'GetTokenInformation', 'The parameter is incorrect.') on earier OS
try:
is_elevated=win32security.GetTokenInformation(th, win32security.TokenElevation)
print('TokenElevation:', is_elevated)
except pywintypes.error as details:
if details.winerror != winerror.ERROR_INVALID_PARAMETER:
raise
return None
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)

View file

@ -0,0 +1,31 @@
import win32security,win32file,win32api,ntsecuritycon,win32con
from security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODE
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)

View file

@ -0,0 +1,144 @@
import os
import win32security,win32file,win32api,ntsecuritycon,win32con
from security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODE
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==None:
old_sacl=win32security.ACL()
old_dacl=sd.GetSecurityDescriptorDacl()
if old_dacl==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)

View file

@ -0,0 +1,23 @@
import win32security,win32file,win32api,ntsecuritycon,win32con
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)

View file

@ -0,0 +1,20 @@
import win32security,win32file,win32api,ntsecuritycon,win32con
from security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODE
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)

View file

@ -0,0 +1,61 @@
# A Python port of the MS knowledge base article Q157234
# "How to deal with localized and renamed user and group names"
# http://support.microsoft.com/default.aspx?kbid=157234
import sys
from win32net import NetUserModalsGet
from win32security import LookupAccountSid
import pywintypes
from ntsecuritycon import *
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("'Administrator' user name = %s" % (name,))
name = LookupAliasFromRid(targetComputer, DOMAIN_ALIAS_RID_ADMINS)
print("'Administrators' local group/alias name = %s" % (name,))
if __name__=='__main__':
main()

View file

@ -0,0 +1,8 @@
import win32security, win32event
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)

View file

@ -0,0 +1,11 @@
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)

View file

@ -0,0 +1,25 @@
from ntsecuritycon import *
import win32api, win32security, winerror
# 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())

Some files were not shown because too many files have changed in this diff Show more