Example #1
0
def add_user(user):
    keys = []

    file = "keys/%s.id_rsa.pub" % user
    if os.path.exists(file):
        keys = [file]

    create(user, extra_groups=['sudo'], ssh_public_keys=keys)
Example #2
0
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)
Example #3
0
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')
Example #4
0
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')
Example #5
0
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)
Example #6
0
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)
Example #7
0
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)
Example #8
0
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')
Example #9
0
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)
Example #10
0
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')
Example #11
0
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)
Example #12
0
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)
Example #13
0
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')
Example #14
0
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
Example #15
0
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)
Example #16
0
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."))
Example #17
0
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)
Example #18
0
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')
Example #19
0
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."))
Example #20
0
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.")
Example #21
0
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)
Example #22
0
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."))
Example #23
0
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", )
Example #24
0
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')
Example #25
0
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")
Example #26
0
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')
Example #27
0
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
Example #28
0
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"
            )
Example #29
0
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."))
Example #30
0
 def test_uid_str(self, mock_run_as_root):
     from fabtools.user import create
     create('alice', uid='421')
Example #31
0
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)
Example #32
0
 def test_uid_str(self, mock_run_as_root):
     from fabtools.user import create
     create('alice', uid='421')
Example #33
0
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.')