Example #1
0
 def create_user(self, user, uid):
     """
     Create the user on the system. If the user and the uid doesn't exist, simply create it.
     If the uid is not used, but user exists, modify existing user to set the appropriate uid.
     If the uid is used, but user doesn't exists, rename existing user and create home directory.
     """
     if uid:
         uid_str = " -u " + str(uid) + " "
         # if uid doesn't exist on the system
         if int(uid) not in [x[2] for x in pwd.getpwall()]:
             # if user doesn't exist on the system
             if user not in [y[0] for y in pwd.getpwall()]:
                 cmd="useradd " + user + uid_str + " -m"
                 os.system(cmd)
             else:
                 cmd="usermod " + uid_str + user
                 os.system(cmd)
         else:
             # get username with uid
             for existing_user in pwd.getpwall():
                 if existing_user[2] == int(uid):
                     user_name = existing_user[0]
             cmd="mkdir -p /home/" + user + " && usermod --home /home/" + user + " --login " + user + " " + str(user_name) + " && chown -R " + user + " /home/" + user
             os.system(cmd)
     else:
         if user not in [x[0] for x in pwd.getpwall()]:
             cmd="useradd " + user + " -m"
             os.system(cmd)
         else:
             print("user already exists")
Example #2
0
    def get_users (self):
        """Return the list of users on the system. These should
        be real users - i.e. should not include system users
        like nobody, gdm, nfsnobody etc.
        """
        list = []
        try:
            users = pwd.getpwall()
        except:
            raise UserDatabaseException(_("Failed to get the user list"))

        for user in pwd.getpwall():
            try:
                # remove non-users
                if user[2] < 500:
                    continue
                if user[0] in list:
                    continue
                if user[6] == "" or string.find(user[6], "nologin") != -1:
                    continue
                if user[0][len (user[0]) - 1] == "$":  # Active Directory hosts end in "$"; we don't want to show those as users
                    continue
                list.append(user[0])
            except:
                pass
        return list
Example #3
0
File: user.py Project: tbenz9/tory
def get_users():
    dict = {}
    #find current users and add to the the dictionary
    try:    
        users = psutil.users()

        names = []
        for user in users:
            names.append(user[0])
        dict['current_users'] = names
    except:
        print "Current Users not found"

    #find all users
    try:    
        all_users = []
        for p in pwd.getpwall():
            all_users.append(p[0])
        dict['all_users'] = all_users
    except:
        print "All Users not found"


    #make a dict of the groups of all the users
    try:
        groups = {}
        for p in pwd.getpwall():
            groups[p[0]] = grp.getgrgid(p[3])[0] 
        dict['groups'] = groups
    except:
        print "Groups not found"

    return dict
Example #4
0
    def testGetPasswdMap(self):
        """Verify we build a correct password map from nss calls."""

        foo = ("foo", "x", 10, 10, "foo bar", "/home/foo", "/bin/shell")
        bar = ("bar", "x", 20, 20, "foo bar", "/home/monkeyboy", "/bin/shell")

        self.mox.StubOutWithMock(pwd, "getpwall")
        pwd.getpwall().AndReturn([foo, bar])

        entry1 = passwd.PasswdMapEntry()
        entry1.name = "foo"
        entry1.uid = 10
        entry1.gid = 10
        entry1.gecos = "foo bar"
        entry1.dir = "/home/foo"
        entry1.shell = "/bin/shell"

        entry2 = passwd.PasswdMapEntry()
        entry2.name = "bar"
        entry2.uid = 20
        entry2.gid = 20
        entry2.gecos = "foo bar"
        entry2.dir = "/home/monkeyboy"
        entry2.shell = "/bin/shell"

        self.mox.ReplayAll()

        password_map = nss.GetPasswdMap()

        self.assertTrue(isinstance(password_map, passwd.PasswdMap))
        self.assertEquals(len(password_map), 2)
        self.assertTrue(password_map.Exists(entry1))
        self.assertTrue(password_map.Exists(entry2))
    def test_get_group_list(self):
        user = pwd.getpwall()[0].pw_name
        primary_group = grp.getgrgid(pwd.getpwall()[0].pw_gid).gr_name
        config = {
            "regex": "(?P<account>.*)-(?P<role>.*)"
        }

        provider = Provider(user, config)
        received_groups = provider.get_group_list()
        self.assertIn(primary_group, received_groups)
Example #6
0
def create_user(d_user):
    info("Create domogik user")
    if d_user not in [x[0] for x in pwd.getpwall()]:
        print("Creating the {0} user".format(d_user))
        debug('/usr/sbin/useradd --system {0}'.format(d_user))
        os.system('/usr/sbin/useradd --system {0}'.format(d_user))
        debug('/usr/sbin/usermod -a -G dialout {0}'.format(d_user))
        os.system('/usr/sbin/usermod -a -G dialout {0}'.format(d_user))
    if d_user not in [x[0] for x in pwd.getpwall()]:
        fail("Failed to create domogik user")
    else:
        ok("Correctly created domogik user")
Example #7
0
def create_user(d_user, d_shell = "/bin/sh"):
    if d_user not in [x[0] for x in pwd.getpwall()]:
        print("Creating the {0} user and add it to dialout".format(d_user))
        cmd_line = 'adduser --system {0} --shell {1} '.format(d_user, d_shell)
        debug(cmd_line)
        os.system(cmd_line)
        cmd_line = 'adduser {0} dialout'.format(d_user)
        debug(cmd_line)
        os.system(cmd_line)
    if d_user not in [x[0] for x in pwd.getpwall()]:
        fail("Failed to create domogik-mq user")
    else:
        ok("Correctly created domogik-mq user")
Example #8
0
    def __init__(self, parent):
        self.ParentClass = parent
        self.xml = self.ParentClass.xml
        self.widget = self.xml.get_widget("setuserWindow")
        self.widget.connect("delete-event", self.widget.hide_on_delete)

        ##comboxEntry
        self.entUser = self.xml.get_widget("entUser")

        liststore = gtk.ListStore(gobject.TYPE_STRING)
        self.entUser.set_model(liststore)
        self.entUser.set_text_column(0)

        #entryCompletion
        # TODO: make it only possible for the user to type something that is in the list
        self.entry = self.entUser.child
        self.entry.set_text(self.ParentClass.user)
        completion = gtk.EntryCompletion()
        self.entry.set_completion(completion)
        completion.set_model(liststore)
        completion.set_text_column(0)

        #fill combox with all the users
        pwd_info = pwd.getpwall()

        for info in pwd_info:
            self.entUser.append_text(info[0])
        ##

        self.cancel_button = self.xml.get_widget ("setuser_cancel_button")
        self.ok_button = self.xml.get_widget ("setuser_ok_button")
        self.xml.signal_connect("on_setuser_cancel_button_clicked", self.on_cancel_button_clicked)
        self.xml.signal_connect("on_setuser_ok_button_clicked", self.on_ok_button_clicked)
Example #9
0
    def initUI(self, class_sel):

        # == update system user list ==
        self.userList=pwd.getpwall()
    
        # == populate classed combo ==
        self.lstClasses.clear()
        pos=0
        idx_sel = 0
        
        for i in range(ord('a'), ord('p')+1):
            
            self.lstClasses.addItem("classe_1%s"%chr(i))
            self.lstClasses.addItem("classe_2%s"%chr(i))
            self.lstClasses.addItem("classe_3%s"%chr(i))
            pos=pos+1
            
        # == table properties ==
        self.tableStudents.setColumnCount(2)
        self.tableStudents.setRowCount(0)
        self.tableStudents.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.tableStudents.setHorizontalHeaderLabels(['Nome Completo', 'username'])
        self.tableStudents.setColumnWidth(0,400)
        self.tableStudents.setColumnWidth(1,300)
        self.tableStudents.setSortingEnabled(True)
        
        
        # == update table with last class ==
        if class_sel != '' :
            pos = self.lstClasses.findText(class_sel)
            if pos >= 0 :
                self.lstClasses.setCurrentIndex(pos)
        self.updateTable()
Example #10
0
 def getNewUserID(self):
     newID = 0
     pwds = pwd.getpwall()
     for p in pwds:
         if (p.pw_uid >= 500 and p.pw_uid <= 1500) and p.pw_uid > newID:
             newID = p.pw_uid
     return newID + 1
