This comprehensive guide delves into the crucial terminal commands needed for managing users in a Linux environment. It covers creating and deleting user accounts, managing user groups, setting file permissions, monitoring user activities, and enforcing security measures. Whether you're a system administrator or a Linux user, this article equips you with the necessary skills to effectively control user access and maintain system security through detailed explanations and practical examples.

Linux User Control: Terminal Commands You Need to Know

  • Last Modified: 16 Apr, 2024

Explore essential terminal commands for effective Linux user management, including user creation, permission handling, and security practices.


Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


Introduction to Linux User Management

Linux stands out in the operating systems landscape for its robustness, flexibility, and excellent security features. Central to harnessing these capabilities is effective user management, which involves handling user accounts, groups, permissions, and access rights through the terminal. This control is crucial for system security and efficiency, especially in multi-user or networked environments.

In this guide, we’ll explore the key terminal commands and practices essential for Linux user management. Whether you’re a new system administrator or a Linux user looking to deepen your understanding of system internals, this article will equip you with the foundational skills and advanced techniques needed to manage users effectively.

Creating and Deleting Users

via GIPHY

### Creating Users

One of the primary tasks in user management is the creation of user accounts. Linux offers several commands for this, but the most commonly used are useradd and adduser.

  • useradd Command: The useradd command creates a new user account using the default settings. The basic syntax to create a new user named john is:

    useradd john
    

    This command adds John to the system with a default home directory and shell. To customize the account at creation, you can specify options like a custom home directory (-d) and a specific shell (-s):

    useradd -d /home/john -s /bin/bash john
    

    This sets John’s home directory to /home/john and his default shell to bash.

  • adduser Command: While useradd is more script-friendly, adduser is more interactive and user-friendly, especially for beginners. It prompts for additional user information such as password, full name, and other details:

    adduser john
    

    The command guides you through setting up the account and even creates the home directory with proper permissions.

Deleting Users

To remove a user, the userdel command is used. This command removes the user’s account but does not, by default, remove their home directory or email spool:

userdel john

To fully remove the user along with their home directory and email spool, use the -r option:

userdel -r john

Advanced Bash Script: User Management Automation

For system administrators who frequently need to create and delete users, automating these tasks can save time and reduce errors. Below is an advanced Bash script that checks if a user exists, creates the user with specific options if they do not, or deletes the user if they do.

  • Script Filename: user_management.sh
#!/bin/bash

# Function to create a user with a home directory and a specific shell
create_user() {
    if id "$1" &>/dev/null; then
        echo "User $1 already exists."
    else
        useradd -d /home/$1 -s /bin/bash $1
        passwd $1
        echo "User $1 has been created with a home directory and bash shell."
    fi
}

# Function to delete a user and their home directory
delete_user() {
    if id "$1" &>/dev/null; then
        userdel -r $1
        echo "User $1 and their home directory have been deleted."
    else
        echo "User $1 does not exist."
    fi
}

# Main logic
case "$2" in
    create)
        create_user $1
        ;;
    delete)
        delete_user $1
        ;;
    *)
        echo "Usage: $0 username create|delete"
        exit 1
        ;;
esac

This script can be executed with two arguments, a username and an action (create or delete). It checks if the user exists, creates them with a custom home directory and shell if they don’t, or deletes them if they do.

User Customization and Modification

via GIPHY

Effective management of user accounts extends beyond simple creation or deletion. The ability to customize and modify user accounts according to specific needs is crucial for maintaining an organized and efficient Linux environment. This involves setting user passwords, changing login shells, and updating user information, which can significantly enhance the user experience and system security.

Modifying User Accounts

Changes to existing user accounts are handled through the usermod command. This powerful utility allows administrators to modify users’ login names, home directories, and group affiliations among other settings.

  • Changing Login Names and Home Directories: If you need to change a user’s login name and simultaneously move their home directory, you can use the usermod command with the -l (login name) and -d (home directory) options along with -m to move the contents of the old home directory to the new one:

    usermod -l newjohn -d /newhome/john -m john
    

    This command changes the username from john to newjohn and relocates the home directory to /newhome/john, transferring all existing files and settings.

  • Adding Users to Additional Groups: To add a user to additional groups without removing them from their current groups, use the -aG options:

    usermod -aG sudo,docker john
    

    This command adds John to both the sudo and docker groups, enhancing his system permissions without affecting his existing group memberships.

