Пример #1
0
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)}
Пример #2
0
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"
Пример #4
0
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>")
Пример #6
0
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}
Пример #7
0
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}
Пример #8
0
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}
Пример #10
0
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}
Пример #11
0
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}
Пример #12
0
 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))
Пример #13
0
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)
Пример #14
0
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}
Пример #15
0
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'
Пример #16
0
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
Пример #17
0
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}
Пример #18
0
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}
Пример #19
0
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('')
Пример #20
0
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}
Пример #22
0
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}
Пример #23
0
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()
Пример #24
0
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)
Пример #25
0
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}
Пример #26
0
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}
Пример #27
0
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)
Пример #28
0
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}
Пример #29
0
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'
    ])
Пример #30
0
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}