def GetDomainName():
try:
tok = win32security.OpenThreadToken(win32api.GetCurrentThread(),
TOKEN_QUERY, 1)
except win32api.error, 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
python类GetDomainName()的实例源码
def GeneralInfo():
global host,fv,srcfile
host=win32api.GetComputerName()
srcfile="C:\\"+host
fv=open(srcfile,'w')
fv.write("Machine NAME : ")
fv.write(host)
fv.write('\n')
fv.write("the machine is joined to the domain : ")
fv.write(str(win32api.GetDomainName()))
fv.write('\n')
fv.write("these settings were logged for user : ")
fv.write(str(win32api.GetUserName()))
fv.write('\n')
fv.write("System Time is : ")
fv.write(str(win32api.GetSystemTime()))
fv.write('\n\n\n')
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
def __init__(self):
global KeyPath
debug("context", "Started CTX with key path: %s" % KeyPath)
self.store = PSSTMessageStore()
self.keystore = Keystore(KeyPath)
self.unseen = Unseen(KeyPath)
self.internal = socket.gethostbyname(socket.gethostname())
# Calculate ID
self.clientID = win32api.GetComputerName().lower() + "." + win32api.GetDomainName().lower()
self.isAdmin = ctypes.windll.shell32.IsUserAnAdmin()
# Get external IP address
try:
# Get External IP Address
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
target = "http://www.icanhazip.com/"
response = opener.open(target).read()
self.external = response.strip()
except Exception as e:
print(str(e))
# Calculate corp and DC
#TODO
def getSoftwareList(self):
try:
hCounter=0
hAttCounter=0
# connecting to the base
hHandle = win32api.RegConnectRegistry(None,win32con.HKEY_LOCAL_MACHINE)
# getting the machine name and domain name
hCompName = win32api.GetComputerName()
hDomainName = win32api.GetDomainName()
# opening the sub key to get the list of Softwares installed
hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,self.CONST_SW_SUBKEY,0,win32con.KEY_ALL_ACCESS)
# get the total no. of sub keys
hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle)
# delete the entire data and insert it again
#deleteMachineSW(hCompName,hDomainName)
# browsing each sub Key which can be Applications installed
while hCounter < hNoOfSubNodes[0]:
hAppName = win32api.RegEnumKey(hHandle,hCounter)
hPath = self.CONST_SW_SUBKEY + "\\" + hAppName
# initialising hAttCounter
hAttCounter = 0
hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,hPath,0,win32con.KEY_ALL_ACCESS)
# [1] will give the no. of attributes in this sub key
hKeyCount = win32api.RegQueryInfoKey(hOpenApp)
hMaxKeyCount = hKeyCount[1]
hSWName = ""
hSWVersion = ""
while hAttCounter < hMaxKeyCount:
hData = win32api.RegEnumValue(hOpenApp,hAttCounter)
if hData[0]== "DisplayName":
hSWName = hData[1]
self.preparefile("SW Name",hSWName)
elif hData[0]== "DisplayVersion":
hSWVersion = hData[1]
self.preparefile("SW Version",hSWVersion)
hAttCounter = hAttCounter + 1
#if (hSWName !=""):
#insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion)
hCounter = hCounter + 1
except:
self.preparefile("Exception","In exception in getSoftwareList")
def LocalGroup(uname=None):
"Creates a local group, adds some members, deletes them, then removes the group"
level = 3
if uname is None: uname=win32api.GetUserName()
if uname.find("\\")<0:
uname = win32api.GetDomainName() + "\\" + uname
group = 'python_test_group'
# delete the group if it already exists
try:
win32net.NetLocalGroupDel(server, group)
print "WARNING: existing local group '%s' has been deleted."
except win32net.error:
pass
group_data = {'name': group}
win32net.NetLocalGroupAdd(server, 1, group_data)
try:
u={'domainandname': uname}
win32net.NetLocalGroupAddMembers(server, group, level, [u])
mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level)
print "members are", mem
if mem[0]['domainandname'] != uname:
print "ERROR: LocalGroup just added %s, but members are %r" % (uname, mem)
# Convert the list of dicts to a list of strings.
win32net.NetLocalGroupDelMembers(server, group, [m['domainandname'] for m in mem])
finally:
win32net.NetLocalGroupDel(server, group)
print "Created a local group, added and removed members, then deleted the group"
def testGetCurrentUser(self):
name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName())
self.failUnless(name == win32api.GetUserNameEx(win32api.NameSamCompatible))
def LocalGroup(uname=None):
"Creates a local group, adds some members, deletes them, then removes the group"
level = 3
if uname is None: uname=win32api.GetUserName()
if uname.find("\\")<0:
uname = win32api.GetDomainName() + "\\" + uname
group = 'python_test_group'
# delete the group if it already exists
try:
win32net.NetLocalGroupDel(server, group)
print("WARNING: existing local group '%s' has been deleted.")
except win32net.error:
pass
group_data = {'name': group}
win32net.NetLocalGroupAdd(server, 1, group_data)
try:
u={'domainandname': uname}
win32net.NetLocalGroupAddMembers(server, group, level, [u])
mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level)
print("members are", mem)
if mem[0]['domainandname'] != uname:
print("ERROR: LocalGroup just added %s, but members are %r" % (uname, mem))
# Convert the list of dicts to a list of strings.
win32net.NetLocalGroupDelMembers(server, group, [m['domainandname'] for m in mem])
finally:
win32net.NetLocalGroupDel(server, group)
print("Created a local group, added and removed members, then deleted the group")
def testGetCurrentUser(self):
name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName())
self.failUnless(name == win32api.GetUserNameEx(win32api.NameSamCompatible))
def getSysInfo(self):
try:
hCounter=0
hProcessorName=""
# connecting to the base
hHandle = win32api.RegConnectRegistry(None,self.HKEY_LOCAL_MACHINE)
# opening the sub key to get the processor name
print "debug1"
hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,self.CONST_PROC_SUBKEY,0,win32con.KEY_ALL_ACCESS)
hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1]
while hCounter < hNoOfKeys:
hData = win32api.RegEnumValue(hHandle,hCounter)
if hData[0]== "Identifier":
hProcessorName = hData[1]
hCounter = hCounter + 1
if hProcessorName=="":
hProcessorName = "Processor Name Cannot be determined"
self.preparefile("Processor Name",hProcessorName)
hCompName = win32api.GetComputerName()
self.preparefile("Computer Name",hCompName)
hDomainName = win32api.GetDomainName()
self.preparefile("Domain Name",hDomainName)
hUserName = win32api.GetUserName()
self.preparefile("User Name",hUserName)
# getting OS Details
hCounter=0
# opening the sub key to get the processor name
hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,self.CONST_OS_SUBKEY,0,win32con.KEY_ALL_ACCESS)
hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1]
hOSVersion=""
hOSName=""
while hCounter < hNoOfKeys:
hData = win32api.RegEnumValue(hHandle,hCounter)
if hData[0]== "ProductName":
hOSName = hData[1]
self.preparefile("OS Name",hOSName)
break
hCounter = hCounter + 1
if hOSName=="":
self.preparefile("OS Name","OS Name could not be read from the registry")
hCounter = 0
while hCounter < hNoOfKeys:
hData = win32api.RegEnumValue(hHandle,hCounter)
if hData[0]== "CSDVersion":
hOSVersion = hData[1]
self.preparefile("OS Version",hOSVersion)
break
hCounter = hCounter + 1
if hOSVersion=="":
self.preparefile("OS Version","OS Version could not be read from the registry")
# inserting master data
#insertMachineMaster(hCompName,hDomainName,hOSName,hOSVersion,hProcessorName)
except:
self.preparefile("Exception","in Exception in getSysDetails")