def fact(): '''Gets the date of last password change''' password_changed = 'None' # for 10.10+ or non-migrated accounts username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if username: task = subprocess.check_output(['/usr/bin/dscl', '.', 'read', 'Users/' + username, 'accountPolicyData']) plist = plistlib.readPlistFromString('\n'.join(task.split()[1:])) if 'creationTime' in plist.keys(): creation_date = datetime.datetime.utcfromtimestamp(plist['creationTime']).date() if 'passwordLastSetTime' in plist.keys(): password_changed = datetime.datetime.utcfromtimestamp(plist['passwordLastSetTime']).date() else: # for 10.9.x and lower, or migrated accounts task = subprocess.Popen(['/usr/bin/dscl', '.', 'read', 'Users/' + username, 'PasswordPolicyOptions'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = task.communicate() if not err: plist = plistlib.readPlistFromString('\n'.join(out.split()[1:])) if 'passwordLastSetTime' in plist.keys(): password_changed = plist['passwordLastSetTime'].date() return {factoid: str(password_changed)}
def get_local_loggedin_user(): """Return the username of the current logged in user""" global loggedin_username username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] loggedin_username = [username, ""][username in [u"loginwindow", None, u""]] return loggedin_username
def setup_global_variables(): global home_directory global okta_dt_launch_agent_dir global okta_dt_launch_agent global okta_dt_launch_agent_tmp global okta_dt_launch_domain global okta_dt_launch_directory global okta_dt_launch_plist global okta_dt_launch_plist_file global okta_dt_launch_plist_file_tmp global okta_cert_path global current_user global python_path current_user = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] current_user = [current_user, ""][current_user in ["loginwindow", None, "", "root"]] home_directory = get_home_directory() okta_dt_launch_agent_dir = home_directory + '/Library/Okta/' okta_dt_launch_agent = okta_dt_launch_agent_dir + 'okta_device_trust.py' okta_dt_launch_agent_tmp = okta_dt_launch_agent_dir + 'okta_device_trust.py.tmp' okta_dt_launch_domain = 'com.okta.devicetrust' okta_dt_launch_directory = home_directory + '/Library/LaunchAgents/' okta_dt_launch_plist = okta_dt_launch_domain + '.plist' okta_dt_launch_plist_file = okta_dt_launch_directory + okta_dt_launch_plist okta_dt_launch_plist_file_tmp = okta_dt_launch_directory + okta_dt_launch_plist + '.tmp' okta_cert_path = get_home_directory() + '/Library/Keychains/okta.keychain' python_path = get_python_path() if not python_path: python_path = "python3"
def get_console_user(): """Get informatino about the console user Returns: 3-Tuple of (str) username, (int) uid, (int) gid """ return SCDynamicStoreCopyConsoleUser(None, None, None)
def print_data(apps): """function to take a dictionary of 32bit apps and output to a CSV file""" # this code will output to a CSV file on your desktop and list 32bit apps currentuser, uid, gid = SCDynamicStoreCopyConsoleUser(None, None, None) user_home_folder = NSHomeDirectoryForUser(currentuser) file = user_home_folder + '/Desktop/32bitapps.csv' print("<result>") for i in range(len(apps)): print(apps[i].get('name') + " " + apps[i].get('version')) print("</result>")
def fact(): '''Get the current logged in user''' try: username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] username = [username, ""][username in [u"loginwindow", None, u""]] except (IOError, OSError): pass return {'logged_in_user': username}
def fact(): '''Returns the icloud status''' result = 'None' console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = '/Users/%s/Library/Preferences/MobileMeAccounts.plist' % console_user if os.path.exists(plist): d = CFPreferencesCopyAppValue('Accounts', plist) result = d[0]['LoggedIn'] if d else False return {factoid: result}
def getUserLoggedIn(): """ Returns the user logged in. When multiple users are logged in, SCDynamicStoreCopyConsoleUser returns the one using the console. """ from SystemConfiguration import SCDynamicStoreCopyConsoleUser username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] username = [username, ""][username in [u"loginwindow", None, u""]] return username
def fact(): '''Returns the channel name for Office updates''' result = 'None' console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = '/Users/%s/Library/Preferences/com.microsoft.autoupdate2.plist' % console_user if os.path.exists(plist): result = CFPreferencesCopyAppValue('ChannelName', plist) return {factoid: result}
def fact(): """Returns the icloud status""" result = "None" console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = "/Users/%s/Library/Preferences/MobileMeAccounts.plist" % console_user if os.path.exists(plist): d = CFPreferencesCopyAppValue("Accounts", plist) result = d[0]["LoggedIn"] if d else False return {factoid: result}
def fact(): '''Gets the ADSite from the nomad plist''' result = '' username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if username: result = CFPreferencesCopyAppValue('ADSite', '/Users/%s/Library/Preferences/com.trusourcelabs.NoMAD.plist' % username) return {factoid: result}
def result(): # Attempt to get currently logged in person username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] username = [username, ""][username in [u"loginwindow", None, u""]] # If we can't get the current user, get last console login if username == "": username = get_last_user() os.setgid(get_gid(username)) os.setuid(get_uid(username))
def dmg_install(filename, installer, command=None): pipes = subprocess.Popen(["hdiutil", "attach", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print(stdout) print(stderr) exit(1) volume_path = re.search(r'(\/Volumes\/).*$', stdout.decode('utf-8')).group(0) installer_path = "%s/%s" % (volume_path, installer) if command is not None and installer == '': command = command.replace('${volume}', volume_path).encode("utf-8") command = shlex.split(command) pipes = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print(stdout) print(stderr) exit(1) if ".pkg" in installer: pkg_install(installer_path) if ".app" in installer: applications_path = "/Applications/%s" % installer.rsplit('/', 1)[-1] if os.path.exists(applications_path): shutil.rmtree(applications_path) shutil.copytree(installer_path, applications_path) # current_user - the name of the user running the script. Apple suggests using # both methods. # uid - the UID of the user running the script # gid - the GID of the group "admin" which the user account is expected to be a member of # users in macOS current_user = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] current_user = [current_user, ""][current_user in ["loginwindow", None, ""]] uid = pwd.getpwnam(current_user).pw_uid gid = grp.getgrnam("admin").gr_gid os.chown(applications_path, uid, gid) for root, dirs, files in os.walk(applications_path): for d in dirs: os.chown(os.path.join(root, d), uid, gid) for f in files: os.chown(os.path.join(root, f), uid, gid) pipes = subprocess.Popen(["hdiutil", "detach", volume_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print(stdout) print(stderr) exit(1)
def fact(): """Returns the icloud drive status""" result = "None" console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = "/Users/%s/Library/Preferences/MobileMeAccounts.plist" % console_user if os.path.exists(plist): d = CFPreferencesCopyAppValue("Accounts", plist)[0]["Services"][2] if d: result = d.get("Enabled", False) return {factoid: result}
def main(): username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] # username = '******' if username: changed = get_date_changed(username) if changed: today = datetime.datetime.utcnow().date() pw_age = (today - changed).days print pw_age else: print 'Undetermined'
def unloadJob(launcher): launch_plist = os.path.join('/Library', 'LaunchAgents', launcher) cfuser = SCDynamicStoreCopyConsoleUser(None, None, None) if cfuser[0]: os.seteuid(cfuser[1]) print "unloading %s for %s" % (launch_plist, cfuser[0]) try: subprocess.call(['/bin/launchctl', 'unload', launch_plist]) except: pass
def fact(): '''Returns the icloud drive status''' result = 'None' console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = '/Users/%s/Library/Preferences/MobileMeAccounts.plist' % console_user if os.path.exists(plist): d = CFPreferencesCopyAppValue('Accounts', plist)[0]['Services'][2] if d: result = d.get('Enabled', False) return {factoid: result}
def fact(): '''Returns the iCloud disk optimization status''' result = 'None' console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = '/Users/%s/Library/Preferences/com.apple.bird.plist' % console_user if os.path.exists(plist): result = CFPreferencesCopyAppValue('optimize-storage', plist) return {factoid: result}
def import_server_variable(): # python3 compatibility by setting unicode = str import sys if sys.version_info[0] >= 3: unicode = str # getting logged in user global username #import getpass #user = getpass.getuser() # or (see loggedInUser in shell scripts) from SystemConfiguration import SCDynamicStoreCopyConsoleUser import sys username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; username = [username,""][username in [u"loginwindow", None, u""]] #print (username) # defining path to script with server variable from os.path import dirname as up three_up = up(up(up(__file__))) #print (three_up) path = (three_up) + "/_scripts_input_keep/finder_favorites.py" #path = (three_up) + "/_scripts_input_keep/finder_favorites_" + username + ".py" # checking if file exists import os if not os.path.exists(path): print("file " + path + " does not exists, exiting...") quit() # reading server variable def getVarFromFile(filename): import imp f = open(filename) global data data = imp.load_source('data', path) f.close() getVarFromFile(path) print ('') print("severs entry...") print (data.servers) global servers servers = (data.servers) # checking if server variable is defined try: servers except NameError: print("servers is not defined, exiting...") quit() else: print('')
def fact(): """Gets the ADSite from the nomad plist""" result = "" username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if username: result = CFPreferencesCopyAppValue( "ADSite", "/Users/%s/Library/Preferences/com.trusourcelabs.NoMAD.plist" % username, ) return {factoid: result}
def fact(): '''Get the current logged in user''' try: username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] username = [username,""][username in [u"loginwindow", None, u""]] except (IOError, OSError): pass if username == '': return {'isUserLoggedIn': False} else: return {'isUserLoggedIn': True}
def fact(): """Returns the iCloud disk optimization status""" result = "None" console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = "/Users/%s/Library/Preferences/com.apple.bird.plist" % console_user if os.path.exists(plist): result = CFPreferencesCopyAppValue("optimize-storage", plist) return {factoid: result}
def get_console_user(): """Find out who is logged in right now.""" current_os = platform.system() if 'Darwin' in current_os: # macOS: Use SystemConfiguration framework to get the current console user. from SystemConfiguration import SCDynamicStoreCopyConsoleUser cfuser = SCDynamicStoreCopyConsoleUser(None, None, None) return cfuser[0] if 'Windows' in current_os: from win32api import GetUserName return GetUserName() if 'Linux' in current_os: from getpass import getuser return getuser()
def send_installed_uptodate(item_display_name): ''' Notify if item that install was requested for is uptodate, check username again incase user logged out during execution ''' username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] if os.path.exists(NOTIFIER_PATH) and username: # item_name - example: OracleJava8 # item_display_name - example: Oracle Java 8 # item_version - example: 1.8.111.14 notifier_args = ['su', '-l', username, '-c', '"{0}" -sender "{1}" -message "{2}" \ -title "{3}"' .format(NOTIFIER_PATH, NOTIFIER_SENDER_ID, \ NOTIFIER_MSG_UPTODATE % (item_display_name), NOTIFIER_MSG_TITLE,)] # Send notification subprocess.call(notifier_args, close_fds=True)
def fact(): '''Returns whether current console user is an admin''' result = False cmd = ['/usr/bin/dscl', '-plist', '.', 'read', '/Groups/admin'] output = subprocess.check_output(cmd) d = plistlib.readPlistFromString( output)['dsAttrTypeStandard:GroupMembership'] console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if console_user in d: result = True return {factoid: result}
def fact(): """Returns whether current console user is an admin""" result = False cmd = ["/usr/bin/dscl", "-plist", ".", "read", "/Groups/admin"] output = subprocess.check_output(cmd) d = plistlib.readPlistFromString( output)["dsAttrTypeStandard:GroupMembership"] console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if console_user in d: result = True return {factoid: result}
def dmg_install(filename, installer, command=None): pipes = subprocess.Popen(["hdiutil", "attach", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print stdout print stderr exit(1) volume_path = re.search(r'(\/Volumes\/).*$', stdout).group(0) installer_path = "%s/%s" % (volume_path, installer) if command is not None and installer == '': command = command.replace('${volume}', volume_path).encode("utf-8") command = shlex.split(command) pipes = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print stdout print stderr exit(1) if ".pkg" in installer: pkg_install(installer_path) if ".app" in installer: applications_path = "/Applications/%s" % installer.rsplit('/', 1)[-1] if os.path.exists(applications_path): shutil.rmtree(applications_path) shutil.copytree(installer_path, applications_path) # current_user - the name of the user running the script. Apple suggests using # both methods. # uid - the UID of the user running the script # gid - the GID of the group "staff" which is the default primary group for all # users in macOS current_user = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] current_user = [current_user, ""][current_user in [u"loginwindow", None, u""]] uid = pwd.getpwnam(current_user).pw_uid gid = grp.getgrnam("staff").gr_gid os.chown(applications_path, uid, gid) os.chmod(applications_path, 0o755) pipes = subprocess.Popen(["hdiutil", "detach", volume_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipes.communicate() if pipes.returncode == 1: print stdout print stderr exit(1)
def fact(): """Gets the age of last password change""" password_age = None password_changed = False # for 10.10+ or non-migrated accounts username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if username: task = subprocess.check_output([ "/usr/bin/dscl", ".", "read", "Users/" + username, "accountPolicyData" ]) plist = plistlib.readPlistFromString("\n".join(task.split()[1:])) if "passwordLastSetTime" in plist.keys(): password_changed = datetime.datetime.utcfromtimestamp( plist["passwordLastSetTime"]).date() else: # for 10.9.x and lower, or migrated accounts task = subprocess.Popen( [ "/usr/bin/dscl", ".", "read", "Users/" + username, "PasswordPolicyOptions", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) (out, err) = task.communicate() if not err: plist = plistlib.readPlistFromString("\n".join( out.split()[1:])) if "passwordLastSetTime" in plist.keys(): password_changed = plist["passwordLastSetTime"].date() if password_changed: today = datetime.datetime.utcnow().date() password_age = (today - password_changed).days else: password_age = "Undetermined" return {factoid: password_age}
def remove_launch_agent(): # From Graham https://grahamgilbert.com/blog/2017/03/26/loading-launchagents-as-root/ username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0] if username is None: # Exit if there isn't anyone logged in sys.exit() # Get uid for user uid = getpwnam(username).pw_uid # Unload the LaunchAgent subprocess.call([ '/bin/launchctl', 'bootout', 'gui/{}'.format(uid), '/Library/LaunchAgents/com.github.tobiasjwm.boxdrivenotifier.plist' ]) # Remove the LaunchAgent subprocess.call([ '/bin/rm', '-f', '/Library/LaunchAgents/com.github.tobiasjwm.boxdrivenotifier.plist' ])
def fact(): '''Returns the icloud desktop sync status''' result = False console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] plist = '/Users/%s/Library/Preferences/MobileMeAccounts.plist' % console_user if os.path.exists(plist): d = CFPreferencesCopyAppValue('Accounts', plist)[0]['Services'][2] sync_active = d.get('Enabled', False) files = glob.glob( '/Users/%s/Library/Mobile Documents/com~apple~CloudDocs/*' % console_user) if sync_active and files: for f in files: if os.path.islink(f): result = True break return {factoid: result}