Python win32api 模块,GetUserName() 实例源码

我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用win32api.GetUserName()

项目:code    作者:ActiveState    | 项目源码 | 文件源码
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')
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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()
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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())
项目:addons-fm    作者:Punto0    | 项目源码 | 文件源码
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
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
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)
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def __init__(self):
        self.user = win32api.GetUserName()  # Username
        self.reg_exist = True
项目:amazonbeat    作者:awormuth    | 项目源码 | 文件源码
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)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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"
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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))
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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.
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def testGetUser(self):
        self.assertEquals(win32api.GetUserName(), win32wnet.WNetGetUser())
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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")
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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))
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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.
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def testGetUser(self):
        self.assertEquals(win32api.GetUserName(), win32wnet.WNetGetUser())
项目:jinjabread    作者:Inveracity    | 项目源码 | 文件源码
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
项目:brobeat-OLD    作者:blacktop    | 项目源码 | 文件源码
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)
项目:solaris-ips    作者:oracle    | 项目源码 | 文件源码
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
项目:lib9    作者:Jumpscale    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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")