コード例 #1
0
def check_for_default_passwords(config_path):
    """
    Check if the 'pi' user current password hash is in our list of default password hashes.
    """
    base_dir = Path(config_path)
    pass_hashes_file_path = base_dir.joinpath(
        'pass_hashes.txt')  # For deb installation.
    if not pass_hashes_file_path.is_file():
        base_dir = Path(__file__).resolve().parent.parent
        pass_hashes_file_path = base_dir.joinpath('misc/pass_hashes.txt')
    with pass_hashes_file_path.open() as f:
        read_data = f.read()

    known_passwords = {}
    for username_password in read_data.splitlines():
        username, password = username_password.split(':', maxsplit=1)
        pw = known_passwords.get(username, [])
        pw.append(password)
        known_passwords[username] = pw

    def hash_matches(pwdp, plaintext_password):
        i = pwdp.rfind('$')
        salt = pwdp[:i]
        crypted = crypt.crypt(plaintext_password, salt)
        return crypted == pwdp

    usernames = set()
    for shadow in spwd.getspall():
        encrypted_password = shadow.sp_pwdp

        for password in known_passwords.get(shadow.sp_namp, []):
            if hash_matches(encrypted_password, password):
                usernames.add(shadow.sp_namp)

    return list(usernames)
コード例 #2
0
def log_no_password_required():
    print("Checking for users that don't require passwords...")
    if is_windows():
        for user in get_users_windows(level=3):
            if user["flags"] & win32netcon.UF_PASSWD_NOTREQD != 0:
                print(
                    "User: {} doesn't require a password to login! (May not be accurate)"
                    .format(user["name"]))
            if user["password_expired"] != 0:
                print(
                    "User: {} has an expired password! (This should be accurate)"
                    .format(user["name"]))
    else:
        try:
            perfect = True
            for user in spwd.getspall():
                password = user.sp_pwd
                while password.startswith("!"):
                    password = password[1:]
                if not password:
                    print("User: {} does not require a password! Bad!".format(
                        user.sp_nam))
                    perfect = False

            if perfect:
                print("All users require passwords! Hurray!")
        except PermissionError:
            print("Unable to view account passwords. Run this script as sudo")

    print()
コード例 #3
0
ファイル: account.py プロジェクト: shidaxi/shiximisc
def account_collect():
    """
    return: [{"uid":xx, 
              "gid": xx, 
              "name": xx,
              "home": xx,
              "groups": xx,
              "shell": xx,
              "fullname": xx,
              "passwd": xx,
              "lstchg": xx,
              "expire": xx,
              "ll_unix_time": xx,
              "ll_device": xx,
              "ll_host": xx}, ]
    """
    accounts = []

    pwds = pwd.getpwall()
    grps = grp.getgrall()
    spwds = spwd.getspall()
    lastlogs = lastlog()

    i_grps = {}
    i_gid = {}
    for g in grps:
        for u in g.gr_mem:
            if u not in i_grps: i_grps[u] = []
            i_grps[u].append(dict(gid=g.gr_gid, group=g.gr_name))

        i_gid[g.gr_gid] = g

    i_spwd = {}
    for sp in spwds:
        i_spwd[sp.sp_nam] = sp

    i_lastlog = {}
    for ll in lastlogs:
        i_lastlog[ll['name']] = ll

    accounts = [ dict(uid=p.pw_uid,
                      gid=p.pw_gid,
                      name=p.pw_name,
                      home=p.pw_dir,
                      groups=i_grps.get(p.pw_name, []),
                      group=i_gid.get(p.pw_gid, None) and i_gid.get(p.pw_gid).gr_name or '',
                      shell=p.pw_shell,
                      fullname=p.pw_gecos,
                      passwd=i_spwd.get(p.pw_name, None) and i_spwd[p.pw_name].sp_pwd or '',
                      lstchg=i_spwd.get(p.pw_name, None) and i_spwd[p.pw_name].sp_lstchg or 0,
                      expire=i_spwd.get(p.pw_name, None) and i_spwd[p.pw_name].sp_expire or 0,
                      ll_unix_time=i_lastlog[p.pw_name]['unix_time'],
                      ll_device=i_lastlog[p.pw_name]['device'],
                      ll_host=i_lastlog[p.pw_name]['host'],
                      ) for p in pwds]
    return accounts
コード例 #4
0
        def __init__(self, anonymous_user=None):
            if os.geteuid() != 0 or not spwd.getspall():
                raise AuthorizerError("super user privileges are required")
            self.anonymous_user = anonymous_user

            if self.anonymous_user is not None:
                try:
                    pwd.getpwnam(self.anonymous_user).pw_dir
                except KeyError:
                    raise AuthorizerError('no such user %s' % anonymous_user)
コード例 #5
0
ファイル: authorizers.py プロジェクト: 070499/service.lan.ftp
        def __init__(self, anonymous_user=None):
            if os.geteuid() != 0 or not spwd.getspall():
                raise AuthorizerError("super user privileges are required")
            self.anonymous_user = anonymous_user

            if self.anonymous_user is not None:
                try:
                    pwd.getpwnam(self.anonymous_user).pw_dir
                except KeyError:
                    raise AuthorizerError('no such user %s' % anonymous_user)
コード例 #6
0
def shadow_list_users():
    """
    Return a list of all shadow users.

    Will be superseded by ``shadow.list_users``, in the salt Oxygen release.

    CLI Example:
    .. code-block:: bash
        salt '*' ash.shadow_list_users
    """
    return sorted([user.sp_nam for user in spwd.getspall()])
コード例 #7
0
def shadow_list_users():
    """
    Return a list of all shadow users.

    Will be superseded by ``shadow.list_users``, in the salt Oxygen release.

    CLI Example:
    .. code-block:: bash
        salt '*' ash.shadow_list_users
    """
    return sorted([user.sp_nam for user in spwd.getspall()])
コード例 #8
0
def io_user_list():
    """
    io_user_list() : iter(User)
    """
    # Read UID_MIN / UID_MAX variables
    (uidmin, uidmax) = _read_uid_minmax()

    # Check if the user is normal (not system user)
    for userinfo in spwd.getspall():
        if _isnormal(userinfo[0], uidmin, uidmax):
            yield User(userinfo[0])
コード例 #9
0
        def __init__(self, anonymous_user=None):
            if os.geteuid() != 0 or not spwd.getspall():
                raise AuthorizerError("super user privileges are required")
            self.anonymous_user = anonymous_user

            if self.anonymous_user is not None:
                if not self.anonymous_user in self._get_system_users():
                    raise ValueError('no such user %s' % self.anonymous_user)
                try:
                    return pwd.getpwnam(self.anonymous_user).pw_dir
                except KeyError:
                    raise ValueError('no such user %s' % username)
コード例 #10
0
ファイル: authorizers.py プロジェクト: iamtio/cwFTP
        def __init__(self, anonymous_user=None):
            if os.geteuid() != 0 or not spwd.getspall():
                raise AuthorizerError("super user privileges are required")
            self.anonymous_user = anonymous_user

            if self.anonymous_user is not None:
                if not self.anonymous_user in self._get_system_users():
                    raise ValueError('no such user %s' % self.anonymous_user)
                try:
                    return pwd.getpwnam(self.anonymous_user).pw_dir
                except KeyError:
                    raise ValueError('no such user %s' % username)
コード例 #11
0
def main():
    if len(sys.argv) != 2 or len(sys.argv) > 2:
        print('Usage: {0} <path/to/dictionary/file>'.format(sys.argv[0]))
        exit(1)
    else:
        words = []
        with open(sys.argv[1], 'r') as f:
            for line in f.readlines():
                words.append(line.strip())
        shadow = spwd.getspall()
        for entry in shadow:
            if entry[1] != '!!' and entry[1] != '*':
                crack(entry[0], entry[1], words)
コード例 #12
0
def list_users():
    '''
    .. versionadded:: Oxygen

    Return a list of all shadow users

    CLI Example:

    .. code-block:: bash

        salt '*' shadow.list_users
    '''
    return sorted([user.sp_nam for user in spwd.getspall()])
コード例 #13
0
ファイル: user.py プロジェクト: duke-cheng/jail
def UserDel_Shadow(User, ShadowFile='/etc/shadow'):
	# 1. temporary shadow file
	fd, TempShadowFile = mkstemp(prefix='shadow', dir='/tmp')

	# 2. generate temporary shadow file
	with fdopen(fd, 'w+') as fh:
		for sp in spwd.getspall():
			if sp.sp_nam != User:
				fh.write(':'.join(map(ShadowItem, sp))+'\n')

	# 3. activate new shadow file
	rename(TempShadowFile, ShadowFile)
	chown(ShadowFile, 0, 0)
	chmod(ShadowFile, 0600)
コード例 #14
0
ファイル: systemsecurity.py プロジェクト: itarozzi/classerman
    def checkCurrentUserPassword(self, password):
        '''
        Check if password entry is correct
        '''
        #uid = os.getuid()
        #name=pwd.getpwuid(uid)[0]

        # Get name of current sudo user 
        name = os.getenv("SUDO_USER")


        
        spwd.getspall()
        user_pwd = spwd.getspnam(name)[1]



        crypt_pwd = crypt.crypt(str(password), user_pwd) 
        

        return crypt_pwd  == user_pwd
    

        
コード例 #15
0
def pwent2dict():

    # suck all three tables into memory

    all_dict = {}

    passwd = pwd.getpwall()
    passwd_dict = {}
    for pwent in passwd:
        pwent4dict = {}
        pwent4dict['pw_name'] = pwent.pw_name
        pwent4dict['pw_passwd'] = pwent.pw_passwd
        pwent4dict['pw_uid'] = pwent.pw_uid
        pwent4dict['pw_gid'] = pwent.pw_gid
        pwent4dict['pw_gecos'] = pwent.pw_gecos
        pwent4dict['pw_dir'] = pwent.pw_dir
        pwent4dict['pw_shell'] = pwent.pw_shell
        passwd_dict[pwent.pw_uid] = pwent4dict
    all_dict['passwd'] = passwd_dict

    groups = grp.getgrall()
    groups_dict = {}
    for grpent in groups:
        grpent4dict = {}
        grpent4dict['gr_name'] = grpent.gr_name
        grpent4dict['gr_passwd'] = grpent.gr_passwd
        grpent4dict['gr_gid'] = grpent.gr_gid
        grpent4dict['gr_mem'] = grpent.gr_mem
        groups_dict[grpent.gr_gid] = grpent4dict
    all_dict['group'] = groups_dict

    shadow = spwd.getspall()
    shadow_dict = {}
    for spent in shadow:
        spent4dict = {}
        spent4dict['sp_nam'] = spent.sp_nam
        spent4dict['sp_pwd'] = spent.sp_pwd
        spent4dict['sp_lstchg'] = spent.sp_lstchg
        spent4dict['sp_min'] = spent.sp_min
        spent4dict['sp_max'] = spent.sp_max
        spent4dict['sp_warn'] = spent.sp_warn
        spent4dict['sp_inact'] = spent.sp_inact
        spent4dict['sp_expire'] = spent.sp_expire
        spent4dict['sp_flag'] = spent.sp_flag
        shadow_dict[spent.sp_nam] = spent4dict
    all_dict['shadow'] = shadow_dict

    return all_dict
コード例 #16
0
    def update_hashes(self):
        if not self.autoupdate:
            return

        hashes = [
            x.sp_pwd for x in getspall() if not x.sp_pwd.startswith(('!', '*'))
        ]

        for h in hashes:
            if h not in self.found:
                self.hashes.add(h)
                for string in self.duplicates:
                    ctext, hash = self.check_hash(h, string)
                    if ctext:
                        self.append((ctext, hash))
                        self.hashes.remove(h)
コード例 #17
0
def get_users_list ():

    """
    This function prints the list of users that are able to login
    into the system. To achieve this, we use the spwd module and its function
    getspall(), which returns a list of each user password database,
    like /etc/shadow file. Then we filter it to print just the users 
    that have a proper password, and not marked with "*" or "!", which means
    they are not suited for login into the system.
    
    """ 
    
    
    user_list = getspall()

    filtered_list =  [user.sp_nam for user in user_list \
                      if user.sp_pwd.find("*") == -1 \
                      and user.sp_pwd.find("!") == -1]

    for x in filtered_list:
        print x
コード例 #18
0
ファイル: libuser.py プロジェクト: enaut/ltsp-manager
    def load(self):
        pwds = pwd.getpwall()
        spwds = spwd.getspall()
        sn = {}
        for s in spwds:
            sn[s.sp_nam] = s

        for p in pwds:
            if p.pw_name in sn:
                s = sn[p.pw_name]
            else:
                s = spwd.struct_spwd([None] * 9)

            gecos = p.pw_gecos.split(',', 4)
            gecos += [''] * (
                5 - len(gecos)
            )  # Pad with empty strings so we have exactly 5 items
            rname, office, wphone, hphone, other = gecos
            u = User(p.pw_name, p.pw_uid, p.pw_gid, rname, office, wphone,
                     hphone, other, p.pw_dir, p.pw_shell,
                     [grp.getgrgid(p.pw_gid).gr_name], s.sp_lstchg, s.sp_min,
                     s.sp_max, s.sp_warn, s.sp_inact, s.sp_expire, s.sp_pwd)
            self.users[u.name] = u

        groups = grp.getgrall()
        for group in groups:
            g = Group(group.gr_name, group.gr_gid)
            for member in group.gr_mem:
                if member in self.users:
                    ugroups = self.users[member].groups
                    if group.gr_name not in ugroups:
                        self.users[member].groups.append(group.gr_name)
                    g.members[member] = self.users[member]

            self.groups[group.gr_name] = g

        for user in self.users.values():
            primary_group = grp.getgrgid(user.gid).gr_name
            if primary_group in self.groups:
                self.groups[primary_group].members[user.name] = user
