Exemplo n.º 1
0
def add_user(username: str):
    if not _user_exists(username):
        logger.info('Adding user: %s', username)
        try:
            useradd('--create-home', '-g', USERS_GROUP, '-G', ','.join(
                (USERS_GROUP, SUDO_GROUP)), username)
        except ErrorReturnCode as e:
            logger.error(e)
Exemplo n.º 2
0
def make_user(
    username: str = "demo_user",
    password: str = None,
    *,
    add_home: bool = True,
    home_dir: Path = None,
    allow_existing_user: bool = True,
    get_sudo: bool = True,
) -> None:
    """ """
    import crypt
    import sh
    import getpass

    query = []

    if add_home:
        query += [f"-m", f"-d"]
        if home_dir:
            query += [str(home_dir)]
        else:
            query += [f"/home/{username}"]

    try:
        user_id = sh.id(["-u", username])
        if int(user_id):
            if not allow_existing_user:
                raise FileExistsError
            group_id = sh.id(["-g", username])
            print(f"user {username} exists with id {user_id} and {group_id}")
    except (ValueError, sh.ErrorReturnCode_1):
        pass
        with ContextWrapper(
                sh.contrib.sudo,
                construction_kwargs=dict(
                    password=getpass.getpass(
                        prompt=f"[sudo] password for {getpass.getuser()}: ")
                    if get_sudo else None,
                    _with=True,
                ),
                enabled=get_sudo,
        ):
            try:
                sh.useradd(query + [
                    f"-p",
                    f"{crypt.crypt(password if password else input(f'new password for user {username}: '), '22')}",
                    f"{username}",
                ])
            except sh.ErrorReturnCode_9:
                pass
Exemplo n.º 3
0
def setupWP(domain,username,password):
	siteRoot = '/webapps/%s'%(domain)
	siteLogs = '/webapps/%s/logs'%(domain)
	sitePublic = '/webapps/%s/public'%(domain)
	wpConfTemplate = 'wp.nginx.vhost.conf.template'
	sh.useradd('-m','-d',siteRoot, username,'-s', '/bin/bash','-p', password)
	sh.usermod('-aG', username, WEB_SERVER_GROUP)
	sh.mkdir('-p', siteLogs)
	sh.mkdir('-p', sitePublic)
	sh.cp('index.php', sitePublic)
	sh.chmod('-R','750', siteRoot)
	sh.chmod('-R','770', siteLogs)
	sh.chown('-R',"%s:%s"%(username,username), siteRoot)
	setupNginx(domain,username,wpConfTemplate,sitePublic,siteLogs)
	setupPhpFpm(username)
Exemplo n.º 4
0
def setupWP(domain, username, password):
    siteRoot = '/webapps/%s' % (domain)
    siteLogs = '/webapps/%s/logs' % (domain)
    sitePublic = '/webapps/%s/public' % (domain)
    wpConfTemplate = 'wp.nginx.vhost.conf.template'
    sh.useradd('-m', '-d', siteRoot, username, '-s', '/bin/bash', '-p',
               password)
    sh.usermod('-aG', username, WEB_SERVER_GROUP)
    sh.mkdir('-p', siteLogs)
    sh.mkdir('-p', sitePublic)
    sh.cp('index.php', sitePublic)
    sh.chmod('-R', '750', siteRoot)
    sh.chmod('-R', '770', siteLogs)
    sh.chown('-R', "%s:%s" % (username, username), siteRoot)
    setupNginx(domain, username, wpConfTemplate, sitePublic, siteLogs)
    setupPhpFpm(username)
Exemplo n.º 5
0
    def initServiceToUser(self, request, user):
        try:
            username = user.username
            homedirectory = '/home/%s' % (username)
            useradd(username, '-m')
            chown('-R', username, homedirectory)

        except ErrorReturnCode:
            messages.error(request,
                           "LocalAccountError: User creation failed. Check if user has sudo rights, that runs this application.")
            user.delete()
            return False
        local = LocalAccount()
        tmp = Service.objects.create(user=user, servicetype=local.getServiceType(), state='a')
        tmp.save()
        messages.success(request, "User is successfully created.")
        return True
Exemplo n.º 6
0
    def ensure_user(self, name, home=None):
        " Ensure the presence of a user in the system and its home path."

        print(" * Check if the user exists ... ")
        
        if any(name == u.pw_name for u in pwd.getpwall()):
            print("   ... user already exists. ")
            return

        print("   ... create user ...")
        
        if home is not None:            
            sh.useradd('-d', home, '-m', name, _err=sys.stderr, _out=sys.stdout)
        else:
            sh.useradd('-m', name, _err=sys.stderr, _out=sys.stdout)
            
        print("   ... done!")
Exemplo n.º 7
0
def check_and_add(username):
    """
    Check if the user already exists.

    Raise UsernameException when it exists, create when not.
    """
    try:
        sh.id(username)
    except sh.ErrorReturnCode:
        if not os.path.exists(PATH_PREFIX):
            # If the initial homes don't exist, create them with the right mode
            os.makedirs(PATH_PREFIX, mode=0o755)
        # User does not exist, add it
        sh.useradd(
            username, '-b', PATH_PREFIX, '-p', '*', '-s', '/bin/bash')
        return
    raise UsernameException(
        400, {'error': 'Username {0} already exists.'.format(username)})
Exemplo n.º 8
0
	def _create_user(self):
		if not self.suexec:
			return (self.default_user, self.default_user)

		r = re.compile('^web(\d+)$', re.IGNORECASE)

		max_num = 0

		with open('/etc/passwd', 'r') as f:
			lines = [x.strip() for x in f.readlines()]

			for account_info in lines:
				parts = account_info.split(':')
				m = r.match(parts[0])
				if m and int(m.group(1)) > max_num:
					max_num = int(m.group(1))

		username = '******' % (max_num + 1)
		useradd('-d', self.vhost_dir, '-M', '-s', '/sbin/nologin', username)
		return (username, username)
Exemplo n.º 9
0
    def _create_user(self):
        if not self.suexec:
            return (self.default_user, self.default_user)

        r = re.compile('^web(\d+)$', re.IGNORECASE)

        max_num = 0

        with open('/etc/passwd', 'r') as f:
            lines = [x.strip() for x in f.readlines()]

            for account_info in lines:
                parts = account_info.split(':')
                m = r.match(parts[0])
                if m and int(m.group(1)) > max_num:
                    max_num = int(m.group(1))

        username = '******' % (max_num + 1)
        useradd('-d', self.vhost_dir, '-M', '-s', '/sbin/nologin', username)
        return (username, username)
Exemplo n.º 10
0
def useradd(username):
    sh.useradd(username, '-b', HOME_PATH_PREFIX, '-p', '*', '-s', '/bin/bash')
Exemplo n.º 11
0
def useradd(username):
    sh.useradd(username, '-b', HOME_PATH_PREFIX, '-p', '*', '-s', '/bin/bash')