Managing User Passwords and Shells

Proper management of user passwords and login shells is fundamental to securing and customizing user environments.

  • Setting and Changing Passwords: The passwd command is used to set or change a user’s password, a crucial task in maintaining security:

    passwd john
    

    This command will prompt you to enter a new password for John, and it’s recommended to encourage users to choose strong, complex passwords.

  • Changing User Shells: The choice of shell can affect how a user interacts with the Linux system. To change a user’s default shell, use the chsh (change shell) command:

    chsh -s /usr/bin/zsh john
    

    This sets Zsh as the default shell for John, which might be preferred for its user-friendly features and advanced customization options.

Advanced Bash Script: User Customization Automation

via GIPHY

To streamline the process of modifying user accounts and setting up environment preferences, a more advanced Bash script can be employed. This script allows for quick modifications and setups, including changing shells and managing passwords.

  • Script Filename: modify_user.sh
#!/bin/bash

# Function to update user's shell
update_shell() {
    if [ $# -ne 2 ]; then
        echo "Usage: update_shell username shell_path"
        return 1
    fi
    chsh -s $2 $1
    echo "Shell updated for $1 to $2"
}

# Function to change user's password
change_password() {
    if [ $# -ne 1 ]; then
        echo "Usage: change_password username"
        return 1
    fi
    passwd $1
}

# Function to move user's home directory
move_home() {
    if [ $# -ne 2 ]; then
        echo "Usage: move_home username new_home_path"
        return 1
    fi
    usermod -d $2 -m $1
    echo "Home directory moved for $1 to $2"
}

# Main logic for handling different actions
case "$1" in
    shell)
        update_shell $2 $3
        ;;
    password)
        change_password $2
        ;;
    movehome)
        move_home $2 $3
        ;;
    *)
        echo "Usage: $0 {shell|password|movehome} args"
        exit 1
        ;;
esac

This script enhances administrative efficiency by automating common tasks such as updating shells, changing passwords, and moving home directories. It uses functions to encapsulate the logic for each task, making it reusable and easy to maintain.

Managing User Groups

via GIPHY

In Linux, groups are a fundamental aspect of managing user permissions and access control. Groups allow system administrators to assign permissions to multiple users at once, which simplifies the management of permissions and can enhance security by limiting access based on group membership.

Understanding User Groups

Each user in Linux can belong to one primary group and multiple secondary groups. The primary group is usually used for personal files, while secondary groups grant permissions for collaborative tasks or accessing shared resources.

via GIPHY

  • Creating Groups: To create a new group, use the groupadd command. For example, to create a group named developers:

    groupadd developers
    

    This command sets up a new group without any members initially.

  • Deleting Groups: If a group is no longer needed, it can be removed with the groupdel command:

    groupdel developers
    

    Ensure that no files are owned by the group before deleting it, as this could lead to permission issues.

Modifying Group Memberships

Managing group memberships is crucial for controlling which users have access to specific system resources.

  • Adding a User to a Group: To add a user to one or more groups, you can use the usermod command with the -aG options, which stand for ‘append to group’:

    usermod -aG developers john
    

    This command adds the user john to the developers group without affecting his membership in other groups.

  • Removing a User from a Group: Removing a user from a group isn’t directly supported by a single command in standard distributions, but you can use gpasswd or edit the /etc/group file manually:

    gpasswd -d john developers
    

    This removes John from the developers group.

Advanced Bash Script: Group Management Automation

For system administrators managing multiple users and groups, automation is key. Below is an advanced Bash script that facilitates group management by creating, deleting, and modifying group memberships.

  • Script Filename: group_management.sh
#!/bin/bash

# Function to create a group
create_group() {
    if getent group $1 > /dev/null 2>&1; then
        echo "Group $1 already exists."
    else
        groupadd $1
        echo "Group $1 created."
    fi
}

# Function to delete a group
delete_group() {
    if getent group $1 > /dev/null 2>&1; then
        groupdel $1
        echo "Group $1 deleted."
    else
        echo "Group $1 does not exist."
    fi
}