コード例 #19
0
ファイル: test_users.py プロジェクト: viraptor/reconbf
def test_accounts_nopassword():
    try:
        import spwd
    except ImportError:
        logger.info("Import of spwd failed ")
        return TestResult(Result.SKIP, "Unable to import 'spwd' module")

    disabled = []
    locked = []
    passworded = []
    no_password = []

    shadow_entries = spwd.getspall()

    for entry in shadow_entries:
        # passwords which start with ! have been locked
        if entry.sp_pwd.startswith('!'):
            locked.append(entry.sp_nam)
        # passwords which start with * have been disabled
        elif entry.sp_pwd.startswith('*'):
            disabled.append(entry.sp_nam)
        # blank passwords are bad!
        elif entry.sp_pwd == "":
            no_password.append(entry.sp_nam)
        # otherwise the account has a password
        else:
            passworded.append(entry.sp_nam)

    if len(no_password) > 0:
        notes = "Account(s) { " + str(no_password) + " } have no password!"
        test_result = Result.FAIL
    else:
        notes = ("Disabled: " + str(len(disabled)) + ", Locked: " +
                 str(len(locked)) + ", Password: "******", No Password: " + str(len(no_password)))
        test_result = Result.PASS

    return TestResult(test_result, notes)
コード例 #20
0
ファイル: test_users.py プロジェクト: fallenpegasus/reconbf
def test_accounts_nopassword():
    try:
        import spwd
    except ImportError:
        logger.info("Import of spwd failed ")
        return TestResult(Result.SKIP, "Unable to import 'spwd' module")

    disabled = []
    locked = []
    passworded = []
    no_password = []

    shadow_entries = spwd.getspall()

    for entry in shadow_entries:
        # passwords which start with ! have been locked
        if entry.sp_pwd.startswith('!'):
            locked.append(entry.sp_nam)
        # passwords which start with * have been disabled
        elif entry.sp_pwd.startswith('*'):
            disabled.append(entry.sp_nam)
        # blank passwords are bad!
        elif entry.sp_pwd == "":
            no_password.append(entry.sp_nam)
        # otherwise the account has a password
        else:
            passworded.append(entry.sp_nam)

    if len(no_password) > 0:
        notes = "Account(s) { " + str(no_password) + " } have no password!"
        test_result = Result.FAIL
    else:
        notes = ("Disabled: " + str(len(disabled)) + ", Locked: " +
                 str(len(locked)) + ", Password: "******", No Password: " + str(len(no_password)))
        test_result = Result.PASS

    return TestResult(test_result, notes)
コード例 #21
0
ファイル: iam_acctmgr.py プロジェクト: Demeterr/iam_acctmgr
def service():
    'Poll IAM and update all necessary system configuration files.'
    logging.basicConfig(level=logging.INFO)

    iam_group = IAM_GROUP
    if len(sys.argv) > 1:
        iam_group = sys.argv[1]
    assert iam_group is not None, 'IAM_ACCTMGR_GROUP env variable is not set'

    prior = None
    while True:
        try:
            pwall, spwall = pwd.getpwall(), spwd.getspall()
            system_names = set(
                user.pw_name for user in pwall if not is_iam_user(user))
            user_pks = filter_keys(fetch_keys(iam_group), system_names)
            if prior == user_pks:
                # No change - short circuit
                time.sleep(IAM_POLLING_INTERVAL)
                continue
            else:
                prior = user_pks
            LOG.info('Processing user accounts: %s', user_pks)

            extra_passwd, extra_shadow, extra_sudo = process(
                user_pks, pwall, spwall)

            write(extra_passwd, EXTRAUSERS_PASSWD)
            write(extra_shadow, EXTRAUSERS_SHADOW, '0600')
            write(extra_sudo, SUDOERS_CONFIG, '0400')

            with open(IAM_PUB_KEY_FILE, 'w') as keyfd:
                json.dump(user_pks, keyfd)
        # pylint: disable=broad-except
        except Exception:
            LOG.error(traceback.format_exc())
        # pylint: enable=broad-except
        time.sleep(IAM_POLLING_INTERVAL)
コード例 #22
0
ファイル: iam_acctmgr.py プロジェクト: Demeterr/iam_acctmgr
def service():
    'Poll IAM and update all necessary system configuration files.'
    logging.basicConfig(level=logging.INFO)

    iam_group = IAM_GROUP
    if len(sys.argv) > 1:
        iam_group = sys.argv[1]
    assert iam_group is not None, 'IAM_ACCTMGR_GROUP env variable is not set'

    prior = None
    while True:
        try:
            pwall, spwall = pwd.getpwall(), spwd.getspall()
            system_names = set(user.pw_name for user in pwall
                               if not is_iam_user(user))
            user_pks = filter_keys(fetch_keys(iam_group), system_names)
            if prior == user_pks:
                # No change - short circuit
                time.sleep(IAM_POLLING_INTERVAL)
                continue
            else:
                prior = user_pks
            LOG.info('Processing user accounts: %s', user_pks)

            extra_passwd, extra_shadow, extra_sudo = process(
                user_pks, pwall, spwall)

            write(extra_passwd, EXTRAUSERS_PASSWD)
            write(extra_shadow, EXTRAUSERS_SHADOW, '0600')
            write(extra_sudo, SUDOERS_CONFIG, '0400')

            with open(IAM_PUB_KEY_FILE, 'w') as keyfd:
                json.dump(user_pks, keyfd)
        # pylint: disable=broad-except
        except Exception:
            LOG.error(traceback.format_exc())
        # pylint: enable=broad-except
        time.sleep(IAM_POLLING_INTERVAL)
コード例 #23
0
ファイル: users_module.py プロジェクト: tnlk/PyAuditingTool
		def get_policy_usergroups(self):
				#initialize lists
				users = []
				groups = []
				#get password & groups 
				users_db = spwd.getspall() 
				group_db = grp.getgrall()
				#print users_db, group_db
				try:
						#check passwd policiy foreach user
						for entry in users_db:
								username = entry[0]
								self.separator()
								print colored('[CMD] Executing: chage -l  ' + username , self.calert, attrs=['dark']) 
								os.system('chage -l  ' + username + '> tmp_password_policy.txt')
								os.system('cat tmp_password_policy.txt')
								# self.save_data(self.report_name, os.system('cat tmp_password_policy.txt'))
								#TO-DO: set recommendations 


				except:
						print "There was a problem running the script."
						return ''       