Example #11
0
    def testPersistentBackup(self):

        with MonkeyPatchScope([
            (netinfo, 'NET_CONF_BACK_DIR',
             os.path.join(self._tempdir, 'netback')),
            (netinfo, 'NET_CONF_DIR', self._tempdir),
            (netinfo, 'NET_CONF_PREF',
             os.path.join(self._tempdir, 'ifcfg-')),
            (ifcfg, 'ifdown', lambda x: 0),
            (ifcfg, '_exec_ifup', lambda *x: 0),
            (libvirt, 'createNetwork', lambda *x: None),
            (libvirt, 'removeNetwork', lambda *x: None),
        ]):
            # after vdsm package is installed, the 'vdsm' account will be
            # created if no 'vdsm' account, we should skip this test
            if 'vdsm' not in [val.pw_name for val in pwd.getpwall()]:
                raise SkipTest("'vdsm' is not in user account database, "
                               "install vdsm package to create the vdsm user")

            self._createFiles()

            for fn, _, _ in self._files:
                self._cw._persistentBackup(fn)

            self._makeFilesDirty()

            self._cw.restorePersistentBackup()

            self._assertFilesRestored()
Example #12
0
def checklock():

    whoami = os.environ['USER']
    stage = os.environ['STAGE']

    if os.path.isfile(stage+'/users/.pylock') == True:
        ownerid = os.stat(stage+'/users/.pylock')[4]
        if ownerid != os.getuid():
            print 'your not the owner'
            print 'attempting to overwrite'
            userlist = pwd.getpwall()
            for o in range(0, len(userlist)):
                if userlist[o][2] == ownerid:
                    username = userlist[o][0]#this is the usersname
                    print username
                    p = subprocess.Popen('who', shell=True, stdout=subprocess.PIPE)
                    whoout = p.stdout.readlines()
                    for w in whoout:
                        if w.find(username) == 0:
                            print 'user with lock still logged in, cant override'
                            return -1
                        else:
                            print 'overriding lock'
                            return 2


        else:
            print 'your the owner, nothing to do.'
            return 0
    else:
        print 'no lock. locking'
        return 1
Example #13
0
	def getUser(self,mess,a): # %nss getUser pw_uid=1000 pw_name=stud
		s=''
		p=None
		print a
		try:
			if (a.has_key('pw_uid')):
				p=pwd.getpwuid(a['pw_uid'])
			elif (a.has_key('pw_name')):
				p=pwd.getpwnam(a['pw_name'])
			else:
				users=pwd.getpwall()
				i=0
				while (i<len(users)):
					users[i]=self.pwdStructToDict(users[i])
					i+=1
				s='@'+mess.getID()+'\n'+self.d.packData(users,'json')
		except:
			p=None
		if (s==''):
			if (p!=None):
				s='@'+mess.getID()+'\n'+self.d.packData(self.pwdStructToDict(p))
			else:
				s='@'+mess.getID()+'\n'+'success=false'
		out=xmpp.Message(mess.getFrom(),s)
		mid=self.d.genId()
		out.setID(mid)
		return out
Example #14
0
def GetUserIDs():
	UserIDs = map(
		lambda x: x.pw_uid,
		pwd.getpwall())
	return set(filter(
		lambda x: x >= MinID and x <= MaxID,
		UserIDs))
	def _ownership_update(self):
		"""Update owner and group"""
		stat = self._provider.get_stat(self._path)

		self._combobox_owner.handler_block_by_func(self._ownership_changed)
		self._combobox_group.handler_block_by_func(self._ownership_changed)

		# remove old entries
		self._list_owner.clear()
		self._list_group.clear()

		# for local file system fill comboboxes with available user and group names
		if self._provider.is_local:
			for i, user in enumerate(pwd.getpwall()):
				self._list_owner.append((user.pw_name, user.pw_uid))
				if user.pw_uid == stat.user_id:
					self._combobox_owner.set_active(i)

			for i, group in enumerate(grp.getgrall()):
				self._list_group.append((group.gr_name, group.gr_gid))
				if group.gr_gid == stat.group_id:
					self._combobox_group.set_active(i)

		# for remote file systems simply set owner and group
		else:
			self._list_owner.append((stat.user_id, stat.user_id))
			self._list_group.append((stat.group_id, stat.group_id))
			self._combobox_owner.set_active(0)
			self._combobox_group.set_active(0)

		self._combobox_owner.handler_unblock_by_func(self._ownership_changed)
		self._combobox_group.handler_unblock_by_func(self._ownership_changed)
Example #16
0
	def fill_user_profiles(self):
		global idstart
		# Find all users and by user ID read pickle and assign
		self.table_user_profiles.setRowCount(0)
		entries = []
		for p in pwd.getpwall():
			if p[2] >= idstart:
				# If user has set profile id, then find name
				user_profile_name = ""
				group_profile_name = ""
				effective_profile_name = ""

				if (int(p[2]) in self.data['user_profiles']):
					user_profile_id = self.data['user_profiles'][int(p[2])]
					user_profile_name = self.data['profiles'][user_profile_id]['name']
					effective_profile_name = user_profile_name
				if (int(p[3]) in self.data['group_profiles']):
					group_profile_id = self.data['group_profiles'][int(p[3])]
					group_profile_name = self.data['profiles'][group_profile_id]['name']
					if (effective_profile_name == ""):
						effective_profile_name = group_profile_name
				entries.append((str(p[2]),p[0],user_profile_name, group_profile_name, effective_profile_name))
		
		# Read all filters from PICKEL and show
		self.table_user_profiles.setRowCount(len(entries))
		self.table_user_profiles.setColumnCount(len(entries[0]))
		for i, row in enumerate(entries):
			for j, col in enumerate(row):
				item = QtGui.QTableWidgetItem(col)
				self.table_user_profiles.setItem(i, j, item)
Example #17
0
	def distribute_configs(self):
		global idstart
		for p in pwd.getpwall():
			if p[2] >= idstart:
				home = p[5]
				# If user has set profile id, then copy settings
				if (int(p[2]) in self.data['user_profiles']):
					profile_id = self.data['user_profiles'][int(p[2])]
					profile_settings = self.data['profiles'][profile_id]
					try:
						pickle.dump(profile_settings, open(home+"/.btw_settings.p", "wb"))
					except:
						pass
				elif (int(p[3]) in self.data['group_profiles']):
					profile_id = self.data['group_profiles'][int(p[3])]
					profile_settings = self.data['profiles'][profile_id]
					try:
						pickle.dump(profile_settings, open(home+"/.btw_settings.p", "wb"))
					except:
						pass
				else:
					try:
						pickle.dump({}, open(home+"/.btw_settings.p", "wb"))
					except:
						pass

				try:
					os.chown(home+"/.btw_settings.p", p[2], p[3])
				except:
					pass
Example #18
0
 def uid_list(self):
     """Lists all UIDs on the target system(s)."""
     uids = []
     for user in pwd.getpwall():
         if user[2] < 4294967294:
             uids.append(user[2])
     return uids
Example #19
0
def UserAdd_Shadow(User, Passwodr='*', ExpireDays=-1, ShadowFile='/etc/shadow'):
	# 1. temporary shadow file
	fd, TempShadowFile = mkstemp(prefix='shadow', dir='/tmp')

	# 2. get users passwd entries
	pwall = pwd.getpwall()
	pwall.sort(lambda a, b: cmp(a.pw_uid, b.pw_uid))

	# 3. generate shadow entries
	CreatedDays = int(time() / 86400)
	if ExpireDays != -1:
		ExpireDays = CreatedDays + ExpireDays

	spall = []
	for pw in pwall:
		try:
			sp = spwd.getspnam(pw.pw_name)
		except KeyError, e:
			sp = spwd.struct_spwd(
				sequence = (
					User,
					'*',
					CreatedDays,
					0,
					99999,
					7,
					-1,
					ExpireDays,
					-1))
		spall.append(sp)
  def UpdateAccounts(self):
    """Update all accounts that should be present or exist already."""

    # Note GetDesiredAccounts() returns a dict of username->sshKeys mappings.
    desired_accounts = self.desired_accounts.GetDesiredAccounts()

    # Plan a processing pass for extra accounts existing on the system with a
    # ~/.ssh/authorized_keys file, even if they're not otherwise in the metadata
    # server; this will only ever remove the last added-by-Google key from
    # accounts which were formerly in the metadata server but are no longer.
    all_accounts = pwd.getpwall()
    keyfile_suffix = os.path.join('.ssh', 'authorized_keys')
    sshable_usernames = [
        entry.pw_name
        for entry in all_accounts
        if os.path.isfile(os.path.join(entry.pw_dir, keyfile_suffix))]
    extra_usernames = set(sshable_usernames) - set(desired_accounts.keys())

    if desired_accounts:
      for username, ssh_keys in desired_accounts.iteritems():
        if not username:
          continue

        self.accounts.UpdateUser(username, ssh_keys)

    for username in extra_usernames:
      # If a username is present in extra_usernames, it is no longer reflected
      # in the metadata server but has an authorized_keys file. Therefore, we
      # should pass the empty list for sshKeys to ensure that any Google-managed
      # keys are no longer authorized.
      self.accounts.UpdateUser(username, [])
