def delete_admin(username): """Remove a project admin's system account and home directory""" if not user.exists(username): raise UserDoesNotExistError("User does not exist: " + username) user_home = user.home_directory(username) sudo('deluser ' + username) sudo('rm -Rf ' + user_home)
def test_create_two_users_with_the_same_uid(): from fabtools.user import create, exists create('user6', uid='2000') assert exists('user6') create('user7', uid='2000', non_unique=True) assert exists('user7') uid6 = int(run("id -u user6")) uid7 = int(run("id -u user7")) assert uid7 == uid6 == 2000 run_as_root('userdel -r user6') assert not exists('user6') run_as_root('userdel -r user7') assert not exists('user7')
def test_create_two_users_with_the_same_uid(): from fabtools.user import create, exists create("user6", uid="2000") assert exists("user6") create("user7", uid="2000", non_unique=True) assert exists("user7") uid6 = int(run("id -u user6")) uid7 = int(run("id -u user7")) assert uid7 == uid6 == 2000 run_as_root("userdel -r user6") assert not exists("user6") run_as_root("userdel -r user7") assert not exists("user7")
def check_user(): new_user = env.user with settings(user='******'): if not user.exists(new_user): password = prompt("Password for the new user: "******"/bin/bash") _success("User %s created" % new_user) else: _info("User %s already exists." % new_user)
def test_create_user_with_default_home_directory(): from fabtools.user import create, exists try: create('user2') assert exists('user2') assert is_dir('/home/user2') finally: run_as_root('userdel -r user2')
def test_create_system_user_without_home_directory(): from fabtools.user import create, exists try: create('user4', system=True) assert exists('user4') assert not is_dir('/home/user4') finally: run_as_root('userdel -r user4')
def test_create_user_without_home_directory(): from fabtools.user import create, exists try: create('user1', create_home=False) assert exists('user1') assert not is_dir('/home/user1') finally: run_as_root('userdel -r user1', warn_only=True)
def test_create_system_user_with_home_directory(): from fabtools.user import create, exists try: create('user5', system=True, create_home=True, home='/var/lib/foo') assert exists('user5') assert is_dir('/var/lib/foo') finally: run_as_root('userdel -r user5')
def test_create_system_user_with_home_directory(): from fabtools.user import create, exists try: create("user5", system=True, create_home=True, home="/var/lib/foo") assert exists("user5") assert is_dir("/var/lib/foo") finally: run_as_root("userdel -r user5", warn_only=True)
def test_create_user_without_home_directory(): from fabtools.user import create, exists try: create('user1', create_home=False) assert exists('user1') assert not is_dir('/home/user1') finally: run_as_root('userdel -r user1')
def test_create_user_without_home_directory(): from fabtools.user import create, exists try: create("user1", create_home=False) assert exists("user1") assert not is_dir("/home/user1") finally: run_as_root("userdel -r user1", warn_only=True)
def add_user(users): for user in users: key_path = os.path.join(os.path.dirname(__file__), '../ssh_key_' + user + '.pub') if not fabuser.exists(user): fabuser.create(user, password='******', shell='/bin/bash') try: fabuser.modify(user, ssh_public_keys=key_path) except FileNotFoundError: pass
def test_create_user_with_default_home_directory(): from fabtools.user import create, exists try: create('user2') assert exists('user2') assert is_dir('/home/user2') finally: run_as_root('userdel -r user2', warn_only=True)
def test_create_system_user_with_home_directory(): from fabtools.user import create, exists try: create('user5', system=True, create_home=True, home='/var/lib/foo') assert exists('user5') assert is_dir('/var/lib/foo') finally: run_as_root('userdel -r user5', warn_only=True)
def test_create_user_with_default_home_directory(): from fabtools.user import create, exists try: create("user2") assert exists("user2") assert is_dir("/home/user2") finally: run_as_root("userdel -r user2", warn_only=True)
def add_user(user=None, group=None): """ Adds user, group can also be specified. """ if user is None: print(red( "User not specified. Usage: admin.add_user:<username>,<group>")) return if not exists(user): create(name=user, group=group, password=user, shell='/bin/bash') print(green("User succesfully created.")) else: print(red("User already exists."))
def test_require_user_with_default_home(): from fabtools.require import user from fabtools.user import exists try: user('req2', create_home=True) assert exists('req2') assert is_dir('/home/req2') finally: run_as_root('userdel -r req2', warn_only=True)
def test_require_user_with_default_home(): from fabtools.require import user from fabtools.user import exists try: user("req2", create_home=True) assert exists("req2") assert is_dir("/home/req2") finally: run_as_root("userdel -r req2", warn_only=True)
def test_create_user_with_home_directory(): from fabtools.user import create, exists try: create('user3', home='/tmp/user3') assert exists('user3') assert not is_dir('/home/user3') assert is_dir('/tmp/user3') finally: run_as_root('userdel -r user3')
def test_require_user_with_default_home(): from fabtools.require import user from fabtools.user import exists try: user('req2', create_home=True) assert exists('req2') assert is_dir('/home/req2') finally: run_as_root('userdel -r req2')
def test_create_user_with_home_directory(): from fabtools.user import create, exists try: create('user3', home='/tmp/user3') assert exists('user3') assert not is_dir('/home/user3') assert is_dir('/tmp/user3') finally: run_as_root('userdel -r user3', warn_only=True)
def add_user(user=None, group=None): """ Adds user, group can also be specified. """ if user is None: print( red("User not specified. Usage: admin.add_user:<username>,<group>") ) return if not exists(user): create(name=user, group=group, password=user, shell='/bin/bash') print(green("User succesfully created.")) else: print(red("User already exists."))
def test_require_user_with_custom_home(): from fabtools.require import user from fabtools.user import exists try: user("req3", home="/home/other") assert exists("req3") assert not is_dir("/home/req3") assert is_dir("/home/other") finally: run_as_root("userdel -r req3", warn_only=True)
def test_require_user_with_custom_home(): from fabtools.require import user from fabtools.user import exists try: user('req3', home='/home/other') assert exists('req3') assert not is_dir('/home/req3') assert is_dir('/home/other') finally: run_as_root('userdel -r req3')
def test_require_user_with_custom_home(): from fabtools.require import user from fabtools.user import exists try: user('req3', home='/home/other') assert exists('req3') assert not is_dir('/home/req3') assert is_dir('/home/other') finally: run_as_root('userdel -r req3', warn_only=True)
def add_key(user='', key=''): if not user: raise ValueError("Username cannot be empty.") if confirm("Add key/user to: " + env.host_string + "?"): key_path = os.path.join(os.path.dirname(__file__), key) if not fabuser.exists(user): fabuser.create(user, password='******', shell='/bin/bash') fabuser.modify(user, group='sudo') try: fabuser.modify(user, ssh_public_keys=key_path) except FileNotFoundError: print("Could not find SSH key at the specified location.")
def users(): from fabtools.require import user as require_user from fabtools.user import exists test_users = ['testuser', 'testuser2'] for username in test_users: require_user(username, create_home=False) yield for username in test_users: if exists(username): run_as_root('userdel %s' % username)
def test_require_user_without_home(): from fabtools.require import user from fabtools.user import exists try: user("req1", create_home=False) assert exists("req1") assert not is_dir("/home/req1") # require again user("req1") finally: run_as_root("userdel -r req1", warn_only=True)
def test_require_user_without_home(): from fabtools.require import user from fabtools.user import exists try: user('req1', create_home=False) assert exists('req1') assert not is_dir('/home/req1') # require again user('req1') finally: run_as_root('userdel -r req1', warn_only=True)
def test_require_user_without_home(): from fabtools.require import user from fabtools.user import exists try: user('req1', create_home=False) assert exists('req1') assert not is_dir('/home/req1') # require again user('req1') finally: run_as_root('userdel -r req1')
def env_base_requirement(direct=True, sync_dotfiles='fabrecipes'): """ Install requirement base system """ pkgs = [ 'zsh', 'wget', 'netctl', 'dialog', 'yaourt', 'python2', 'ifplugd', 'net-tools', 'wpa_actiond', 'wpa_supplicant', ] # Check if a custom package for computer env_section = inspect.stack()[0][3] if 'pkgs' in env and env_section in env.pkgs: pkgs = list(set(pkgs + env.pkgs[env_section])) # Install required packages run_as_root('dirmngr </dev/null') run_as_root('pacman-key --init') run_as_root('pacman-key --populate archlinux') run_as_root('pacman-key --refresh-keys') run_as_root('pacman --noconfirm -Syyu') run_as_root('pacman-db-upgrade') require.arch.packages(pkgs, options=["--noconfirm"]) # Install oh-my-zsh ohmyzsh = '$HOME/.oh-my-zsh' if not is_dir(ohmyzsh): run( 'git clone git://github.com/robbyrussell/oh-my-zsh.git %(ohmyzsh)s' % locals() ) # Set default ZSH shell for user if user.exists(env.useraccount): user.modify(env.useraccount, shell='/usr/bin/zsh') # Synchronize user dotfiles sync_dotfiles = 'fabrecipes/autoinstall/%(env_section)s' % locals() dotfiles.sync('%(sync_dotfiles)s/user/' % locals(), '$HOME/') dotfiles.sync('%(sync_dotfiles)s/sys/' % locals(), '/', use_sudo='true')
def user(name, comment=None, home=None, create_home=None, skeleton_dir=None, group=None, create_group=True, extra_groups=None, password=None, system=False, shell=None, uid=None, ssh_public_keys=None, non_unique=False): """ Require a user and its home directory. See :func:`fabtools.user.create` for a detailed description of arguments. :: from fabtools import require # This will also create a home directory for alice require.user('alice') # Sometimes we don't need a home directory require.user('mydaemon', create_home=False) # Require a user without shell access require.user('nologin', shell='/bin/false') .. note:: This function can be accessed directly from the ``fabtools.require`` module for convenience. """ from fabtools.require import directory as require_directory # Make sure the user exists if not exists(name): create(name, comment=comment, home=home, create_home=create_home, skeleton_dir=skeleton_dir, group=group, create_group=create_group, extra_groups=extra_groups, password=password, system=system, shell=shell, uid=uid, ssh_public_keys=ssh_public_keys, non_unique=non_unique) else: modify(name, comment=comment, home=home, group=group, extra_groups=extra_groups, password=password, shell=shell, uid=uid, ssh_public_keys=ssh_public_keys, non_unique=non_unique) # Make sure the home directory exists and is owned by user if home: require_directory(home, owner=name, use_sudo=True)
def setup_app(): """ Setup the application """ if not exists(user): puts(green("Creating user: {0}".format(user))) create(user, comment="logparser applicaiton user", system=True, shell="/sbin/nologin") if not is_dir("/var/log/{0}".format(app)): with cd("/var/log"): require.files.directory(app, owner=user, group=user, use_sudo=True) with cd("{0}/{1}".format(app_dir, app)): if not virtualenv_exists("{0}_env".format(app)): sudo("virtualenv {0}_env".format(app)) if virtualenv_exists("{0}_env".format(app)): with virtualenv("{0}_env".format(app)): sudo("pip install -r requirements.txt", )
def add_user(user=None, extra_group=None): """ Adds user, an extra group can also be specified. """ if user is None: print(red( "User not specified. Usage: admin.add_user:<username>,<group>")) return if not exists(user): # the default group created is equal to the user, the extra_group is # added only if present if extra_group: create(name=user, group=user, extra_groups=[extra_group], password=user, shell='/bin/bash') else: create(name=user, group=user, password=user, shell='/bin/bash') print(green("User succesfully created.")) else: print(red("User already exists."))
def create_user(username, password=None): if user.exists(username): raise KeyError("Username {} is taken".format(username)) if password is None: password = gen_pass(10) # Create user user.create(name=username, group="www-data", extra_groups=["sudo"], shell="/bin/bash", create_home=True, password=password) print c.blue("Username="******"Password=", bold=True),\ c.green(password, bold=True) return username, password
def create_admin(username, sudoer=True): """Create a system user account for a project admin""" if user.exists(username): raise UserExistsError("User already exists: " + username) admin = get_admin_profile(username) # TODO: Process more kwargs accepted by fabtools.require.user user_options = ('ssh_public_keys', 'shell',) user_kwargs = {kwarg: admin[kwarg] for kwarg in user_options if kwarg in admin} if 'skeleton_dir' in admin: with remote_local_file(admin['skeleton_dir']) as skel_dir: user_kwargs['skeleton_dir'] = skel_dir require.users.user(username, **user_kwargs) else: require.users.user(username, **user_kwargs) if sudoer: require.users.sudoer(username) sudo('usermod -G root -a ' + username) #run_admin_postcreate(username) # TODO: see if any work's required to make += work here env.machine.installed_admins = sorted((env.machine.installed_admins or []) + [username])
def setupsupervisor(): """ Setup supervisor on remote host. """ if not is_installed("supervisor"): puts(green("Installing supervisor.")) sudo("pip install supervisor") if not exists("supervisor"): puts(green("Creating supervisor user")) create("supervisor", comment="supervisord user", system=True) supervisor_context = {"logpath": "/var/log/supervisord.log"} puts(green("Uploading supervisord.conf")) upload_template("templates/supervisord.conf", "/etc/supervisord.conf", \ context=supervisor_context, mode=0700, use_sudo=True) texts = ["[include]", "files=/etc/supervisor.d/*.conf"] for text in texts: if not contains("/etc/supervisord.conf", text, use_sudo=True): append("/etc/supervisord.conf", text, use_sudo=True) with cd("/etc"): if not is_dir("supervisor.d"): puts(green("Making supervisor.d configuration directory")) sudo("mkdir supervisor.d") sudo("chown supervisor:root -R supervisor.d") sudo("chown supervisor:root supervisord.conf") with cd("init.d"): if not is_file("supervisord"): puts(green("Uploading supervisord startup script")) put(local_path="files/supervisord", remote_path="/etc/init.d/supervisord", \ mode=0700, use_sudo=True) sudo("chown supervisor:root supervisord") puts(green("Starting supervisord service")) sudo("chkconfig --add supervisord") sudo("chkconfig --level 3 supervisord on") sudo("service supervisord start") with cd("/var/log"): if not is_file("supervisord.log"): puts(green("Creating supervisor log file")) sudo( "touch supervisord.log && chown supervisor:root supervisord.log" )
def uninstall(app): # pragma: no cover """uninstall the app""" for path in (app.nginx_location, app.nginx_site, app.venv_dir): if exists(str(path)): if path == app.nginx_site: nginx.disable(app.nginx_site.name) files.remove(str(path), recursive=True, use_sudo=True) stop.execute_inner(app) if user.exists(app.name): if app.stack != 'soundcomparisons': sudo('dropdb --if-exists %s' % app.name, user='******') else: sudo('echo "drop database {0};" | mysql'.format(app.name)) sudo('userdel -rf %s' % app.name) if exists(str(app.supervisor)): files.remove(str(app.supervisor), recursive=True, use_sudo=True) supervisor.update_config() service.reload('nginx') systemd.uninstall(app, pathlib.Path(os.getcwd()) / 'systemd')
def add_user(user=None, extra_group=None): """ Adds user, an extra group can also be specified. """ if user is None: print( red("User not specified. Usage: admin.add_user:<username>,<group>") ) return if not exists(user): # the default group created is equal to the user, the extra_group is # added only if present if extra_group: create(name=user, group=user, extra_groups=[extra_group], password=user, shell='/bin/bash') else: create(name=user, group=user, password=user, shell='/bin/bash') print(green("User succesfully created.")) else: print(red("User already exists."))
def setup_user(): if not user.exists('scipy'): sudo('useradd -s/bin/bash -d/home/scipy -m scipy')
def user(name, comment=None, home=None, create_home=None, skeleton_dir=None, group=None, create_group=True, extra_groups=None, password=None, system=False, shell=None, uid=None): """ Require a user and its home directory. See :func:`fabtools.user.create` for a detailed description of arguments. :: from fabtools import require # This will also create a home directory for alice require.user('alice') # Sometimes we don't need a home directory require.user('mydaemon', create_home=False) # Require a user without shell access require.user('nologin', shell='/bin/false') .. note:: This function can be accessed directly from the ``fabtools.require`` module for convenience. """ from fabtools.require import directory as require_directory # Make sure the user exists if not exists(name): create(name, comment=comment, home=home, create_home=create_home, skeleton_dir=skeleton_dir, group=group, create_group=create_group, extra_groups=extra_groups, password=password, system=system, shell=shell, uid=uid) else: modify(name, comment=comment, home=home, group=group, extra_groups=extra_groups, password=password, shell=shell, uid=uid) # Make sure the home directory exists and is owned by user if home: require_directory(home, owner=name, use_sudo=True)
def remove_users(): from fabtools.user import exists for user in TEST_USERS: if exists(user): run_as_root('userdel %s' % user)
def configure_postgres_user(): if system_user.exists("postgres"): system_user.modify("postgres", password=env.postgresql_user_password)
def create_missing_admins(): """Create system accounts for any admins missing one""" for admin in env.project.ADMINS: if 'username' in admin and not user.exists(admin['username']): create_admin(admin['username'])
def setup_user(): if not user.exists(SITE_USER): sudo('useradd -s/bin/bash -d/home/%s -m %s' % (SITE_USER, SITE_USER))
def install(): """ Installs Nix""" # Install the Nix package if not deb.is_installed('nix'): execute('nix.install_deps') # obtain the LSB codename codename = utils.deb.get_release_info().codename url = NIX_BUILDS_URL.format(**NIX_BUILDS[codename]) tmp_dir = mkdtemp() with cd(tmp_dir): print(green('Downloading Nix 1.11.2')) run("wget '{}'".format(url)) print(green('Installing Nix')) sudo('dpkg --unpack *.deb') deb.install('nix') rmtree(tmp_dir) # Create Nix build user accounts grp = 'nixbld' if not group.exists(grp): group.create(grp) for n in range(10): usr = "******".format(n) if not user.exists(usr): user.create(usr, comment="Nix build user {}".format(n), group=grp, extra_groups=[grp], system=True, shell='/bin/false') sudo('mkdir -p /etc/nix') sudo('mkdir -p /nix/store') sudo('chown root.nixbld /nix/store') sudo('chmod 1775 /nix/store') sudo('mkdir -p -m 1777 /nix/var/nix/gcroots/per-user') sudo('mkdir -p -m 1777 /nix/var/nix/profiles/per-user') # Configure nix-daemon init_path = '/etc/init.d/' upload_template(os.path.join(TEMPLATES_FOLDER, 'nix-daemon'), init_path, backup=False, mode=0o755, use_sudo=True) sudo('update-rc.d nix-daemon defaults') green('Starting nix-daemon') sudo('/etc/init.d/nix-daemon start') # Setup profile nix_profile = '/etc/profile.d/nix.sh' append(nix_profile, PROFILE_SUFFIX, use_sudo=True) sudo('service nix-daemon restart') # Setup Nix for current user execute('nix.user_setup') green('Done. Remember to log out and back in before using Nix.')