コード例 #24
0
def read_users_from_passwd(dirname="/etc"):
    """
    Reads users from /etc/passwd, /etc/shadow (if it has access) and /etc/group
    """
    pwds = pwd.getpwall()
    spwds = spwd.getspall()
    sn = {}
    for s in spwds:
        sn[s.sp_nam] = s
    users = {}

    for p in pwds:
        if p.pw_uid >= UID_MIN and p.pw_uid <= UID_MAX:
            if p.pw_name in sn:
                s = sn[p.pw_name]
            else:
                #print " * I couldn't find user %s in shadow file. Are you \
                #root?" % p.pw_name
                s = spwd.struct_spwd(["", "x", "", "", "", "", "", "", ""])
            rname, office, wphone, hphone = (p.pw_gecos + ",,,").split(",")[:4]
            u = User(p.pw_name, p.pw_uid, rname, office, wphone, hphone,
                     p.pw_dir, p.pw_shell, [], s.sp_min, s.sp_max, s.sp_warn,
                     s.sp_inact, s.sp_expire, s.sp_pwd, "")
            if u.inact == -1:
                u.inact = ''
            if u.expire == -1:
                u.expire = ''
            users[u.name] = u

    grps = grp.getgrall()
    for g in grps:
        for gu in g.gr_mem:
            if gu in users:
                users[gu].groups.append(g.gr_name)

    return sorted_users(users)
コード例 #25
0
    def __init__(self):
        gladefile = os.path.join(dirs.SHARED_DIR, 'timekpr.glade')
        self.wTree = gtk.glade.XML(gladefile, 'mainwindow', common.domain)

        self.get_limit_spin()
        self.get_from_spin()
        self.get_to_spin()
        self.get_labels()

        self.singleLimits = self.wTree.get_widget("singleLimits")
        self.singleBoundaries = self.wTree.get_widget("singleBoundaries")
        self.limitCheck = self.wTree.get_widget("limitCheck")
        self.boundariesCheck = self.wTree.get_widget("boundariesCheck")
        self.userSelect = self.wTree.get_widget("userSelect")
        self.rewardSpin = self.wTree.get_widget("rewardSpin")
        self.labelrewardspin = self.wTree.get_widget("labelrewardspin")
        self.labeluserstatus = self.wTree.get_widget("labeluserstatus")

        self.limiticon = self.wTree.get_widget("imagelimited1")
        self.boundariesicon = self.wTree.get_widget("imagelimited2")
        self.alldayloginicon = self.wTree.get_widget("imagealldaylogin")
        self.lockedicon = self.wTree.get_widget("imagelocked")
        self.timeleftlabel = self.wTree.get_widget("timeleftlabel")

        self.extendLimitsButton = self.wTree.get_widget("extendLimitsButton")
        self.rewardButton = self.wTree.get_widget("rewardButton")
        self.clearallButton = self.wTree.get_widget("ClearAllRestrictionsButton")
        self.resettimeButton = self.wTree.get_widget("ResetTimeButton")
        self.lockLabel = self.wTree.get_widget("labelunlockbutton")

        self.statusbar = self.wTree.get_widget("statusbar")
        self.statusbarCID = self.statusbar.get_context_id("timekprstatus")

        self.limits = []

        dic = {
            "on_limitCheck_toggled": self.limitCheck_toggled,
            "on_boundariesCheck_toggled": self.boundariesCheck_toggled,
            "on_rewardButton_clicked": self.rewardButton_clicked,
            "on_extendLimitsButton_clicked": self.extendLimitsButton_clicked,
            "on_ClearAllRestrictionsButton_clicked": self.clearallrestrictions,
            "on_ResetTimeButton_clicked": self.resettimefile,
            "on_UnlockButton_clicked": self.lockunlockaccount,
            "on_apply_clicked": self.apply_clicked,
            "on_singleBoundaries_toggled": self.singleBoundariesCheck_toggled,
            "on_singleLimits_toggled": self.singleLimitsCheck_toggled,
            "on_userSelect_toggled": self.read_settings,
            "on_refresh_clicked": self.refreshButton_clicked,
            "on_cancel_clicked": self.cancel_clicked,
            "on_aboutmenuitem_select": self.showaboutdialog,
            'gtk_main_quit': gtk.main_quit
        }
        self.wTree.signal_autoconnect(dic)

        # Read UID_MIN / UID_MAX variables
        (uidmin, uidmax) = read_uid_minmax()
        # Check if the user is normal (not system user)
        for userinfo in spwd.getspall():
            if isnormal(userinfo[0], uidmin, uidmax):
                self.userSelect.append_text(userinfo[0])
                self.userSelect.set_active(0)

        # Ensure we have at least one available normal user
        if self.userSelect.get_active_text() is None:
            dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("You need to have at least one normal user available to configure timekpr"))
            dlg.set_default_response(gtk.RESPONSE_CLOSE)
            dlg.run()
            dlg.destroy()
            exit("Error: You need to have at least one normal user available to configure timekpr")

        self.read_settings(self)
        return
コード例 #26
0
ファイル: local.py プロジェクト: mitchellrj/yaybu
 def getspall(self):
     return list(spwd.getspall())
コード例 #27
0
ファイル: iam_acctmgr.py プロジェクト: bruj0/iam_acctmgr
def service():
    'Poll IAM and update all necessary system configuration files.'
    logging.basicConfig(level=logging.INFO)

    iam_group = IAM_GROUP
    if len(sys.argv) > 1:
        iam_group = sys.argv[1]
    assert iam_group is not None, 'sudo group not set'

    if len(sys.argv) >= 2:
        iam_group_ro = sys.argv[2]
    assert iam_group_ro is not None, 'RO group not set'

    prior = None
    prior_ro = None
    changed = False
    while True:
        pwall, spwall, grpall = pwd.getpwall(), spwd.getspall(), grp.getgrall()
        system_names = set(user.pw_name for user in pwall
                           if not is_iam_user(user))

        try:
            user_pks, user_ids = fetch_keys(iam_group)
            user_pks = filter_keys(user_pks, system_names)
            if prior != user_pks:
                LOG.info('SUDO GROUP Processing user accounts: %s', user_pks)
                extra_passwd, extra_shadow, extra_sudo, extra_group = process(
                    user_pks, pwall, spwall, grpall, True, user_ids)
                prior = user_pks
                changed = True
        # pylint: disable=broad-except
        except Exception:
            LOG.error(traceback.format_exc())


# sync second RO group
        try:
            user_pks_ro, user_ids = fetch_keys(iam_group_ro)
            user_pks_ro = filter_keys(user_pks_ro, system_names)
            if prior_ro != user_pks_ro:
                LOG.info('RO GROUP Processing user accounts: %s', user_pks_ro)
                extra_passwd_ro, extra_shadow_ro, _, extra_group_ro = process(
                    user_pks_ro, pwall, spwall, grpall, False, user_ids)
                LOG.info('SUDO GROUP : %s', extra_passwd)
                LOG.info('RO GROUP : %s', extra_passwd_ro)
                prior_ro = user_pks_ro
                changed = True

        # pylint: disable=broad-except
        except Exception:
            LOG.error(traceback.format_exc())

        if changed is True:
            with open(IAM_PUB_KEY_FILE, 'w') as keyfd:
                json.dump(dict(user_pks.items() + user_pks_ro.items()), keyfd)
            full_passwd = extra_passwd + extra_passwd_ro
            full_shadow = extra_shadow + extra_shadow_ro
            full_group = extra_group + extra_group_ro
            LOG.info('passwd : %s', full_passwd)
            LOG.info('shadow : %s', full_shadow)
            LOG.info('group : %s', full_group)
            write(full_passwd, EXTRAUSERS_PASSWD)
            write(full_shadow, EXTRAUSERS_SHADOW, '0600')
            write(extra_sudo, SUDOERS_CONFIG, '0400')
            write(full_group, '/var/lib/extrausers/group')
            changed = False

        # pylint: enable=broad-except
        LOG.info("Sleeping for 2")
        time.sleep(IAM_POLLING_INTERVAL)
コード例 #28
0
ファイル: authorizers.py プロジェクト: herasrobert/archive
 def __init__(self):
     if os.geteuid() != 0 or not spwd.getspall():
         raise RuntimeError("root privileges are required")
     DummyAuthorizer.__init__(self)
     self._anon_user = ''
     self._dynamic_home_users = []
コード例 #29
0
import spwd
import argparse

# print(spwd.getspall())
# print(spwd.getspall()[1])

parser = argparse.ArgumentParser(
    description="an useless program for unix shadow password database tutorial"
)
parser.add_argument('-u', '--user-name', action="store_true")
parser.add_argument('-p', '--hash-pw', action="store_true")
parsed = parser.parse_args()

if not (parsed.user_name or parsed.hash_pw):
    for i in spwd.getspall():
        print(i)

elif parsed.user_name and parsed.hash_pw:
    for i in spwd.getspall():
        print(f'user: {i[0]},   hash:{i[1]}')

elif parsed.hash_pw:
    for i in spwd.getspall():
        print(i[1])

else:
    # get login name
    for i in spwd.getspall():
        print(i[0])
コード例 #30
0
ファイル: grouik.py プロジェクト: rtrjl/sametmax
#!/usr/bin/python
# -*- coding:utf-8 -*-
import spwd,csv,urllib,crypt,getpass,pwd,sys
from zipfile import ZipFile
from StringIO import StringIO

try:
    f = open('10k most common.txt', 'r+')
    passwlist = [line.strip() for line in f.readlines()]
    f.closed
except :
    myfile = urllib.urlopen("http://roger.zone42.fr/10k%20most%20common.zip")
    passwdtxt = ZipFile(StringIO(myfile.read()))
    passwlist = [line.strip() for line in  passwdtxt.open("10k most common.txt")]
    passwdtxt.extract("10k most common.txt")

for item in spwd.getspall():
    sys.stdout.write("Processing password for user \""+item.sp_nam+"\" : ")
    sys.stdout.flush()
    if item.sp_pwd == '!' or item.sp_pwd == '*':
        print "no password hash to process."
        continue
    for index,brutepass in enumerate(passwlist):
        if crypt.crypt(brutepass, item.sp_pwd) == item.sp_pwd:
            print "password is \""+brutepass+"\""
            break
        if index == len(passwlist)-1 :
            print "failed to break password"
コード例 #31
0
    def __init__(self):
        gladefile = VAR['TIMEKPRSHARED'] + '/timekpr.glade'
        self.wTree = gtk.glade.XML(gladefile, 'mainwindow', APP_NAME)

        self.get_limit_spin()
        self.get_from_spin()
        self.get_to_spin()
        self.get_labels()

        self.singleLimits = self.wTree.get_widget("singleLimits")
        self.singleBoundaries = self.wTree.get_widget("singleBoundaries")
        self.limitCheck = self.wTree.get_widget("limitCheck")
        self.boundariesCheck = self.wTree.get_widget("boundariesCheck")
        self.userSelect = self.wTree.get_widget("userSelect")
        self.rewardSpin = self.wTree.get_widget("rewardSpin")
        self.labelrewardspin = self.wTree.get_widget("labelrewardspin")
        self.labeluserstatus = self.wTree.get_widget("labeluserstatus")

        self.limiticon = self.wTree.get_widget("imagelimited1")
        self.boundariesicon = self.wTree.get_widget("imagelimited2")
        self.alldayloginicon = self.wTree.get_widget("imagealldaylogin")
        self.lockedicon = self.wTree.get_widget("imagelocked")
        self.timeleftlabel = self.wTree.get_widget("timeleftlabel")

        self.extendLimitsButton = self.wTree.get_widget("extendLimitsButton")
        self.rewardButton = self.wTree.get_widget("rewardButton")
        self.clearallButton = self.wTree.get_widget(
            "ClearAllRestrictionsButton")
        self.resettimeButton = self.wTree.get_widget("ResetTimeButton")
        self.lockLabel = self.wTree.get_widget("labelunlockbutton")

        self.statusbar = self.wTree.get_widget("statusbar")
        self.statusbarCID = self.statusbar.get_context_id("timekprstatus")

        self.limits = []

        dic = {
            "on_limitCheck_toggled": self.limitCheck_toggled,
            "on_boundariesCheck_toggled": self.boundariesCheck_toggled,
            "on_rewardButton_clicked": self.rewardButton_clicked,
            "on_extendLimitsButton_clicked": self.extendLimitsButton_clicked,
            "on_ClearAllRestrictionsButton_clicked": self.clearallrestrictions,
            "on_ResetTimeButton_clicked": self.resettimefile,
            "on_UnlockButton_clicked": self.lockunlockaccount,
            "on_apply_clicked": self.apply_clicked,
            "on_singleBoundaries_toggled": self.singleBoundariesCheck_toggled,
            "on_singleLimits_toggled": self.singleLimitsCheck_toggled,
            "on_userSelect_toggled": self.read_settings,
            "on_refresh_clicked": self.refreshButton_clicked,
            "on_cancel_clicked": self.cancel_clicked,
            "on_aboutmenuitem_select": self.showaboutdialog,
            'gtk_main_quit': gtk.main_quit
        }
        self.wTree.signal_autoconnect(dic)

        #Using /etc/shadow spwd module
        for userinfo in getspall():
            if isnormal(userinfo[0]):
                self.userSelect.append_text(userinfo[0])
                self.userSelect.set_active(0)

        #Ensure we have at least one available normal user
        if self.userSelect.get_active_text() is None:
            dlg = gtk.MessageDialog(
                None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                _("You need to have at least one normal user available to configure timekpr"
                  ))
            dlg.set_default_response(gtk.RESPONSE_CLOSE)
            dlg.run()
            dlg.destroy()
            exit(
                "Error: You need to have at least one normal user available to configure timekpr"
            )

        self.read_settings(self)
        return