Example #21
0
def rm_crontab_boot():
    """
    Checks all users crontabs and removes any references to @reboot kmotion 

    args    :
    excepts : 
    return  : none
    """
    
    # How about: users = [ i[0] for i in pwd.getpwall() if i[2] > 500 ]   --
    # seems to work on all unix variants I have access to capable of running
    # Motion :) -- I'd make the groupid check >1000 but the pesky OSX uses
    # 501 for it's first user. Patch from Roman Gaufman
    for user in [i[0] for i in pwd.getpwall() if i[2] > 500 or i[2] == 0]:
        f_obj = os.popen('crontab -u %s -l' % user)
        ctab = f_obj.readlines()
        f_obj.close()
        
        # 'ctab == []' when no crontab for user
        if ctab == [] or ctab[0] == 'no crontab for %s' % user: continue
        tmp = []
        for line in ctab:
            if not (line[:7] == '@reboot' and line[-17:] == '/kmotion start &\n'):
                tmp.append(line)

        f_obj = os.popen('crontab -u %s -' % user, 'w')
        f_obj.writelines(tmp)
        f_obj.close()
Example #22
0
def list_all_known_prefixes():
    all_env_paths = set()
    if on_win:
        home_dir_dir = dirname(expand('~'))
        for home_dir in listdir(home_dir_dir):
            environments_txt_file = join(home_dir_dir, home_dir, '.conda', 'environments.txt')
            if isfile(environments_txt_file):
                all_env_paths.update(_clean_environments_txt(environments_txt_file))
    else:
        from os import geteuid
        from pwd import getpwall
        if geteuid() == 0:
            search_dirs = tuple(pwentry.pw_dir for pwentry in getpwall()) or (expand('~'),)
        else:
            search_dirs = (expand('~'),)
        for home_dir in search_dirs:
            environments_txt_file = join(home_dir, '.conda', 'environments.txt')
            if isfile(environments_txt_file):
                all_env_paths.update(_clean_environments_txt(environments_txt_file))

    # in case environments.txt files aren't complete, also add all known conda environments in
    # all envs_dirs
    envs_dirs = (envs_dir for envs_dir in context.envs_dirs if isdir(envs_dir))
    all_env_paths.update(path for path in (
        join(envs_dir, name) for envs_dir in envs_dirs for name in listdir(envs_dir)
    ) if path not in all_env_paths and is_conda_environment(path))

    all_env_paths.add(context.root_prefix)
    return sorted(all_env_paths)
Example #23
0
def migrateUsers():
    # build user -> group map for migration (hopefully we'll drop this in 2012)
    migration = []
    migrationMap = {
                    "removable"     : ["cdrom", "plugdev"],
                    "pnp"           : ["lp", "floppy"],
                    "pnpadmin"      : ["lpadmin"],
                   }
    for user in pwd.getpwall():
        groups = set()
        if 1000 <= user.pw_uid < 65534:
            for group in grp.getgrall():
                if user.pw_name in group.gr_mem:
                    groups.add(group.gr_name)

            for oldGroup, newGroups in migrationMap.items():
                if oldGroup in groups:
                    #groups.remove(oldGroup)
                    groups.update(newGroups)

            if groups:
                migration.append((user.pw_uid, list(groups)))

    # Migrate regular user groups
    for user, group in migration:
        # setUser(uid, realname, homedir, shell, passwd, groups)
        hav("setUser", user, "", "", "", "", group)
Example #24
0
 def isSystemUser(self, name):
     pwds = pwd.getpwall()
     for p in pwds:
         if p.pw_name == name:
             if p.pw_uid < self.first_uid or p.pw_uid > self.last_uid:
                 return True
     return False
Example #25
0
def get_users(exclude_system_users=True):
    if exclude_system_users:
        return [user.pw_name for user in pwd.getpwall()
                if user.pw_uid >= 1000]

    admin = libuser.admin()
    return admin.enumerateUsers()
 def enum_instances(self, env, model, keys_only):
     self._logger.log_debug("\n%s:  enum_instances called for class %s" % (self.__class__.__name__.upper(), model.classname))
     for pwent in pwd.getpwall():
         user_cin = pywbem.CIMInstanceName('TestAssoc_User',
                 namespace=model.path.namespace)
         group_cin = pywbem.CIMInstanceName('TestAssoc_Group',
                 namespace=model.path.namespace)
         model['Dependent'] = get_user_instance(pwent[2], user_cin, True)
         model.path['Dependent'] = get_user_instance(pwent[2], 
                 user_cin, True)
         model['Antecedent'] = get_group_instance(pwent[3], group_cin, True)
         model.path['Antecedent'] = get_group_instance(pwent[3], 
                 group_cin, True)
         if not keys_only:
             model['isPrimaryGroup'] = True
         yield model
         for grent in grp.getgrall():
             if pwent[0] in grent[3]:
                 model['Antecedent'] = get_group_instance(grent[2], 
                         group_cin, True)
                 model.path['Antecedent'] = get_group_instance(grent[2], 
                         group_cin, True)
                 if not keys_only:
                     model['isPrimaryGroup'] = False
                 yield model
Example #27
0
def map_uids_to_names():
    """Determine the mapping between user ids and user names."""
    ul = pwd.getpwall()
    d = {}
    for u in ul:
        d[u[2]] = u[0]
    return d
    def dir_chown(self, directories, user, group, recursive=False):
        """
        Chown a or multiple directories
        :param directories: Directories to chown
        :param user: User to assign to directories
        :param group: Group to assign to directories
        :param recursive: Chown the directories recursively or not
        :return: None
        """
        all_users = [user_info[0] for user_info in pwd.getpwall()]
        all_groups = [group_info[0] for group_info in grp.getgrall()]

        if user not in all_users:
            raise ValueError('User "{0}" is unknown on the system'.format(user))
        if group not in all_groups:
            raise ValueError('Group "{0}" is unknown on the system'.format(group))

        uid = pwd.getpwnam(user)[2]
        gid = grp.getgrnam(group)[2]
        if isinstance(directories, basestring):
            directories = [directories]
        for directory in directories:
            directory = self.shell_safe(directory)
            os.chown(directory, uid, gid)
            if recursive is True:
                for root, dirs, _ in os.walk(directory):
                    for sub_dir in dirs:
                        os.chown('/'.join([root, sub_dir]), uid, gid)
Example #29
0
 def getNewUserID(self):
     pwds = pwd.getpwall()
     for new_id in range(self.first_uid, self.last_uid):
         for p in pwds:
             if p.pw_uid != new_id:
                 return new_id
     return 0
Example #30
0
        def complete_files(self, text, state):
            str_delim = text[0]
            path = text[1:]

            if path.startswith("~/"):
                path = expanduser("~/") + path[2:]

            elif path.startswith("~"):
                i = path.find(pathsep)
                if i > 0:
                    path = expanduser(path[:i]) + path[i:]
                else:
                    return [
                        str_delim + "~" + i[0] + pathsep
                        for i in getpwall()
                        if i[0].startswith(path[1:])
                        ][state]

            dir, fname = splitpath(path)
            if not dir:
                dir = os.curdir
            return [
                str_delim + joinpath(dir, i)
                for i in os.listdir(dir)
                if i.startswith(fname)
                ][state]