# Function to modify group membership
modify_membership() {
    case $2 in
        add)
            usermod -aG $1 $3
            echo "User $3 added to group $1."
            ;;
        remove)
            gpasswd -d $3 $1
            echo "User $3 removed from group $1."
            ;;
        *)
            echo "Usage: modify_membership groupname {add|remove} username"
            return 1
            ;;
    esac
}

# Main logic
case "$1" in
    create)
        create_group $2
        ;;
    delete)
        delete_group $2
        ;;
    modify)
        modify_membership $2 $3 $4
        ;;
    *)
        echo "Usage: $0 {create|delete|modify} args"
        exit 1
        ;;
esac

This script provides a comprehensive solution for managing groups. It includes functions for creating and deleting groups and modifying user memberships within those groups. The script checks for the existence of the group before attempting to create or delete it, preventing errors and ensuring efficient management.

Advanced Permissions and Ownership

In Linux, managing file permissions and ownership is crucial for securing access to system files and directories. Proper understanding and handling of these permissions allow administrators to protect sensitive data and ensure that users have appropriate access to resources.

Understanding Linux Permissions

Permissions in Linux are managed at three levels: for the owner, the group, and others. Each file and directory has associated permissions that dictate how it can be accessed. These permissions include read (r), write (w), and execute (x).

  • Changing File Permissions (chmod): The chmod command is used to change the access permissions of files and directories. For instance, to give the owner full permissions, the group read and execute permissions, and others no permissions on a file, you would use:

    chmod 750 filename
    

    Here, 7 (binary 111) allows the owner read, write, and execute permissions; 5 (binary 101) allows the group read and execute permissions; and 0 (binary 000) gives others no permissions.

  • Changing Ownership (chown): The ownership of a file can be changed using the chown command. To change the owner of a file to john and the group to developers, you would use:

    chown john:developers filename
    

    This command changes both the user and group ownership of filename to John and developers, respectively.

Special Permissions: setuid, setgid, and Sticky Bit

Linux also supports special kinds of permissions that affect executable files and directories.

  • setuid (Set User ID): When setuid permission is set on an executable file, the file is executed with the privileges of the file’s owner, not the user who runs it. This is useful for allowing users to perform tasks like changing their passwords, which typically require administrative privileges.

    chmod u+s /usr/bin/passwd
    

    This applies the setuid permission to the passwd program, allowing it to run with root privileges.

  • setgid (Set Group ID): Similar to setuid, setgid affects how files and directories are accessed based on the group ownership. When setgid is applied to a directory, new files created within the directory inherit the directory’s group, and new directories inherit the setgid bit.

    chmod g+s /path/to/directory
    

    This command ensures that all files created within the specified directory inherit its group ownership.

  • Sticky Bit: The sticky bit is used primarily on directories. It restricts file deletion so that only the file’s owner, the directory’s owner, or root can delete files within the directory.

    chmod +t /tmp
    

    This example sets the sticky bit on the /tmp directory, preventing users from deleting each other’s files.

Advanced Bash Script: Permissions Management Automation

via GIPHY

For a system administrator, managing permissions for multiple files and directories efficiently is crucial. Here’s an advanced script that automates the management of permissions and ownership.

  • Script Filename: permissions_management.sh
#!/bin/bash

# Function to change permissions
change_permissions() {
    chmod $1 $2
    echo "Permissions for $2 set to $1."
}

# Function to change ownership
change_ownership() {
    chown $1:$2 $3
    echo "Ownership for $3 changed to $1:$2."
}

# Function to apply special permissions
apply_special_permissions() {
    case $1 in
        setuid)
            chmod u+s $2
            echo "Setuid has been set for $2."
            ;;
        setgid)
            chmod g+s $2
            echo "Setgid has been set for $2."
            ;;
        sticky)
            chmod +t $2
            echo "Sticky bit has been set for $2."
            ;;
        *)
            echo "Invalid option: $1. Use setuid, setgid, or sticky."
            return 1
            ;;
    esac
}

# Main logic for script usage
case "$1" in
    perm)
        change_permissions $2 $3
        ;;
    own)
        change_ownership $2 $3 $4
        ;;
    spec)
        apply_special_permissions $2 $3
        ;;
    *)
        echo "Usage: $0 {perm|own|spec} options"
        exit 1
        ;;
esac

This script facilitates the management of standard and special permissions along with ownership changes. It includes functions to change permissions, change ownership, and apply special permissions like setuid, setgid, and the sticky bit.

Monitoring User Activities and System Access

Monitoring user activities and system access is a critical aspect of system administration in Linux. This process involves tracking user logins, system usage, and managing resources to ensure optimal performance and security. Effective monitoring can help in detecting unauthorized access and ensuring that system resources are used appropriately.

Tracking User Logins

One of the primary methods of monitoring involves checking who is currently logged into the system and reviewing past login activities.

  • who Command: The who command displays a list of all users currently logged into the system. It provides details such as the username, terminal line, login time, and more.

    who
    

    This simple command is often the first step in monitoring current user activities on a server.

  • last Command: For reviewing past logins, the last command is invaluable. It pulls information from the /var/log/wtmp file, which records all logins and logouts.

    last
    

    This command lists the recent sessions, showing usernames, terminal lines, login times, logout times, and the duration of each session.

Managing User Processes

In addition to tracking logins, managing how users consume system resources is another key area of system monitoring.

  • top and htop Commands: Both top and htop commands provide real-time views of running system processes. htop is an enhanced version that offers a more user-friendly and visually appealing interface.

    top
    
    htop
    

    These commands display information about processor usage, memory usage, and running processes, and they can be very useful for monitoring system health and user activity.

  • ps Command: The ps command shows a snapshot of current processes. It can be used to see what processes a particular user is running:

    ps -u username
    

    This command lists all processes currently being run by username, which is helpful for monitoring specific user activities.

Limiting User Resources

To ensure that no single user consumes too many system resources, Linux provides mechanisms for setting limits on user usage.

  • ulimit Command: The ulimit command is used to set or report user process resource limits. These limits can control aspects like CPU time, file sizes, and the number of processes that can be run.

    ulimit -u 100 -n 1024
    

    This sets the maximum number of processes per user to 100 and the maximum number of open files to 1024.

Advanced Bash Script: System Monitoring Automation

via GIPHY

To facilitate the management and monitoring of user activities, an advanced Bash script can be developed. This script can automate checking user logins and managing resources.

  • Script Filename: system_monitoring.sh
#!/bin/bash

# Function to display currently logged-in users
show_logged_in_users() {
    who
}

# Function to display last logged-in users
show_last_logins() {
    last -n 10
}

# Function to check resource usage by user
check_user_resources() {
    top -u $1
}

# Main logic for handling monitoring tasks
case "$1" in
    current)
        show_logged_in_users
        ;;
    history)
        show_last_logins
        ;;
    resources)
        check_user_resources $2
        ;;
    *)
        echo "Usage: $0 {current|history|resources} [username]"
        exit 1
        ;;
esac

This script provides a straightforward interface for key monitoring tasks such as viewing currently logged-in users, checking recent login history, and monitoring resource usage for a specific user.

With the tools and scripts described, Linux administrators can effectively oversee user activities and system access, enhancing both system performance and security.

Security Practices for User Management

via GIPHY

In Linux systems, securing user accounts is paramount to safeguarding system integrity and data. This section explores essential security measures for user management, including password policies, account restrictions, and using tools to monitor for unauthorized access.

Enhancing Password Security

Proper password management is critical to preventing unauthorized system access. Linux provides several tools and configurations to strengthen password security.

  • Setting Strong Password Policies: Using the passwd command, system administrators can enforce strong password policies. The chage tool can be used to manage password aging policies to require users to change passwords regularly.

    passwd john
    chage -M 90 -m 7 -W 14 john
    

    This sets John’s password and configures it to expire every 90 days, with a minimum password age of 7 days and a warning issued 14 days before expiration.

  • Locking and Unlocking User Accounts: If a user account should be temporarily disabled without deleting it, the usermod command can be used to lock and unlock accounts.

    usermod -L john  # Lock John's account
    usermod -U john  # Unlock John's account
    

    Locking an account disables its password, preventing the user from logging in.

Securing User Files and Directories

Setting appropriate permissions and ownership is crucial for protecting sensitive data.

  • File Permissions and Ownership: As covered earlier, using chmod and chown commands helps ensure that only authorized users have access to critical files and directories.

    chmod 700 /home/john/private
    chown john:john /home/john/private
    

    This sets John’s private directory to be accessible only by him, providing a higher level of security for sensitive information.

Monitoring for Unauthorized Access

Continuous monitoring for unauthorized access is essential for maintaining system security.

  • Using System Logs: Logs provide vital information about system activities and potential security breaches. Regularly checking log files, such as /var/log/auth.log, can help detect unauthorized access attempts.

    grep 'Failed' /var/log/auth.log
    

    This command filters the authentication log for failed login attempts, which can indicate attempted security breaches.

Advanced Bash Script: Security Monitoring Automation

Automating security monitoring and configurations can greatly enhance the efficiency and responsiveness of security practices. Below is an advanced Bash script that automates checking for failed login attempts and managing password policies.

  • Script Filename: security_enforcement.sh
#!/bin/bash

# Function to check for failed login attempts
check_failed_logins() {
    grep 'Failed' /var/log/auth.log
}

# Function to set password policies for a user
set_password_policy() {
    passwd $1
    chage -M 90 -m 7 -W 14 $1
    echo "Password policies set for $1."
}

# Function to lock or unlock a user account
modify_account_status() {
    if [ "$2" == "lock" ]; then
        usermod -L $1
        echo "Account $1 locked."
    elif [ "$2" == "unlock" ]; then
        usermod -U $1
        echo "Account $1 unlocked."
    else
        echo "Invalid option: $2. Use lock or unlock."
        return 1
    fi
}

# Main logic for handling security tasks
case "$1" in
    monitor)
        check_failed_logins
        ;;
    policy)
        set_password_policy $2
        ;;
    account)
        modify_account_status $2 $3
        ;;
    *)
        echo "Usage: $0 {monitor|policy|account} [username] [lock|unlock]"
        exit 1
        ;;
esac

This script provides tools for essential security functions, including monitoring for failed login attempts, setting password policies, and modifying account statuses to lock or unlock user accounts.

Frequently Asked Questions (FAQ)

1. What is the difference between useradd and adduser?

useradd is a low-level utility for adding users which sticks closely to the defaults unless specifically changed through options. It is more script-friendly. adduser, on the other hand, is a higher-level utility that is more interactive and user-friendly, usually preferred for manual user creation as it prompts for additional details.

2. How do I view all the groups a user is a part of in Linux?

You can use the groups command followed by the username to view all the groups a user belongs to:

groups john

This command will list all the groups that John is a member of.

3. What is the significance of the sticky bit in Linux?

The sticky bit is a permission setting that when set on a directory, only allows file owners, the directory owner, or root to delete or rename files within that directory. It’s commonly used in directories like /tmp to prevent users from deleting or renaming each other’s temporary files.

4. How can I limit the number of files a user can open in Linux?

You can use the ulimit command to set limits on the resources available to users, such as the number of open files:

ulimit -n 1024  # Sets the max number of open files to 1024

5. Can I change a user’s password without knowing the current one?

Yes, as a root user or with sudo privileges, you can change another user’s password without knowing the current one using the passwd command followed by the username:

sudo passwd john

You will then be prompted to enter a new password for the user.

What Did We Learn?

In this comprehensive guide on Linux user management, we explored a variety of essential terminal commands and practices that are vital for system administrators. Here are the key takeaways:

  • User and Group Management: We learned how to create, delete, and modify user accounts and groups, which is foundational in managing access and permissions in a Linux environment.

  • Permission Handling: We delved into setting file permissions, ownership, and special permissions like setuid, setgid, and the sticky bit. These are critical for securing system resources and ensuring appropriate access levels.

  • System Monitoring: Techniques for monitoring user activities and managing system resources were discussed, which help in maintaining system performance and detecting potential unauthorized access.

  • Security Practices: We covered strategies to enhance password security, lock and unlock user accounts, and monitor system logs for failed login attempts. These practices are essential for maintaining robust security standards.

  • Automation with Scripts: Advanced Bash scripts were introduced to automate common tasks related to user and group management, permission changes, and security monitoring. Automation aids in reducing administrative overhead and minimizing human errors.


Images by

...
Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


See Also

comments powered by Disqus