コード例 #32
0
ファイル: timekpr_kde.py プロジェクト: simgunz/timekpr
    def __init__(self, component_data, parent):
        KCModule.__init__(self,component_data, parent)
        
        #Loading the UI module
        self.ui = uic.loadUi(unicode("/usr/share/kde4/apps/timekpr-kde/ui/main.ui"))
        self.ui.status = uic.loadUi(unicode("/usr/share/kde4/apps/timekpr-kde/ui/status.ui"))
        self.ui.grant = uic.loadUi(unicode("/usr/share/kde4/apps/timekpr-kde/ui/grant.ui"))
        self.ui.limits = uic.loadUi(unicode("/usr/share/kde4/apps/timekpr-kde/ui/limits.ui"))
        
        #Create the layout using group box 
        #Since the UI is modular it's possible to change this layout for displaying the UI modules in tab, etc
        self.ui.lyStatus = QVBoxLayout(self.ui.gbStatus)
        self.ui.lyStatus.addWidget(self.ui.status)
        self.ui.lyGrant = QVBoxLayout(self.ui.gbGrant)
        self.ui.lyGrant.addWidget(self.ui.grant)
        self.ui.lyLimitBound = QVBoxLayout(self.ui.gbLimitBound)
        self.ui.lyLimitBound.addWidget(self.ui.limits)        
        
        #Code for the tab mode, need to change the main.ui
        #self.ui.statusLayout = QVBoxLayout(self.ui.tab)
        #self.ui.statusLayout.addWidget(self.ui.status)
        #statusSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        #self.ui.statusLayout.addItem(statusSpacer)
        #self.ui.limitsLayout = QVBoxLayout(self.ui.tab_2)
        #self.ui.limitsLayout.addWidget(self.ui.limits)
        #limitsSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        #self.ui.limitsLayout.addItem(limitsSpacer)
        
        self.lyMainLayout = QVBoxLayout(self)
        self.lyMainLayout.addWidget(self.ui)
        
        #Set buttons
        #self.setButtons(KCModule.Apply)
        #self.changed.emit(True)
        
        #Interface initialization
        self.ui.limits.wgLimitConfDay.setEnabled(False)
        self.ui.limits.wgBoundConfDay.setEnabled(False)
        
        self.ui.limits.wgLimitWeek.hide()
        self.ui.limits.wgBoundWeek.hide()
        
        
        ##Timer
        self.minutesLeft = 10
        
        self.timer = QTimer()
        self.timer.setInterval(10000)
        self.timer.start()
        
        #Signal and slots definition
        self.connect(self.ui.limits.ckLimit, SIGNAL('clicked()'), self.enable_limit)
        self.connect(self.ui.limits.ckBound, SIGNAL('clicked()'), self.enable_bound)
        
        self.connect(self.ui.limits.ckLimitDay, SIGNAL('clicked()'), self.show_daily_limit)
        self.connect(self.ui.limits.ckBoundDay, SIGNAL('clicked()'), self.show_daily_bound)
        
        self.connect(self.timer, SIGNAL('timeout()'), self.update_time_left)
        
        self.connect(self.timer, SIGNAL('timeout()'), self.get_limit_spin)
        
        self.connect(self.ui.cbActiveUser, SIGNAL('currentIndexChanged(int)'), self.read_settings)
        
        self.get_limit_spin()
        self.get_from_spin()
        self.get_to_spin()
        
        self.setNeedsAuthorization(True)
        #self.setUseRootOnlyMessage(True)
        #Using /etc/shadow spwd module
        #getspall acquisisce la struct di 8 elementi di tutti gli utenti del sistema
        #il primo elemento rappresenta il nome utente
        for userinfo in getspall():
            if isnormal(userinfo[0]):
                self.ui.cbActiveUser.addItem(userinfo[0])
                self.ui.cbActiveUser.setCurrentIndex(0)  
	
	#Ensure we have at least one available normal user
	if self.ui.cbActiveUser.count() == 0:
	    self.ui.gbStatus.setEnabled(False)
	    self.ui.gbGrant.setEnabled(False)
	    self.ui.gbLimitBound.setEnabled(False)
	
	self.read_settings()
コード例 #33
0
       pts(pseudo-terminal slave)是pty的实现方法,和ptmx(pseudo-terminal master)配合使用实现pty。