Example #31
0
    def record_account(self):
        fingerprint = Kdatabase().get_obj("fingerprint")

        if common.is_linux():
            import pwd
            pwall_users = pwd.getpwall()
Example #32
0
def user_exists(user_name):
	for user in pwd.getpwall():
		if user_name == user.pw_name:
			return True

	return False
Example #33
0
# -*- coding: utf-8 -*-
import pwd
#заводим счетчики
erroruser = []
errorpass = []
#получаем базу данных паролей
passwd_db = pwd.getpwall()
try:
    #проверяем каждое имя пользователя и пароль на валидность
    for entry in passwd_db:
        username = entry[0]
        password = entry[1]
        if len(username) < 6:
            erroruser.append(username)
        if len(password) < 8:
            errorpass.append(username)
    #выводим результаты на экран
    print "Следующие пользователи имеют имена менее чем из 6 символов:"
    for item in erroruser:
        print item
    print "\nСледующие пользователи имеют пароли менее чем из 8 символов:"
    for item in errorpass:
        print item
except:
    print "Возникла проблема при выполнении программы!"
Example #34
0
 def _get_system_users():
     """Return all users defined on the UNIX system."""
     # there should be no need to convert usernames to unicode
     # as UNIX does not allow chars outside of ASCII set
     return [entry.pw_name for entry in pwd.getpwall()]
Example #35
0
    def __init__(self):
        dummy = _('Timekpr Control Panel')
        dummy = _('Timekpr Client')

        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 getpwall():
            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
