def testDsCrackNamesSyntax(self): # Do a syntax check only - that allows us to avoid binding. # But must use DS_CANONICAL_NAME (or _EX) expected = win32api.GetUserNameEx(win32api.NameCanonical) fmt_offered = ntsecuritycon.DS_FQDN_1779_NAME name = win32api.GetUserNameEx(fmt_offered) result = win32security.DsCrackNames( None, ntsecuritycon.DS_NAME_FLAG_SYNTACTICAL_ONLY, fmt_offered, ntsecuritycon.DS_CANONICAL_NAME, (name, )) self.failUnlessEqual(expected, result[0][2])
def win32_restrict_file_to_user(fname): """Secure a windows file to read-only access for the user. Follows guidance from win32 library creator: http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html This method should be executed against an already generated file which has no secrets written to it yet. Parameters ---------- fname : unicode The path to the file to secure """ import win32api import win32security import ntsecuritycon as con # everyone, _domain, _type = win32security.LookupAccountName("", "Everyone") admins = win32security.CreateWellKnownSid(win32security.WinBuiltinAdministratorsSid) user, _domain, _type = win32security.LookupAccountName("", win32api.GetUserNameEx(win32api.NameSamCompatible)) sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION) dacl = win32security.ACL() # dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, everyone) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins) sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION, sd)
def NameSamCompatible(): """ Retrieves the domain/username of the current user. :rtype: str """ return win32api.GetUserNameEx(win32api.NameSamCompatible)
def get_current_user(): ''' Gets the user executing the process Returns: str: The user name ''' try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$': # Make the system account easier to identify. # Fetch sid so as to handle other language than english test_user = win32api.GetUserName() if test_user == 'SYSTEM': user_name = 'SYSTEM' elif get_sid_from_name(test_user) == 'S-1-5-18': user_name = 'SYSTEM' except pywintypes.error as exc: raise CommandExecutionError( 'Failed to get current user: {0}'.format(exc[2])) if not user_name: return False return user_name
def testDsCrackNames(self): h = win32security.DsBind() fmt_offered = ntsecuritycon.DS_FQDN_1779_NAME name = win32api.GetUserNameEx(fmt_offered) result = win32security.DsCrackNames(h, 0, fmt_offered, fmt_offered, (name, )) self.failUnlessEqual(name, result[0][2])
def check_data_path_permissions(): """ Checks if the current user is owner of C:\ProgramData\FAForever Fixes the permissions in case that FAF was run as different user before """ if sys.platform == 'win32' and (not 'CI' in os.environ): data_path = Settings.get('client/data_path') if os.path.exists(data_path): try: my_user = win32api.GetUserNameEx(win32con.NameSamCompatible) sd = win32security.GetFileSecurity( data_path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, type = win32security.LookupAccountSid( None, owner_sid) data_path_owner = "%s\\%s" % (domain, name) if my_user != data_path_owner: set_data_path_permissions() except Exception as e: # we encountered error 1332 in win32security.LookupAccountSid here: http://forums.faforever.com/viewtopic.php?f=3&t=13728 # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379166(v=vs.85).aspx states: # "It also occurs for SIDs that have no corresponding account name, such as a logon SID that identifies a logon session." # so let's just fix permissions on every exception for now and wait for someone stuck in a permission-loop win32api.MessageBox( 0, "FA Forever ran into an exception checking the data folder permissions: '{}'\n" "If you get this popup more than one time, please report a screenshot of this popup to tech support forum. " "Full stacktrace:\n{}".format(e, traceback.format_exc()), "Permission check exception") set_data_path_permissions()
def testGetCurrentUser(self): domain = win32api.GetDomainName() if domain == "NT AUTHORITY": # Running as a service account, so the comparison will fail raise TestSkipped("running as service account") name = "%s\\%s" % (domain, win32api.GetUserName()) self.assertEquals(name, win32api.GetUserNameEx(win32api.NameSamCompatible))
def get_user_pySID_object(): # get current user's name username = win32api.GetUserNameEx(win32con.NameSamCompatible) # pySID object for the current user user, _, _ = win32security.LookupAccountName("", username) return user
def check_permissions(path, logger): logger.info("I am", win32api.GetUserNameEx(win32con.NameSamCompatible)) logger.info(path) sd = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, _ = win32security.LookupAccountSid(None, owner_sid) logger.info("File owned by %s\\%s" % (domain, name))
def get_current_user(with_domain=True): ''' Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name ''' try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$': # Make the system account easier to identify. # Fetch sid so as to handle other language than english test_user = win32api.GetUserName() if test_user == 'SYSTEM': user_name = 'SYSTEM' elif get_sid_from_name(test_user) == 'S-1-5-18': user_name = 'SYSTEM' elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: raise CommandExecutionError( 'Failed to get current user: {0}'.format(exc)) if not user_name: return False return user_name
def test_username(self): name = win32api.GetUserNameEx(win32con.NameSamCompatible) if name.endswith('$'): # When running as a service account (most likely to be # NetworkService), these user name calculations don't produce the # same result, causing the test to fail. raise unittest.SkipTest('running as service account') self.assertEqual(psutil.Process().username(), name)
def get_real_name(): if platform.system() == 'Windows': import win32api real_name = win32api.GetUserNameEx(3) # Comes back in the form "Last, First" real_name_parts = [x.strip() for x in reversed(real_name.split(','))] real_name = ' '.join(real_name_parts) return real_name else: return None
def _get_user_name(): 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))
def loadActiveUser(): user = '' if (HAS_PYAD): try: ad_dn = win32api.GetUserNameEx(win32api.NameFullyQualifiedDN) user = aduser.ADUser.from_dn(ad_dn) except: print( "Unable to connect to AD server, please ask a systems admin for help" ) return user
def _get_current_user(): """ Return the pySID corresponding to the current user. """ account_name = win32api.GetUserNameEx(win32api.NameSamCompatible) # LookupAccountName() expects the system name as first parameter. By passing None to it, # we instruct Windows to first search the matching account in the machine local accounts, # then into the primary domain accounts, if the machine has joined a domain, then finally # into the trusted domains accounts. This is the preferred lookup mechanism to use in Windows # if there is no reason to use a specific lookup mechanism. # See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-lookupaccountnamea return win32security.LookupAccountName(None, account_name)[0]
def checkCredentials(user, passw): domain, username = win32api.GetUserNameEx( win32api.NameSamCompatible).split('\\') if user != username: return 'Wrong credentials. Please try again.' try: lg = win32security.LogonUser(user, domain, passw, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) except: return 'Wrong credentials. Please try again.' else: return 'Success'
def getUserDomain(): """ Gets the Windows domain of the current user """ if "USERDOMAIN" in os.environ: return os.environ["USERDOMAIN"] # returns e.g. KBCFP\username fqun = win32api.GetUserNameEx(win32api.NameSamCompatible) names = fqun.split('\\') if len(names) != 2: raise ValueError( "Invalid user name: %s. Need 2 backslash-separated components (got %d)" % (fqun, len(names))) return names[0]
def sytemUsername(): if os.name == 'posix': import pwd # get the name for the UID for the current process username = pwd.getpwuid(os.getuid())[0] elif os.name == 'nt': # thanks internets -- http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html` import win32api import win32con username = win32api.GetUserNameEx(win32con.NameSamCompatible) else: username = '******' + os.name system_info.write('diag launched by: ' + username)
def get_download_path(): name = win32api.GetUserNameEx(win32api.NameSamCompatible) rename = re.sub(r'\W', " ", name) print(rename) pos = rename.find(' ') print(pos) path2 = 'Downloads' path1 = 'Users' #print (name) #print (name[8:]) user_name = name[pos + 1:] #print ('user name :'+name) full_path = 'C:' + "\\" + path1 + "\\" + user_name + "\\" + path2 print(full_path) return full_path
def set_data_path_permissions(): """ Set the owner of C:\ProgramData\FAForever recursively to the current user """ if not admin.isUserAdmin(): win32api.MessageBox( 0, "FA Forever needs to fix folder permissions due to user change. Please confirm the following two admin prompts.", "User changed") if sys.platform == 'win32' and (not 'CI' in os.environ): data_path = Settings.get('client/data_path') if os.path.exists(data_path): my_user = win32api.GetUserNameEx(win32con.NameSamCompatible) admin.runAsAdmin(["icacls", data_path, "/setowner", my_user, "/T"]) admin.runAsAdmin(["icacls", data_path, "/reset", "/T"])
def is_private(path): """ Return True if `path` is accessible only by 'owner'. path: string Path to file or directory to check. .. note:: On Windows this requires the pywin32 extension. """ if not os.path.exists(path): return True # Nonexistent file is secure ;-) if sys.platform == 'win32': # pragma no cover if not HAVE_PYWIN32: return False # No way to know. # Find the SIDs for user and system. username = win32api.GetUserNameEx(win32con.NameSamCompatible) # Map Cygwin 'root' to 'Administrator'. Typically these are intended # to be identical, but /etc/passwd might configure them differently. if username.endswith('\\root'): username = username.replace('\\root', '\\Administrator') user, domain, type = win32security.LookupAccountName('', username) system, domain, type = win32security.LookupAccountName('', 'System') # Find the DACL part of the Security Descriptor for the file sd = win32security.GetFileSecurity( path, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() if dacl is None: logging.warning('is_private: No DACL for %r', path) return False # Happened on a user's XP system. # Verify the DACL contains just the two entries we expect. count = dacl.GetAceCount() if count != 2: return False for i in range(count): ace = dacl.GetAce(i) if ace[2] != user and ace[2] != system: return False return True else: return (os.stat(path).st_mode & 0077) == 0
def get_download_path(): global full_path name = win.GetUserNameEx(win.NameSamCompatible) rename = re.sub(r'\W', " ", name) #print (rename) pos = rename.find(' ') #print (pos) path2 = 'Downloads' path1 = 'Users' #print (name) #print (name[8:]) user_name = name[pos + 1:] full_path = 'C:' + "\\" + path1 + "\\" + user_name + "\\" + path2 #print (full_path) print(full_path) return full_path, full_path + "\\" + 'WinLink_Report'
def get_current_user(self): """Returns the effective user name running this process. The effective user may not be the same as the initiator of the process if the process has escalated its privileges. @return: The name of the effective user running this process. @rtype: str """ # As a little hack, we pretend anyone that has administrative privilege is running as # the local user 'Administrators' (note the 's'). This will result in us setting the configuration file # to be owned by 'Administrators' which is the right thing to do. if win32com.shell.shell.IsUserAnAdmin(): return self.__local_administrators else: return win32api.GetUserNameEx(win32api.NameSamCompatible)
def GetUserFullName(): ''' Detects full user name from system information. ''' if sys.platform == 'win32': try: return win32api.GetUserNameEx(win32api.NameDisplay) except pywintypes.error: return '' else: import pwd name = pwd.getpwuid(os.getuid())[4] if ',' in name: name = name[:name.index(',')] return name
def findUser(pth): # print "Creater = ", win32api.GetUserNameEx (win32con.NameSamCompatible) thisUserIs = win32api.GetUserNameEx(win32con.NameSamCompatible) thisUserIs = thisUserIs.replace("PROD\\", "") #print "User ID = " + thisUserIs try: sd = win32security.GetFileSecurity( pth, win32security.OWNER_SECURITY_INFORMATION) owner_sid = sd.GetSecurityDescriptorOwner() name, domain, type = win32security.LookupAccountSid(None, owner_sid) except: name = "error getting name " + pth return name
def name(): if win32api is not None: try: name = win32api.GetUserNameEx(win32api.NameDisplay) if name: return name except win32api.error: name = win32api.GetUserName() if name: return name try: name = getpass.getuser() if name: return name except Exception: # FIXME Make specific when it is documented pass return "User"
def test_settable (self): "Check that a writeable property can be written" name = str (time.time ()).split (".")[0] old_value = "***" new_value = "!!!" username = win32api.GetUserNameEx (win32con.NameSamCompatible) self.assert_ (not self.connection.Win32_Environment (Name=name, UserName=username)) self.connection.Win32_Environment.new (Name=name, UserName=username, VariableValue=old_value).put () for envvar in self.connection.Win32_Environment (Name=name, UserName=username): self.assertEqual (envvar.VariableValue, old_value) envvar.VariableValue = new_value try: for envvar in self.connection.Win32_Environment (Name=name, UserName=username): self.assertEqual (envvar.VariableValue, new_value) finally: for envvar in self.connection.Win32_Environment (Name=name, UserName=username): envvar.VariableValue = None
def user_name(): """The name of the current user """ if pwd: # Strip trailing commas seen on Linux return pwd.getpwuid(os.getuid()).pw_gecos.rstrip(',') elif win32api and pywintypes: NameDisplay = 3 try: # Returns Unicode return win32api.GetUserNameEx(NameDisplay) except pywintypes.error: try: return win32api.GetUserName() except pywintypes.error: return '' else: return ''
def current(sam=False): ''' Get the username that salt-minion is running under. If salt-minion is running as a service it should return the Local System account. If salt is running from a command prompt it should return the username that started the command prompt. .. versionadded:: 2015.5.6 :param bool sam: False returns just the username without any domain notation. True returns the domain with the username in the SAM format. Ie: ``domain\\username`` :return: Returns False if the username cannot be returned. Otherwise returns the username. :rtype: bool str CLI Example: .. code-block:: bash salt '*' user.current ''' try: if sam: user_name = win32api.GetUserNameEx(win32con.NameSamCompatible) else: user_name = win32api.GetUserName() except pywintypes.error as exc: (number, context, message) = exc log.error('Failed to get current user') log.error('nbr: {0}'.format(number)) log.error('ctx: {0}'.format(context)) log.error('msg: {0}'.format(message)) return False if not user_name: return False return user_name
def get_current_user(): ''' Gets the user executing the process Returns: str: The user name ''' try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$' and win32api.GetUserName() == 'SYSTEM': # Make the system account easier to identify. user_name = 'SYSTEM' except pywintypes.error as exc: raise CommandExecutionError('Failed to get current user: {0}'.format( exc[2])) if not user_name: return False return user_name