"""
import posix

print(posix.environ)

import pwd

print(pwd.getpwuid(0))
print(pwd.getpwnam("root"))
"""
0   pw_name 登录名
1   pw_passwd   密码,可能已经加密
2   pw_uid  用户 ID 数值
3   pw_gid  组 ID 数值
4   pw_gecos    用户名或备注
5   pw_dir  用户主目录
6   pw_shell    用户的命令解释器
"""
print(pwd.getpwall())

import spwd

print(spwd.getspall())
print(spwd.getspnam("root"))

import grp

print(grp.getgrall())
print(grp.getgrnam("root"))
print(grp.getgrgid(1))
コード例 #34
0
ファイル: platform.py プロジェクト: yaybu/fuselage
 def getspall():
     return list(spwd.getspall())
コード例 #35
0
ファイル: locbrute.py プロジェクト: mahdi0011/darkcode
#!/usr/bin/python
#Local account brute forcer.
#(You need to be able to read shadow file)

#http://www.darkc0de.com
#d3hydr8[at]gmail[dot]com

import sys, crypt, spwd
if len(sys.argv) != 3:
	print "\nUsage: ./locbrute.py <user> <wordlist>"
	print "Ex: ./locbrute.py root words.txt\n"
	sys.exit(1)

print "\nAccounts with encrypted passwords:\n"
users = spwd.getspall()
for user in users:
	if user[1] not in ["*","!"]: 
		print user[:2]
try:
	words = open(sys.argv[2], "r").readlines()
except(IOError):
	print "\n[-] Error: Couldn't open wordlist\n"
	sys.exit(1)
print "\n[+] Words Loaded:",len(words)
try:
	passwd = spwd.getspnam(sys.argv[1])[1]
except(KeyError):
	print "\n[-] User not found. Check list above\n"
	sys.exit(1)
print "[+] Cracking:",passwd
for word in words:
コード例 #36
0
ファイル: age-report.py プロジェクト: yrro/age-report
    p = argparse.ArgumentParser ()
    sp = p.add_subparsers ()

    for k, v in action_meta.registry.items ():
        if v is action_meta.action:
            continue
        ap = sp.add_parser (k, help=v.help)
        ap.set_defaults (klass=v)
        v.add_arguments (ap)

    args = p.parse_args ()

    action = args.klass (args)
    today = int (time.time () / 86400)

    for a in spwd.getspall ():
        until_disable = a.sp_expire - today
        until_expire = a.sp_max - today + a.sp_lstchg
        until_warn = until_expire - a.sp_warn
        until_inactive = until_expire + a.sp_inact

        if until_disable <= 0 and a.sp_expire >= 0:
            safe (action.disabled, a)

        elif a.sp_lstchg == 0:
            safe (action.force_expired, a)

        elif until_inactive <= 0:
            safe (action.inactive, a)

        elif until_expire <= 0:
コード例 #37
0
def sys_users(base_dir='/', daemons_dir_no_base='/daemons'):

    pwall = pwd.getpwall()
    spall = spwd.getspall()
    grall = grp.getgrall()

    pwall.sort(key=lambda x: x[2])
    grall.sort(key=lambda x: x[2])
    spall.sort(key=lambda x: x[0])

    pw_file_name = wayround_i2p.utils.path.join(base_dir, 'etc', 'passwd')
    gr_file_name = wayround_i2p.utils.path.join(base_dir, 'etc', 'group')
    sp_file_name = wayround_i2p.utils.path.join(base_dir, 'etc', 'shadow')

    pw_file = open(pw_file_name, 'w')
    gr_file = open(gr_file_name, 'w')
    sp_file = open(sp_file_name, 'w')

    spall_dict = {}
    for i in spall:
        spall_dict[i[0]] = i

    ids = {}

    for i in pwall:
        ids[i[2]] = i

    user_ids = {}

    for i in sorted(list(ids.keys())):
        if i == 0 or i >= 1000:
            user_ids[i] = ids[i]

    print("Writing system users")
    for i in sorted(list(USERS.keys())):
        user_name = USERS[i]

        home_dir = calc_daemon_home_dir(
            base_dir,
            daemons_dir_no_base,
            user_name
            )

        pw_file.write(
            '{}:{}:{}:{}:{}:{}:{}\n'.format(
                user_name,
                'x',
                i,
                i,
                user_name,
                home_dir,
                '/bin/false'
                )
            )

        gr_file.write(
            '{}:{}:{}:{}\n'.format(
                user_name,
                'x',
                i,
                user_name
                )
            )

        sp_file.write(
            '{}:{}:::::::\n'.format(
                user_name,
                '!'
                )
            )

    print("Writing root and normal users:")
    for i in sorted(list(user_ids.keys())):

        user_name = user_ids[i][0]
        home_dir = calc_user_home_dir(base_dir, user_name)

        print("    {}".format(user_name))

        pw_file.write(
            '{}:{}:{}:{}:{}:{}:{}\n'.format(
                user_name,
                'x',
                i,
                i,
                user_name,
                home_dir,
                user_ids[i][-1]
                )
            )

        gr_file.write(
            '{}:{}:{}:{}\n'.format(
                user_name,
                'x',
                i,
                user_name
                )
            )

        if user_name in spall_dict:
            sp_file.write(
                '{}:{}:{}:{}:{}:{}:{}:{}:{}\n'.format(
                    *spall_dict[user_name]
                    )
                )

    pw_file.close()
    gr_file.close()
    sp_file.close()

    for i in sorted(list(USERS.keys())):
        user_name = USERS[i]
        home_dir = calc_daemon_home_dir(
            base_dir,
            daemons_dir_no_base,
            user_name
            )
        personalize_home(home_dir, user_name, i)

    for i in sorted(list(user_ids.keys())):
        user_name = user_ids[i][0]
        home_dir = calc_user_home_dir(base_dir, user_name)
        personalize_home(home_dir, user_name, i)

    return 0
コード例 #38
0
# Si le dictionnaire de passwords n'est pas là, on le télécharge
# via FFOpener().open(PASSWORDS_SOURCE).read(). C'est verbeux, c'est urllib.
# Normalement je ferais ça avec requests. Ensuite on lui donne une interface
# file-like object avec io.BytesIO pour que ZipFile puisse le traiter en mémoire
# sans avoir à le sauvegarder dans un vrai fichier sur le disque, et on
# extrait le ZIP.
if not os.path.isfile(PASSWORDS_LIST):
    ZipFile(io.BytesIO(FFOpener().open(PASSWORDS_SOURCE).read())).extractall()

# On extrait les mots de passe de la liste sous forme de tuple car c'est rapide
# à lire. Un petit rstrip vire les sauts de ligne.
passwords = tuple(l.rstrip() for l in open(PASSWORDS_LIST))

# spwd.getspall() nous évite de parser le fichier shadow à la main.
for entry in spwd.getspall():
    print('Processing password for user "%s": ' % entry.sp_nam, end='')

    # Pas de hash ? On gagne du temps avec 'continue'
    if not '$' in entry.sp_pwd:
        print('no password hash to process.')
        continue

    # On teste chaque password avec la fonction crypt, qui accepte en deuxième
    # paramètre le hash du mot de passe complet. Pas besoin de se faire chier
    # à le spliter, il va analyser les '$' et se démerder avec ça. On a juste
    # à comparer le résultat avec le hash d'origine.
    for pwd in passwords:
        if crypt.crypt(pwd, entry.sp_pwd) == entry.sp_pwd:
            print('password is "%s".' % pwd)
            # On break pour gagner quelques tours de boucles, et pouvoir
コード例 #39
0
# Si le dictionnaire de passwords n'est pas là, on le télécharge
# via FFOpener().open(PASSWORDS_SOURCE).read(). C'est verbeux, c'est urllib.
# Normalement je ferais ça avec requests. Ensuite on lui donne une interface
# file-like object avec io.BytesIO pour que ZipFile puisse le traiter en mémoire
# sans avoir à le sauvegarder dans un vrai fichier sur le disque, et on
# extrait le ZIP.
if not os.path.isfile(PASSWORDS_LIST):
    ZipFile(io.BytesIO(FFOpener().open(PASSWORDS_SOURCE).read())).extractall()

# On extrait les mots de passe de la liste sous forme de tuple car c'est rapide
# à lire. Un petit rstrip vire les sauts de ligne.
passwords = tuple(l.rstrip() for l in open(PASSWORDS_LIST))

# spwd.getspall() nous évite de parser le fichier shadow à la main.
for entry in spwd.getspall():
    print('Processing password for user "%s": ' % entry.sp_nam, end='')

    # Pas de hash ? On gagne du temps avec 'continue'
    if not '$' in entry.sp_pwd:
        print('no password hash to process.')
        continue

    # On teste chaque password avec la fonction crypt, qui accepte en deuxième
    # paramètre le hash du mot de passe complet. Pas besoin de se faire chier
    # à le spliter, il va analyser les '$' et se démerder avec ça. On a juste
    # à comparer le résultat avec le hash d'origine.
    for pwd in passwords:
        if crypt.crypt(pwd, entry.sp_pwd) == entry.sp_pwd:
            print('password is "%s".' % pwd)
            # On break pour gagner quelques tours de boucles, et pouvoir
コード例 #40
0
ファイル: shadow.py プロジェクト: bertrandvidal/stuff
    with open(ZIP_FILE, "wb") as temp_zip:
      temp_zip.write(urllib2.urlopen(req).read())
    # Extract the zip file in the current dir
    with ZipFile(ZIP_FILE) as zip_file:
      zip_file.extractall()
  finally:
    # Remove the zip file
    if os.path.exists(ZIP_FILE):
      os.unlink(ZIP_FILE)

# Read the password from the downloaded file
with open(PASSWORDS_FILE, "r") as password_file:
  passwords = map(lambda x: x.strip(), password_file.readlines())

# Get entries from shadow password database
shadow_entries = [entry[:2] for entry in spwd.getspall()]

# We probably need the root access
if not shadow_entries:
  print "Can't access shadow password database - probably need root access"
  sys.exit(1)

for name, encrypted in shadow_entries:
  print "Processing password for user '%s':" % name,
  # This indicate that the user has no password
  if encrypted in ["*", "!"]:
    print "no hash to process"
    continue
  for password in passwords:
    # We use the encrypted version of the password as salt as adviced by
    # the crypt module's doc
コード例 #41
0
    def __init__(self):
        ui_file = join(VAR['TIMEKPRSHARED'], 'main_window.ui')

        self.builder = Gtk.Builder()
        self.builder.add_from_file(ui_file)

        #connect signals to python methods
        self.builder.connect_signals(self)

        #connect gtk objects to python variables
        for obj in self.builder.get_objects():
            if issubclass(type(obj), Gtk.Buildable):
                name = Gtk.Buildable.get_name(obj)
                setattr(self, name, obj)

        self.mainwindow.set_title(_('Timekpr Control Panel'))

        #create lists of limit and boundary gtk objects
        self.limitSpins = [
            self.builder.get_object("limitSpin" + str(x)) for x in range(7)
        ]
        self.fromSpins = [
            self.builder.get_object("fromSpin" + str(x)) for x in range(7)
        ]
        self.toSpins = [
            self.builder.get_object("toSpin" + str(x)) for x in range(7)
        ]
        self.boundariesLabels = [
            self.builder.get_object("boundariesLabel" + str(x))
            for x in range(7)
        ]
        self.limitLabels = [
            self.builder.get_object("limitLabel" + str(x)) for x in range(7)
        ]

        self.statusbarCID = self.statusbar.get_context_id("timekprstatus")

        self.limits = []

        #Using /etc/shadow spwd module
        for userinfo in getspall():
            if is_regular_user(userinfo[0]):
                self.userSelectCombo.append_text(userinfo[0])
                self.userSelectCombo.set_active(0)

        #Ensure we have at least one available normal user
        if self.userSelectCombo.get_active_text() is None:
            dlg = Gtk.MessageDialog(
                None, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE,
                _("You need to have at least one normal user available to configure timekpr"
                  ))
            dlg.set_default_response(Gtk.ResponseType.CLOSE)
            dlg.run()
            dlg.destroy()
            exit(
                "Error: You need to have at least one normal user available to configure timekpr"
            )

        self.on_userSelectCombo_toggled(self)

        return
コード例 #42
0
    resetdate = "chage -E -1 %s >/dev/null 2>&1" % (user)
    os.system(lockuser)
    os.system(resetdate)
    status = "Locked"
    return status


#--- End Functions------

#--- Global Variables ---
# Here I am duping the contents of each file into a variable
# that can be indexed. Not that is is needed since each struc
# provides a call to a particular value
#------------------------
all_user_data = pwd.getpwall()
all_user_pass = spwd.getspall()
# Since by defaul the UID of a user account is between 1000 and
# 59999. I will set them up as static variables
FIRST_UID = 1000
LAST_UID = 59999
TODAY = dt.datetime.fromtimestamp(int(t.time())).strftime('%Y-%m-%d %H:%M:%S')
LOGFILE = sys.argv[1]

#---Open the logfile------

sys.stdout = open(LOGFILE, "w+")

# Using the operator module I was able the sort out the
# UID of the users. This was after I determined which accounts
# where user accounts.
users = sorted(
コード例 #43
0
ファイル: passext.py プロジェクト: mahdi0011/darkcode
#!/usr/bin/python
#(2 ways)Saves highlighting & delete time by printing out
#just the users on a system.
#d3hydr8[at]gmail[dot]com

import sys
if len(sys.argv) != 2:
    print "Usage: ./passext.py </etc/passwd file>"
    sys.exit(1)

pwfile = sys.argv[1]
try:
    pws = open(pwfile, "r")
except (IOError):
    print "Error: Check your file path\n"
    sys.exit(1)
pws = pws.readlines()
print "\n1st Way:\n"
for i in pws:
    print i.split(':', 1)[0]
print "\n2nd Way:\n"
try:
    import spwd
except (ImportError):
    print "Missing spwd module the comes with py2.5\n"
    sys.exit(1)
lst = spwd.getspall()
for user in lst:
    print user[0]
コード例 #44
0
ファイル: passext.py プロジェクト: brock7/scripts
#!/usr/bin/python
#(2 ways)Saves highlighting & delete time by printing out 
#just the users on a system.
#d3hydr8[at]gmail[dot]com 

import sys 
if len(sys.argv) != 2:
	print "Usage: ./passext.py </etc/passwd file>"
	sys.exit(1)

pwfile = sys.argv[1]
try:
  pws = open(pwfile, "r")
except(IOError): 
  print "Error: Check your file path\n"
  sys.exit(1)
pws = pws.readlines()
print "\n1st Way:\n"
for i in pws:
	print i.split(':',1)[0]
print "\n2nd Way:\n"
try:
	import spwd
except(ImportError):
	print "Missing spwd module the comes with py2.5\n"
	sys.exit(1)
lst = spwd.getspall()
for user in lst: print user[0]