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')
python类GetUserName()的实例源码
def process_request(self, request, client_address):
# An example using the connection once it is established.
print "The server is running as user", GetUserName()
self.sa.ctxt.ImpersonateSecurityContext()
try:
print "Having conversation with client as user", GetUserName()
while 1:
# we need to grab 2 bits of data - the encrypted data, and the
# 'key'
data = _get_msg(request)
key = _get_msg(request)
if data is None or key is None:
break
data = self.sa.decrypt(data, key)
print "Client sent:", repr(data)
finally:
self.sa.ctxt.RevertSecurityContext()
self.close_request(request)
print "The server is back to user", GetUserName()
def process_request(self, request, client_address):
# An example using the connection once it is established.
print("The server is running as user", GetUserName())
self.sa.ctxt.ImpersonateSecurityContext()
try:
print("Having conversation with client as user", GetUserName())
while 1:
# we need to grab 2 bits of data - the encrypted data, and the
# 'key'
data = _get_msg(request)
key = _get_msg(request)
if data is None or key is None:
break
data = self.sa.decrypt(data, key)
print("Client sent:", repr(data))
finally:
self.sa.ctxt.RevertSecurityContext()
self.close_request(request)
print("The server is back to user", GetUserName())
def get_system_user():
"""Return system user info string, such as USERNAME-EUID"""
try:
info = getpass.getuser()
except ImportError:
if os.name == 'nt':
# when there is no 'USERNAME' in environment, getpass.getuser()
# fail when trying to import 'pwd' module - which is unix only.
# In that case we have to fallback to real win32 API.
import win32api
info = win32api.GetUserName()
else:
raise
euid = getattr(os, 'geteuid', None) # Non available on some platforms
if euid is not None:
info = '%s-%d' % (info, euid())
return info
def add_to_startup(self):
path = "C:\\Users\\" + win32api.GetUserName() + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
if os.path.isfile(path + "Lo0sR.py") == True:
pass
else:
shutil.copy(__file__, path)
def __init__(self):
self.user = win32api.GetUserName() # Username
self.reg_exist = True
def assert_common_fields(self, evt, msg=None, eventID=10, sid=None,
level="Information", extra=None):
assert evt["computer_name"].lower() == win32api.GetComputerName().lower()
assert "record_number" in evt
self.assertDictContainsSubset({
"event_id": eventID,
"level": level,
"log_name": self.providerName,
"source_name": self.applicationName,
"type": self.api,
}, evt)
if msg == None:
assert "message" not in evt
else:
self.assertEquals(evt["message"], msg)
self.assertDictContainsSubset({"event_data.param1": msg}, evt)
if sid == None:
self.assertEquals(evt["user.identifier"], self.get_sid_string())
self.assertEquals(evt["user.name"].lower(),
win32api.GetUserName().lower())
self.assertEquals(evt["user.type"], "User")
assert "user.domain" in evt
else:
self.assertEquals(evt["user.identifier"], sid)
assert "user.name" not in evt
assert "user.type" not in evt
if extra != None:
self.assertDictContainsSubset(extra, evt)
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 GetInfo(userName=None):
"Dumps level 3 information about the current user"
if userName is None: userName=win32api.GetUserName()
print "Dumping level 3 information about user"
info = win32net.NetUserGetInfo(server, userName, 3)
for key, val in info.items():
verbose("%s=%s" % (key,val))
def SetInfo(userName=None):
"Attempts to change the current users comment, then set it back"
if userName is None: userName=win32api.GetUserName()
oldData = win32net.NetUserGetInfo(server, userName, 3)
try:
d = oldData.copy()
d["usr_comment"] = "Test comment"
win32net.NetUserSetInfo(server, userName, 3, d)
new = win32net.NetUserGetInfo(server, userName, 3)['usr_comment']
if str(new) != "Test comment":
raise RuntimeError("Could not read the same comment back - got %s" % new)
print "Changed the data for the user"
finally:
win32net.NetUserSetInfo(server, userName, 3, oldData)
def GetUserName():
try:
return win32api.GetUserName()
except win32api.error, details:
# Seeing 'access denied' errors here for non-local users (presumably
# without permission to login locally). Get the fully-qualified
# username, although a side-effect of these permission-denied errors
# is a lack of Python codecs - so printing the Unicode value fails.
# So just return the repr(), and avoid codecs completely.
return repr(win32api.GetUserNameEx(win32api.NameSamCompatible))
# Send a simple "message" over a socket - send the number of bytes first,
# then the string. Ditto for receive.
def _doAuth(self, pkg_name):
sspiclient=sspi.ClientAuth(pkg_name,targetspn=win32api.GetUserName())
sspiserver=sspi.ServerAuth(pkg_name)
sec_buffer=None
err = 1
while err != 0:
err, sec_buffer = sspiclient.authorize(sec_buffer)
err, sec_buffer = sspiserver.authorize(sec_buffer)
return sspiclient, sspiserver
def testGetUser(self):
self.assertEquals(win32api.GetUserName(), win32wnet.WNetGetUser())
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 GetInfo(userName=None):
"Dumps level 3 information about the current user"
if userName is None: userName=win32api.GetUserName()
print("Dumping level 3 information about user")
info = win32net.NetUserGetInfo(server, userName, 3)
for key, val in list(info.items()):
verbose("%s=%s" % (key,val))
def SetInfo(userName=None):
"Attempts to change the current users comment, then set it back"
if userName is None: userName=win32api.GetUserName()
oldData = win32net.NetUserGetInfo(server, userName, 3)
try:
d = oldData.copy()
d["usr_comment"] = "Test comment"
win32net.NetUserSetInfo(server, userName, 3, d)
new = win32net.NetUserGetInfo(server, userName, 3)['usr_comment']
if str(new) != "Test comment":
raise RuntimeError("Could not read the same comment back - got %s" % new)
print("Changed the data for the user")
finally:
win32net.NetUserSetInfo(server, userName, 3, oldData)
def GetUserName():
try:
return win32api.GetUserName()
except win32api.error as details:
# Seeing 'access denied' errors here for non-local users (presumably
# without permission to login locally). Get the fully-qualified
# username, although a side-effect of these permission-denied errors
# is a lack of Python codecs - so printing the Unicode value fails.
# So just return the repr(), and avoid codecs completely.
return repr(win32api.GetUserNameEx(win32api.NameSamCompatible))
# Send a simple "message" over a socket - send the number of bytes first,
# then the string. Ditto for receive.
def _doAuth(self, pkg_name):
sspiclient=sspi.ClientAuth(pkg_name,targetspn=win32api.GetUserName())
sspiserver=sspi.ServerAuth(pkg_name)
sec_buffer=None
err = 1
while err != 0:
err, sec_buffer = sspiclient.authorize(sec_buffer)
err, sec_buffer = sspiserver.authorize(sec_buffer)
return sspiclient, sspiserver
def testGetUser(self):
self.assertEquals(win32api.GetUserName(), win32wnet.WNetGetUser())
def get_user():
'''
Get the current user
'''
if HAS_PWD:
return pwd.getpwuid(os.geteuid()).pw_name
else:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$' and win32api.GetUserName() == 'SYSTEM':
# Make the system account easier to identify.
user_name = 'SYSTEM'
return user_name
def assert_common_fields(self, evt, msg=None, eventID=10, sid=None,
level="Information", extra=None):
assert evt["computer_name"].lower() == win32api.GetComputerName().lower()
assert "record_number" in evt
self.assertDictContainsSubset({
"event_id": eventID,
"level": level,
"log_name": self.providerName,
"source_name": self.applicationName,
"type": self.api,
}, evt)
if msg == None:
assert "message" not in evt
else:
self.assertEquals(evt["message"], msg)
self.assertDictContainsSubset({"event_data.param1": msg}, evt)
if sid == None:
self.assertEquals(evt["user.identifier"], self.get_sid_string())
self.assertEquals(evt["user.name"].lower(),
win32api.GetUserName().lower())
self.assertEquals(evt["user.type"], "User")
assert "user.domain" in evt
else:
self.assertEquals(evt["user.identifier"], sid)
assert "user.name" not in evt
assert "user.type" not in evt
if extra != None:
self.assertDictContainsSubset(extra, evt)
def get_username():
try:
return getpass.getuser()
except ImportError:
# getpass.getuser() will fail on systems without
# pwd module, so try a common python windows add-on
try:
import win32api
return win32api.GetUserName()
except ImportError:
return None
def userIsAdministrator(self):
'''Verifies if the logged on user has administrative rights'''
if self._userIsAdministrator is not None:
return self._userIsAdministrator
import win32net
import win32netcon
username = win32api.GetUserName()
privileges = win32net.NetUserGetInfo(None, username, 1)
if privileges['priv'] == win32netcon.USER_PRIV_ADMIN:
self._userIsAdministrator = True
else:
self._userIsAdministrator = False
return self._userIsAdministrator
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")