Example #36
0
def install():  
    """
    The auto install script

    args    :   
    excepts : 
    return  : none
    """
    
    # ##########################################################################
    
    print DEP_TEXT,
    raw_ip = raw_input()
    if raw_ip != '' and raw_ip != 'yes':
        raise exit_('Please satisfy the above dependencies')
    
    # ##########################################################################
    
    print INSTALL_TEXT,
    if raw_input() != 'install':
        raise exit_('Install aborted')
    print LINE_TEXT

    # ##########################################################################
    
    # check we are running as root
    checking('Checking install is running as root')
    uid = os.getuid()
    if uid != 0:
        fail()
        raise exit_('The installer needs to be runs as root')
    ok()
    
    # ##########################################################################
    
    # check we can read ./core/core_rc - if we can't, assume we are
    # not in the kmotion root directory
    checking('Checking installer is running in correct directory')
    if not os.path.isfile('./core/core_rc'):
        fail()
        raise exit_('Please \'cd\' to the kmotion root directory before running the installer')
    ok()

    # if we are in the root dir set kmotion_dir
    kmotion_dir = os.getcwd()
    
    # check for existing motion instances
    checking('Checking for existing \'motion\' daemon instances')
    check_motion(kmotion_dir)
    ok()
    
    checking('Killing kmotion daemons')
    daemon_whip.kill_daemons()
    ok()
        
    # select a user to run the kmotion service
    checking('Searching for possible users to run kmotion service')
    ok()
    print SELECT_USER,
    users_uid = [[i[0], i[2], i[3]] for i in pwd.getpwall() if i[2] >= 500 or i[2] == 0]
    
    users = [i[0] for i in users_uid if i[0] != 'root' and i[0] != 'nobody']
    uid =   [i[1] for i in users_uid if i[0] != 'root' and i[0] != 'nobody']
    gid =   [i[2] for i in users_uid if i[0] != 'root' and i[0] != 'nobody']
    
    for user in users:
        print '\'%s\'' % user,
    print '\n\nType \'user\' to continue :',
    select = raw_input()
    
    if select not in users:
        raise exit_('Invalid user selected, Install aborted')
    kmotion_user = select
    kmotion_uid = uid[users.index(select)]
    kmotion_gid = gid[users.index(select)]
    
    # ##########################################################################
    
    # select ramdisk type
    df_out = Popen(['df'], stdout=PIPE).communicate()[0].split('\n')
    
    for line in df_out:
        split = line.split()
        
        if len(split) < 6: 
            continue
        
        #if False: # debug option to force 'virtual_ramdisk'
        if split[5] == '/dev/shm' and int(split[1]) > 30000:
            ramdisk_dir = '/dev/shm/kmotion_ramdisk'
            checking('Selected ramdisk ... /dev/shm')
            ok()
            break
            
    else:
        ramdisk_dir = '%s/www/virtual_ramdisk' % kmotion_dir
        checking('Selected virtual_ramdisk')
        ok()
      
    # ##########################################################################

    # initialise resource configurations
    checking('Initialise resource configurations')
    try: # wrapping in a try - except because parsing data from kmotion_rc
        init_core.init_rcs(kmotion_dir, ramdisk_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        fail()
        raise exit_('Corrupt \'kmotion_rc\' : %s' % sys.exc_info()[1])
    ok()
    
    # ##########################################################################
    
    # generate kmotion vhost
    checking('Generating kmotion vhost')
    try: # wrapping in a try - except because parsing data from kmotion_rc
        init_core.gen_vhost(kmotion_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        fail()
        raise exit_('Corrupt \'kmotion_rc\' : %s' % sys.exc_info()[1])
    
    # chown is needed so kmotion vhost is not locked to root allowing non root
    # kmotion to regenerate the vhost
    os.chown('%s/www/vhosts/kmotion' % kmotion_dir, kmotion_uid, kmotion_gid) 
    ok()
    
    # ##########################################################################
    
    # modifying 'apache2.conf'
    checking('Adding kmotion include to \'apache2.conf\'')
    try:
        modify_apache2(kmotion_dir)
    except exit_, text_:
        fail()
        raise exit_(text_)
Example #37
0
def user_exists(username):
    all_users = pwd.getpwall()
    for info in all_users:
        if info.pw_name == username:
            return True
    return False
Example #38
0
def discovery():
    stat = get_memory_stat()
    data = [
        struct_passwd_to_data(x) for x in pwd.getpwall() if x.pw_uid in stat
    ]
    print(json.dumps({'data': data}, indent=4, sort_keys=True))
Example #39
0
 def _get_system_users():
     """Return all users defined on the UNIX system."""
     return [entry.pw_name for entry in pwd.getpwall()]
Example #40
0
def _first_avail_uid():
    uids = set(x.pw_uid for x in pwd.getpwall())
    for idx in range(501, 2**24):
        if idx not in uids:
            return idx
Example #41
0
def pam_sm_authenticate(pamh, flags, argv):
    """ Authentication Function.

        If username is _guest_, with this function \
        guest user will be authenticated without \
        password.
    """

    try:
        pwd.getpwnam(pamh.get_user(None))
        return auth_return(pamh, -1)
    except KeyError:
        pass

    try:
        debugging = (argv[1] == 'debug')
    except IndexError:
        debugging = False

    try:
        config = ConfigParser.ConfigParser()
        config.read('/etc/security/guestlogin.conf')
        guest_enabled = config.get('guest', 'enabled')
        if guest_enabled == '':
            guest_enabled = "true"
        guest_name = config.get('guest', 'guestname')
        if guest_name == '':
            guest_name = "guest"
        guest_limit = config.get('guest', 'guestlimit')
        if guest_limit == '':
            guest_limit = 5
        guest_home_dir_size = config.get('guest', 'homedirsize')
        if guest_home_dir_size == '':
            guest_home_dir_size = 300
        guest_group = config.get('guest', 'guestgroup')
        if guest_group == '':
            guest_group = "guests"

    except ConfigParser.Error:
        guest_enabled = "true"
        guest_name = "guest"
        guest_limit = 5
        guest_home_dir_size = 300
        guest_group = "guests"
        if debugging and pamh.get_user(None) == guest_name:
            log("Unable to read config file at /etc/security/guestlogin.\
conf, using default values.\n")

    if guest_enabled == "false":
        return auth_return(pamh, 1)

    if pamh.get_user(None) == guest_name:
        users = [x.pw_name for x in pwd.getpwall()]
        i = 1
        while "%s%s" % (guest_name, i) in users:
            i = i + 1
            if (i > guest_limit):
                if debugging:
                    log("Guest User limit reached! Unable to create \
another guest user account.\n")
                return auth_return(pamh, -2)

        username = "******" % (guest_name, i)
        pamh.user = username
        try:
            grp.getgrnam(guest_group)
        except KeyError:
            if debugging:
                log("No group found named as %s, it will be \
created.\n" % guest_group)
            out = subprocess.Popen(["groupadd %s" % guest_group], \
                    shell=True, stdout=subprocess.PIPE, \
                    stderr=subprocess.PIPE)
            if out.wait() != 0:
                if debugging:
                    log("Creating group %s has been failed!" % guest_group)
                return auth_return(pamh, -1)
        try:
            home_dir = tempfile.mkdtemp(prefix='%s.' % username)
        except IOError:
            if debugging:
                log("No usable temporary directory name found")
            return auth_return(pamh, -2)

        if debugging:
            log("%s has been created successful with mktemp.\n" % home_dir)

        out = subprocess.Popen(["mount -t tmpfs -o size=%sm -o mode=711 \
                -o noexec none %s"                                   % (guest_home_dir_size, home_dir)], \
                shell=True)
        if out.wait() != 0:
            if debugging:
                log("Unable to mount %s" % home_dir)
            return auth_return(pamh, -2)

        if not os.path.ismount(home_dir):
            if debugging:
                log("Mount error! Unable to ismount(%s)" % home_dir)
            return auth_return(pamh, 2, home_dir)

        if debugging:
            log("%s has mounted as tmpfs\n" % home_dir)

        out = subprocess.Popen(["useradd -m -d %s/home -g %s %s" % \
                (home_dir, guest_group, username)], shell=True, \
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if out.wait() != 0:
            if debugging:
                log("Unable to add user %s to system\n" % username)
            return auth_return(pamh, -2)

        try:
            pwd.getpwnam(username)

        except KeyError:
            if debugging:
                log("User %s not found! Unable to getpwnam(%s)\n" % \
                        (username, username))
            return auth_return(pamh, 3, home_dir)

        if debugging:
            log("%s has been created successfully\n" % username)

        return auth_return(pamh, 0)

    else:
        return auth_return(pamh, -1)
Example #42
0
                                    retrieveAttributes)
    except ldap.LDAPError, e:
        logger.error(e)
        sys.exit(-1)

    nextuid = 0
    uidnumbers = []
    for dn, entry in ldap_result_id:
        if 'uidNumber' in entry:
            uidnumbers.append(int(entry['uidNumber'][0]))
    uidnumbers.sort()
    if 0 >= len(uidnumbers): nextuid = minUid
    else: nextuid = uidnumbers[-1] + 1

    if nextuid < minUid: nextuid = minUid
    while nextuid in map(lambda a: a.pw_uid, pwd.getpwall()):
        nextuid += 1


#  i = 1
#  max_idx = len(uidnumbers) -1
#  while i <= max_idx and uidnumbers[i] - uidnumbers[i-1] <= 1:
#    i += 1
#  if i <= max_idx:
#    if uidnumbers[i] - uidnumbers[i-1] > 1:
#      nextuid = uidnumbers[i-1] + 1
    return nextuid


def getGid(cn):
    ''' Return the gidNumber of the given cn '''
Example #43
0
def get_users():
    users = ""
    for user in pwd.getpwall():
        users += ", " + user[0]
    return users.lstrip(",").lstrip()
Example #44
0
import re
import subprocess

import shutil
import copy
import pwd

import getpass

########
# Conf #
########
dir = os.path.dirname(os.path.realpath(__file__))

userList = []
for p in pwd.getpwall():
    userList.append(p[0])

args = sys.argv
mulletInputPath = args[1]
#mulletInputPath = "/home/adam/ownCloud/PC/mullet/laptop"

########
# Keys #
########
keyPath = os.path.join(mulletInputPath, "keys")
keyUsers = os.listdir(keyPath)
for keyUser in keyUsers:
    print()
    print(keyUser)
Example #45
0
    def fill_cache(self, job, force=False):
        user_next_index = group_next_index = 100000000
        cache_data = {'users': {}, 'groups': {}}

        if self.middleware.call_sync('cache.has_key',
                                     'LDAP_cache') and not force:
            raise CallError(
                'LDAP cache already exists. Refusing to generate cache.')

        self.middleware.call_sync('cache.pop', 'LDAP_cache')

        if (self.middleware.call_sync('ldap.config'))['disable_freenas_cache']:
            self.middleware.call_sync('cache.put', 'LDAP_cache', cache_data)
            self.logger.debug('LDAP cache is disabled. Bypassing cache fill.')
            return

        pwd_list = pwd.getpwall()
        grp_list = grp.getgrall()

        local_uid_list = list(u['uid']
                              for u in self.middleware.call_sync('user.query'))
        local_gid_list = list(
            g['gid'] for g in self.middleware.call_sync('group.query'))

        for u in pwd_list:
            is_local_user = True if u.pw_uid in local_uid_list else False
            if is_local_user:
                continue

            cache_data['users'].update({
                u.pw_name: {
                    'id': user_next_index,
                    'uid': u.pw_uid,
                    'username': u.pw_name,
                    'unixhash': None,
                    'smbhash': None,
                    'group': {},
                    'home': '',
                    'shell': '',
                    'full_name': u.pw_gecos,
                    'builtin': False,
                    'email': '',
                    'password_disabled': False,
                    'locked': False,
                    'sudo': False,
                    'microsoft_account': False,
                    'attributes': {},
                    'groups': [],
                    'sshpubkey': None,
                    'local': False
                }
            })
            user_next_index += 1

        for g in grp_list:
            is_local_user = True if g.gr_gid in local_gid_list else False
            if is_local_user:
                continue

            cache_data['groups'].update({
                g.gr_name: {
                    'id': group_next_index,
                    'gid': g.gr_gid,
                    'group': g.gr_name,
                    'builtin': False,
                    'sudo': False,
                    'users': [],
                    'local': False
                }
            })
            group_next_index += 1

        self.middleware.call_sync('cache.put', 'LDAP_cache', cache_data)
        self.middleware.call_sync('dscache.backup')
Example #46
0
 def check_empty_password(self, plugins_output):
     for (pw_name, _, pw_uid, pw_gid, _, _, pw_shell) in pwd.getpwall():
         (_, sp_pwd, _, _, _, _, _, _, _) = spwd.getspnam(pw_name)
         if sp_pwd == '':
             self.error('User %s has an empty password' % pw_name)
Example #47
0
def get_users(exclude_system_users=True):
    if exclude_system_users:
        return [user.pw_name for user in pwd.getpwall() if user.pw_uid >= 1000]

    admin = libuser.admin()
    return admin.enumerateUsers()
Example #48
0
def get_other_nonroot_user():
    while True:
        user = random.choice(pwd.getpwall())
        if user.pw_uid not in (0, os.getuid()):
            break
    return user
Example #49
0
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)
Example #50
0
def add_all_users_to_dial_out():
    allUsers = [p[0] for p in pwd.getpwall()]
    with click.progressbar(allUsers) as bar:
        for user in bar:
            subprocess.call(["sudo", "adduser", user, "dialout"],
                            stdout=subprocess.PIPE)
Example #51
0
def read(filename):
    maps = _get_maps()
    lineno = 0
    for line in open(filename, 'r'):
        lineno += 1
        line = line.strip()
        # skip comments and blank lines
        if re.match('(#.*)?$', line, re.IGNORECASE):
            continue
        # parse options with a single integer argument
        m = re.match(
            '(?P<keyword>threads|ldap_version|bind_timelimit|timelimit|idle_timelimit|reconnect_sleeptime|reconnect_retrytime|pagesize|nss_min_uid)\s+(?P<value>\d+)',
            line, re.IGNORECASE)
        if m:
            globals()[m.group('keyword').lower()] = int(m.group('value'))
            continue
        # parse options with a single boolean argument
        m = re.match(
            '(?P<keyword>referrals|nss_nested_groups|nss_getgrent_skipmembers|nss_disable_enumeration)\s+(?P<value>%s)'
            % '|'.join(_boolean_options.keys()), line, re.IGNORECASE)
        if m:
            globals()[m.group('keyword').lower()] = _boolean_options[m.group(
                'value').lower()]
            continue
        # parse options with a single no-space value
        m = re.match(
            '(?P<keyword>uid|gid|bindpw|rootpwmodpw|sasl_mech)\s+(?P<value>\S+)',
            line, re.IGNORECASE)
        if m:
            globals()[m.group('keyword').lower()] = m.group('value')
            continue
        # parse options with a single value that can contain spaces
        m = re.match(
            '(?P<keyword>binddn|rootpwmoddn|sasl_realm|sasl_authcid|sasl_authzid|sasl_secprops|krb5_ccname|tls_cacertdir|tls_cacertfile|tls_randfile|tls_ciphers|tls_cert|tls_key|pam_password_prohibit_message)\s+(?P<value>\S.*)',
            line, re.IGNORECASE)
        if m:
            globals()[m.group('keyword').lower()] = m.group('value')
            continue
        # log <SCHEME> [<LEVEL>]
        m = re.match(
            'log\s+(?P<scheme>syslog|/\S*)(\s+(?P<level>%s))?' %
            '|'.join(_log_levels.keys()), line, re.IGNORECASE)
        if m:
            logs.append((m.group('scheme'),
                         _log_levels[str(m.group('level')).lower()]))
            continue
        # uri <URI>
        m = re.match('uri\s+(?P<uri>\S+)', line, re.IGNORECASE)
        if m:
            # FIXME: support multiple URI values
            # FIXME: support special DNS and DNS:domain values
            global uri
            uri = m.group('uri')
            continue
        # base <MAP>? <BASEDN>
        m = re.match(
            'base\s+((?P<map>%s)\s+)?(?P<value>\S.*)' % '|'.join(maps.keys()),
            line, re.IGNORECASE)
        if m:
            mod = maps[str(m.group('map')).lower()]
            if not hasattr(mod, 'bases'):
                mod.bases = []
            mod.bases.append(m.group('value'))
            continue
        # filter <MAP> <SEARCHFILTER>
        m = re.match(
            'filter\s+(?P<map>%s)\s+(?P<value>\S.*)' % '|'.join(maps.keys()),
            line, re.IGNORECASE)
        if m:
            mod = maps[m.group('map').lower()]
            mod.filter = m.group('value')
            continue
        # scope <MAP>? <SCOPE>
        m = re.match(
            'scope\s+((?P<map>%s)\s+)?(?P<value>%s)' %
            ('|'.join(maps.keys()), '|'.join(_scope_options.keys())), line,
            re.IGNORECASE)
        if m:
            mod = maps[str(m.group('map')).lower()]
            mod.scope = _scope_options[m.group('value').lower()]
            continue
        # map <MAP> <ATTRIBUTE> <ATTMAPPING>
        m = re.match(
            'map\s+(?P<map>%s)\s+(?P<attribute>\S+)\s+(?P<value>\S.*)' %
            '|'.join(maps.keys()), line, re.IGNORECASE)
        if m:
            mod = maps[m.group('map').lower()]
            attribute = m.group('attribute')
            if attribute not in mod.attmap:
                raise ParseError(filename, lineno,
                                 'attribute %s unknown' % attribute)
            mod.attmap[attribute] = m.group('value')
            # TODO: filter out attributes that cannot be an expression
            continue
        # deref <DEREF>
        m = re.match('deref\s+(?P<value>%s)' % '|'.join(_deref_options.keys()),
                     line, re.IGNORECASE)
        if m:
            global deref
            deref = _deref_options[m.group('value').lower()]
            continue
        # nss_initgroups_ignoreusers <USER,USER>|<ALLLOCAL>
        m = re.match('nss_initgroups_ignoreusers\s+(?P<value>\S.*)', line,
                     re.IGNORECASE)
        if m:
            users = m.group('value')
            if users.lower() == 'alllocal':
                # get all users known to the system currently (since nslcd
                # isn't yet running, this should work)
                import pwd
                users = (x.pw_name for x in pwd.getpwall())
            else:
                users = users.split(',')
                # TODO: warn about unknown users
            nss_initgroups_ignoreusers.update(users)
            continue
        # pam_authz_search <FILTER>
        m = re.match('pam_authz_search\s+(?P<value>\S.*)', line, re.IGNORECASE)
        if m:
            from expr import Expression
            pam_authz_searches.append(Expression(m.group('value')))
            # TODO: check pam_authz_search expression to only contain
            # username, service, ruser, rhost, tty, hostname, fqdn, dn or
            # uid variables
            continue
        # ssl <on|off|start_tls>
        m = re.match('ssl\s+(?P<value>%s)' % '|'.join(_ssl_options.keys()),
                     line, re.IGNORECASE)
        if m:
            global ssl
            ssl = _ssl_options[m.group('value').lower()]
            continue
        # sasl_canonicalize yes|no
        m = re.match(
            '(ldap_?)?sasl_(?P<no>no)?canon(icali[sz]e)?\s+(?P<value>%s)' %
            '|'.join(_boolean_options.keys()), line, re.IGNORECASE)
        if m:
            global sasl_canonicalize
            sasl_canonicalize = _boolean_options[m.group('value').lower()]
            if m.group('no'):
                sasl_canonicalize = not sasl_canonicalize
            continue
        # tls_reqcert <demand|hard|yes...>
        m = re.match(
            'tls_reqcert\s+(?P<value>%s)' %
            '|'.join(_tls_reqcert_options.keys()), line, re.IGNORECASE)
        if m:
            global tls_reqcert
            tls_reqcert = _tls_reqcert_options[m.group('value').lower()]
            continue
        # validnames /REGEX/i?
        m = re.match('validnames\s+/(?P<value>.*)/(?P<flags>[i]?)$', line,
                     re.IGNORECASE)
        if m:
            global validnames
            flags = 0 | re.IGNORECASE if m.group('flags') == 'i' else 0
            validnames = re.compile(m.group('value'), flags=flags)
            continue
        # reconnect_invalidate <MAP>,<MAP>,...
        m = re.match('reconnect_invalidate\s+(?P<value>\S.*)', line,
                     re.IGNORECASE)
        if m:
            dbs = re.split('[ ,]+', m.group('value').lower())
            for db in dbs:
                if db not in maps.keys() + ['nfsidmap']:
                    raise ParseError(filename, lineno, 'map %s unknown' % db)
            reconnect_invalidate.update(dbs)
            continue
        # unrecognised line
        raise ParseError(filename, lineno, 'error parsing line %r' % line)
    # if logging is not configured, default to syslog
    if not logs:
        logs.append(('syslog', logging.INFO))
    # dump config (debugging code)
    for k, v in globals().items():
        if not k.startswith('_'):
            logging.debug('%s=%r', k, v)
Example #52
0
def postInstall():
    # We don't want to overwrite an existing file during upgrade
    specialFiles = [
        "hosts", "passwd", "shadow", "group", "fstab", "ld.so.conf",
        "resolv.conf"
    ]

    for specialFile in specialFiles:
        if not os.path.exists("/etc/%s" % specialFile):
            shutil.copy("/usr/share/baselayout/%s" % specialFile, "/etc")

    shutil.copy("/etc/passwd", "/usr/share/baselayout/passwd.backup")
    shutil.copy("/etc/group", "/usr/share/baselayout/group.backup")

    # build user -> group map for migration
    migration = []
    for user in pwd.getpwall():
        groups = []
        if user[2] >= 1000 and user[2] < 65534:
            for group in grp.getgrall():
                if group[3].__contains__(user[0]):
                    groups.append(group[0])
            if groups.__contains__("cdrom"):
                groups.remove("cdrom")
                groups.append("removable")
            if groups.__contains__("plugdev"):
                groups.remove("plugdev")
                groups.append("removable")

            if groups.__contains__("lp"):
                groups.remove("lp")
                groups.append("pnp")
            if groups.__contains__("scanner"):
                groups.remove("scanner")
                groups.append("pnp")
            if len(groups) > 0:
                migration.append(
                    "hav call User.Manager.setUser uid %s groups %s" %
                    (user[2], ",".join(uniq(groups))))

        # Remove old groups/users
    groups = ["lp", "floppy", "uucp", "cdrom", "squid", "gdm", "xfs", "games", \
                "named", "mysql", "postgres", "cdrw", "apache", "nut", "usb", \
                "vpopmail", "users", "nofiles", "qmail", "postfix", "postdrop", "smmsp", \
                "slocate", "utmp", "scanner", "messagebus", "haldaemon", "plugdev", "firebird", \
                "dhcp", "ntlmaps", "ldap", "clamav"]

    for group in groups:
        try:
            gid = grp.getgrnam(group)[2]
            os.system("hav call User.Manager.deleteGroup gid %s" % gid)
        except KeyError:
            pass

    users = ["lp", "uucp", "squid", "gdm", "xfs", "games", \
                "named", "mysql", "postgres", "apache", "nut", "cyrus", \
                "vpopmail", "messagebus", "haldaemon", "alias", "qmaild", "qmaill", \
                "qmailp", "qmailq", "qmailr", "qmails", "postfix", "smmsp", "firebird", \
                "dhcp", "ntlmaps", "ldap", "clamav"]

    for user in users:
        try:
            uid = pwd.getpwnam(user)[2]
            os.system("hav call User.Manager.deleteUser uid %s" % uid)
        except KeyError:
            pass

    # Merge new system groups
    # I will replace these with proper comar calls, after finishing
    # some comar api work there, right now they are ok
    os.system("hav call User.Manager.addGroup gid 30 name squid")
    os.system("hav call User.Manager.addGroup gid 50 name named")
    os.system("hav call User.Manager.addGroup gid 60 name mysql")
    os.system("hav call User.Manager.addGroup gid 70 name postgres")
    os.system("hav call User.Manager.addGroup gid 80 name apache")
    os.system("hav call User.Manager.addGroup gid 90 name dovecot")
    os.system("hav call User.Manager.addGroup gid 100 name users")
    os.system("hav call User.Manager.addGroup gid 101 name dbus")
    os.system("hav call User.Manager.addGroup gid 102 name hal")
    os.system("hav call User.Manager.addGroup gid 103 name polkit")
    os.system("hav call User.Manager.addGroup gid 104 name postfix")
    os.system("hav call User.Manager.addGroup gid 105 name postdrop")
    os.system("hav call User.Manager.addGroup gid 106 name smmsp")
    os.system("hav call User.Manager.addGroup gid 107 name slocate")
    os.system("hav call User.Manager.addGroup gid 108 name utmp")
    os.system("hav call User.Manager.addGroup gid 109 name firebird")
    os.system("hav call User.Manager.addGroup gid 110 name dhcp")
    os.system("hav call User.Manager.addGroup gid 111 name ldap")
    os.system("hav call User.Manager.addGroup gid 112 name clamav")
    os.system("hav call User.Manager.addGroup gid 113 name ntlmaps")
    os.system("hav call User.Manager.addGroup gid 123 name ntp")
    os.system("hav call User.Manager.addGroup gid 130 name tss")
    os.system("hav call User.Manager.addGroup gid 131 name ejabberd")
    os.system("hav call User.Manager.addGroup gid 132 name tomcat")
    os.system("hav call User.Manager.addGroup gid 133 name ups")

    # Comar' profile groups
    os.system("hav call User.Manager.addGroup gid 200 name pnp")
    os.system("hav call User.Manager.addGroup gid 201 name removable")
    os.system("hav call User.Manager.addGroup gid 202 name netuser")
    os.system("hav call User.Manager.addGroup gid 203 name netadmin")
    os.system("hav call User.Manager.addGroup gid 204 name power")
    os.system("hav call User.Manager.addGroup gid 205 name pnpadmin")

    # Merge new system users
    os.system(
        "hav call User.Manager.addUser uid 20 name dialout realname Dialout shell /bin/false homedir /dev/null groups dialout"
    )
    os.system(
        "hav call User.Manager.addUser uid 30 name squid realname Squid shell /bin/false homedir /var/cache/squid groups squid"
    )
    os.system(
        "hav call User.Manager.addUser uid 40 name named realname Bind shell /bin/false homedir /var/bind groups named"
    )
    os.system(
        "hav call User.Manager.addUser uid 60 name mysql realname MySQL shell /bin/false homedir /var/lib/mysql groups mysql"
    )
    os.system(
        "hav call User.Manager.addUser uid 70 name postgres realname PostgreSQL shell /bin/bash homedir /var/lib/postgresql groups postgres"
    )
    os.system(
        "hav call User.Manager.addUser uid 80 name apache realname Apache shell /bin/false homedir /dev/null groups apache"
    )
    os.system(
        "hav call User.Manager.addUser uid 90 name dovecot realname Dovecot shell /bin/false homedir /dev/null groups dovecot"
    )
    os.system(
        "hav call User.Manager.addUser uid 101 name dbus realname D-BUS shell /bin/false homedir /dev/null groups dbus"
    )
    os.system(
        "hav call User.Manager.addUser uid 102 name hal realname Hal shell /bin/false homedir /dev/null groups hal"
    )
    os.system(
        "hav call User.Manager.addUser uid 103 name polkit realname PolicyKit shell /bin/false homedir /dev/null groups polkit"
    )
    os.system(
        "hav call User.Manager.addUser uid 104 name postfix realname Postfix shell /bin/false homedir /var/spool/postfix groups postfix"
    )
    os.system(
        "hav call User.Manager.addUser uid 106 name smmsp realname smmsp shell /bin/false homedir /var/spool/mqueue groups smmsp"
    )
    os.system(
        "hav call User.Manager.addUser uid 109 name firebird realname Firebird shell /bin/false homedir /opt/firebird groups firebird"
    )
    os.system(
        "hav call User.Manager.addUser uid 110 name dhcp realname DHCP shell /bin/false homedir /dev/null groups dhcp"
    )
    os.system(
        "hav call User.Manager.addUser uid 111 name ldap realname OpenLDAP shell /bin/false homedir /dev/null groups ldap"
    )
    os.system(
        "hav call User.Manager.addUser uid 112 name clamav realname Clamav shell /bin/false homedir /dev/null groups clamav"
    )
    os.system(
        "hav call User.Manager.addUser uid 113 name ntlmaps realname NTLMaps shell /bin/false homedir /dev/null groups ntlmaps"
    )
    os.system(
        "hav call User.Manager.addUser uid 123 name ntp realname NTP shell /bin/false homedir /dev/null groups ntp"
    )
    os.system(
        "hav call User.Manager.addUser uid 130 name tss realname tss shell /bin/false homedir /var/lib/tpm groups tss"
    )
    os.system(
        "hav call User.Manager.addUser uid 131 name ejabberd realname Ejabberd shell /bin/false homedir /dev/null groups ejabberd"
    )
    os.system(
        "hav call User.Manager.addUser uid 132 name tomcat realname Tomcat shell /bin/false homedir /var/lib/tomcat groups tomcat"
    )
    os.system(
        "hav call User.Manager.addUser uid 133 name ups realname UPS shell /bin/false homedir /var/lib/nut groups ups,dialout,tty,pnp"
    )
    # Comar' profile users
    os.system(
        "hav call User.Manager.addUser uid 200 name pnp realname PnP shell /bin/false homedir /dev/null groups pnp"
    )

    #migrate
    for cmd in migration:
        os.system(cmd)

    # We should only install empty files if these files don't already exist.
    if not os.path.exists("/var/log/lastlog"):
        os.system("/usr/bin/touch /var/log/lastlog")
    if not os.path.exists("/var/run/utmp"):
        os.system("/usr/bin/install -m 0664 -g utmp /dev/null /var/run/utmp")
    if not os.path.exists("/var/log/wtmp"):
        os.system("/usr/bin/install -m 0664 -g utmp /dev/null /var/log/wtmp")

    # Enable shadow groups
    os.system("/usr/sbin/grpconv")
    os.system("/usr/sbin/grpck -r &>/dev/null")

    # Create /root if not exists
    if not os.path.exists("/root/"):
        shutil.copytree("/etc/skel", "/root")
        os.chown("/root", 0, 0)
        os.chmod("/root", 0700)

    # Tell init to reload new inittab
    os.system("/sbin/telinit q")

    # Skype language selector
    lang = open("/etc/env.d/03locale").readline().strip("LANG=")[:5]

    if lang == "tr_TR":
        os.system(
            "sed -i -e 's/<Language>.*<\/Language>/<Language>tr<\/Language>/' /etc/skel/.Skype/shared.xml"
        )
    elif lang == "nl_NL":
        os.system(
            "sed -i -e 's/<Language>.*<\/Language>/<Language>nl<\/Language>/' /etc/skel/.Skype/shared.xml"
        )
    elif lang == "de_DE":
        os.system(
            "sed -i -e 's/<Language>.*<\/Language>/<Language>de<\/Language>/' /etc/skel/.Skype/shared.xml"
        )
    elif lang == "es_ES":
        os.system(
            "sed -i -e 's/<Language>.*<\/Language>/<Language>es<\/Language>/' /etc/skel/.Skype/shared.xml"
        )
    else:
        os.system(
            "sed -i -e 's/<Language>.*<\/Language>/<Language>en<\/Language>/' /etc/skel/.Skype/shared.xml"
        )
Example #53
0
 def get_ids(self, uid):
     return (id for id in pwd.getpwall() if (id.pw_uid >= uid))
Example #54
0
    def fill_cache(self, job, force=False):
        user_next_index = group_next_index = 200000000
        if self.middleware.call_sync('cache.has_key',
                                     'NIS_cache') and not force:
            raise CallError(
                'NIS cache already exists. Refusing to generate cache.')

        self.middleware.call_sync('cache.pop', 'NIS_cache')
        pwd_list = pwd.getpwall()
        grp_list = grp.getgrall()

        local_uid_list = list(u['uid']
                              for u in self.middleware.call_sync('user.query'))
        local_gid_list = list(
            g['gid'] for g in self.middleware.call_sync('group.query'))
        cache_data = {'users': [], 'groups': []}

        for u in pwd_list:
            is_local_user = True if u.pw_uid in local_uid_list else False
            if is_local_user:
                continue

            cache_data['users'].append({
                u.pw_name: {
                    'id': user_next_index,
                    'uid': u.pw_uid,
                    'username': u.pw_name,
                    'unixhash': None,
                    'smbhash': None,
                    'group': {},
                    'home': '',
                    'shell': '',
                    'full_name': u.pw_gecos,
                    'builtin': False,
                    'email': '',
                    'password_disabled': False,
                    'locked': False,
                    'sudo': False,
                    'sudo_nopasswd': False,
                    'sudo_commands': [],
                    'microsoft_account': False,
                    'attributes': {},
                    'groups': [],
                    'sshpubkey': None,
                    'local': False
                }
            })
            user_next_index += 1

        for g in grp_list:
            is_local_user = True if g.gr_gid in local_gid_list else False
            if is_local_user:
                continue

            cache_data['groups'].append({
                g.gr_name: {
                    'id': group_next_index,
                    'gid': g.gr_gid,
                    'group': g.gr_name,
                    'builtin': False,
                    'sudo': False,
                    'sudo_nopasswd': False,
                    'sudo_commands': [],
                    'users': [],
                    'local': False
                }
            })
            group_next_index += 1

        self.middleware.call_sync('cache.put', 'NIS_cache', cache_data)
        self.middleware.call_sync('dscache.backup')
Example #55
0
  def GetPrimaryGid():
    return os.getgid()

  def GetUserGroups():
    return set([GetPrimaryGid()] +
               [g.gr_gid for g in grp.getgrall() if USER_NAME() in g.gr_mem])

  DEFAULT_MODE = int(GetDefaultMode(), 8)
  USER_ID = os.getuid()
  USER_NAME = LazyWrapper(lambda: pwd.getpwuid(USER_ID).pw_name)
  # Take the current user's UID and increment it by one, this counts as an
  # invalid UID, as the metric used is if the UID matches the current user's,
  # exactly.
  INVALID_UID = LazyWrapper(lambda: sorted([user.pw_uid for user
                                            in pwd.getpwall()])[-1] + 1)

  # Note that because the system's GID mapping can change mid-test, tests that
  # check for specific errors should always re-fetch these GID-related values,
  # rather than reusing these LazyWrapper values.
  INVALID_GID = LazyWrapper(lambda: GetInvalidGid())
  # Get a list of all groups on the system where the current username is listed
  # as a member of the group in the gr_mem group attribute. Make this a list of
  # all group IDs and cast as a set for more efficient lookup times.
  USER_GROUPS = LazyWrapper(lambda: GetUserGroups())

# 256-bit base64 encryption keys used for testing AES256 customer-supplied
# encryption. These are public and open-source, so don't ever use them for
# real data.
TEST_ENCRYPTION_KEY1 = b'iMSM9eeXliDZHSBJZO71R98tfeW/+87VXTpk5chGd6Y='
TEST_ENCRYPTION_KEY1_SHA256_B64 = Base64Sha256FromBase64EncryptionKey(
Example #56
0
#Written for RHEL/Centos
#Writes a tab-formatted list of user information pulled from /etc/passwd

import pwd
print('{:<20s} {:<20s} {:<20s}'.format("Username","Userid","Full Name"))
for entry in pwd.getpwall():
    print('{:<20s} {:<20s} {:<20s}'.format(str(entry[0]), str(entry[2]), str(entry[4])))
   
Example #57
0
def sync_unix_users_and_groups(min_uid, max_uid, min_gid, max_gid,
                               check_shell):
    """
  Syncs the Hue database with the underlying Unix system, by importing users and
  groups from 'getent passwd' and 'getent groups'. This should also pull in
  users who are accessible via NSS.
  """
    global __users_lock, __groups_lock

    hadoop_groups = dict((group.gr_name, group) for group in grp.getgrall() \
        if (group.gr_gid >= min_gid and group.gr_gid < max_gid) or group.gr_name == 'hadoop')
    user_groups = dict()

    __users_lock.acquire()
    __groups_lock.acquire()
    # Import groups
    for name, group in hadoop_groups.iteritems():
        try:
            if len(group.gr_mem) != 0:
                hue_group = Group.objects.get(name=name)
        except Group.DoesNotExist:
            hue_group = Group(name=name)
            hue_group.save()
            LOG.info("Created group %s" % (hue_group.name, ))

        # Build a map of user to groups that the user is a member of
        members = group.gr_mem
        for member in members:
            if member not in user_groups:
                user_groups[member] = [hue_group]
            else:
                user_groups[member].append(hue_group)

    # Now let's import the users
    hadoop_users = dict((user.pw_name, user) for user in pwd.getpwall() \
        if (user.pw_uid >= min_uid and user.pw_uid < max_uid) or user.pw_name in grp.getgrnam('hadoop').gr_mem)
    for username, user in hadoop_users.iteritems():
        try:
            if check_shell:
                pw_shell = user.pw_shell
                if subprocess.call([pw_shell, "-c", "echo"],
                                   stdout=subprocess.PIPE) != 0:
                    continue
            hue_user = User.objects.get(username=username)
        except User.DoesNotExist:
            hue_user = User(username=username,
                            password='******',
                            is_active=True,
                            is_superuser=False)
            hue_user.set_unusable_password()

        # We have to do a save here, because the user needs to exist before we can
        # access the associated list of groups
        hue_user.save()
        if username not in user_groups:
            hue_user.groups = []
        else:
            # Here's where that user to group map we built comes in handy
            hue_user.groups = user_groups[username]
        hue_user.save()
        LOG.info(_("Synced user %s from Unix") % hue_user.username)

    __users_lock.release()
    __groups_lock.release()
Example #58
0
def getUsers(includeRoot=False):
    users = []
    for p in pwd.getpwall():
        if (len(str(p[2])) > 3) and (str(p[5])[0:5] == "/home"): #or (str(p[5])[0:5] == "/root"):
            users.append(p[0].lower())
    return users
Example #59
0
def default_users():
    return [user.pw_name for user in pwd.getpwall() if user.pw_uid >= 1000]
Example #60
0
		if error == 'file':
			self.message = 'Could not find .pynetatmo.conf in your home directory'
		elif error == 'key':
			self.message = 'Your configuration file appears to be invalid. Please check {home}.pynetatmo.conf'.format(home=HOME)
		else:
			self.message = None
		NetatmoError.__init__(self, self.message)




###################
#  CONFIGURATION  #
###################

for p in getpwall():
	HOME = p.pw_dir
	try:
		CONF = None
		with open(os.path.join(HOME, '.pynetatmo.conf'), 'r') as f:
			CONF = json.load(f)
			logger.debug('Configuration loaded')
		break
	except:
		pass
if not CONF:
	HOME = os.getenv('HOME') + '/'
	configure = input('Configuration file not found.\nWould you like to be guided through the configuration steps (otherwise you will have to create the JSON file on your own)? [y/n] ')
	if configure.upper() == 'Y':
		with open(os.path.join(HOME, '.pynetatmo.conf'), 'w') as f:
			try: