How to Enable User Accounts in Linux Using an Automated Bash Script

Managing user accounts efficiently is a crucial task for IT professionals and Managed Service Providers (MSPs). A significant part of this involves enabling and disabling user accounts as needed. This blog post will discuss a Bash script that simplifies the process of enabling user accounts in Linux systems. By understanding and utilizing this script, IT professionals can streamline user management, enhance system security, and ensure smooth operations.

Background

User account management in Linux is a fundamental responsibility for system administrators. Ensuring that only authorized users have access to system resources is vital for maintaining security and operational integrity. This Bash script is designed to enable user accounts by changing their login shell to /bin/bash and unlocking the account. Such automation can save time, reduce human error, and enforce consistent security practices across multiple systems.

The Script:

#!/usr/bin/env bash

# Description: Enables a user account by changing its shell to /bin/bash and unlocking the account.
#
# Release Notes: Initial Release
# By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
# Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
# Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
# Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
# Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
# Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
# Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#
# Below are all the valid parameters for this script.
#
# Preset Parameter: "ReplaceMeWithUsernameToEnable"
#   Username of the user you would like to enable.
#

# Help text function for when invalid input is encountered
print_help() {
  printf '\n### Below are all the valid parameters for this script. ###\n'
  printf '\nPreset Parameter: "ReplaceMeWithUsernameToEnable" \n'
  printf '\t%s\n' "Username of the user you would like to enable."
}

# Determines whether or not help text is nessessary and routes the output to stderr
die() {
  local _ret="${2:-1}"
  echo "$1" >&2
  test "${_PRINT_HELP:-no}" = yes && print_help >&2
  exit "${_ret}"
}

_arg_userToEnable=

# Grabbing the parameters and parsing through them.
parse_commandline() {
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --help | -h)
      _PRINT_HELP=yes die 0
      ;;
    --*)
      _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
      ;;
    *)
      if [[ -z $_arg_userToEnable ]]; then
        _arg_userToEnable=$1
      else
        _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1' but user '$_arg_userToEnable' was already specified!" 1
      fi
      ;;
    esac
    shift
  done
}

# Parse the command-line arguments passed to the script.
parse_commandline "$@"

if [[ -n $usernameToEnable ]]; then
  _arg_userToEnable="$usernameToEnable"
fi

# Check if the username to disable is empty and display an error if it is.
if [[ -z $_arg_userToEnable ]]; then
  _PRINT_HELP=yes die "[Error] The username of the user you would like to disable is required!'" 1
fi

# Validate the username to ensure it only contains lowercase letters, digits, hyphens, and underscores.
if [[ ! $_arg_userToEnable =~ ^[a-z0-9_-]+$ ]]; then
  _PRINT_HELP=no die "[Error] Invalid characters detected in '$_arg_userToEnable' usernames can only have a-z, 0-9 or -, _ characters!" 1
fi

# Search for the user in the /etc/passwd file.
passwdEntry=$(grep -w "$_arg_userToEnable" /etc/passwd)
if [[ -z $passwdEntry ]]; then
  _PRINT_HELP=no die "[Error] User '$_arg_userToEnable' does not exist." 1
fi

# Check to see if account is expired
accountExpiration=$(chage -l "$_arg_userToEnable" | grep "Account expires" | grep -v 'never' | cut -d ":" -f2 | xargs)
if [[ -n $accountExpiration ]]; then
  accountExpirationSeconds=$(date -d "$accountExpiration" +"%s")
  
  currentTime=$(date +"%s")
  # Warn if account is expired
  if [[ $accountExpirationSeconds -le $currentTime ]]; then
    echo "WARNING: The account for '$_arg_userToEnable' is currently expired as of '$accountExpiration'. You may need to set a new expiration date."
  fi
fi

noLogin=$(grep -w "$_arg_userToEnable" /etc/passwd | grep "nologin")
unlockedaccount=$(passwd -S "$_arg_userToEnable" | cut -f2 -d " " | grep -v "L")
if [[ -z $noLogin && -n $unlockedaccount ]]; then
  _PRINT_HELP=no die "[Error] User '$_arg_userToEnable' is already enabled." 1
fi

if [[ -f /bin/bash ]]; then
  preferredShell="/bin/bash"
elif [[ -f /bin/sh ]]; then
  preferredShell="/bin/sh"
fi

# Attempt to change the shell of the user to /bin/bash to enable login capabilities.
if ! usermod "$_arg_userToEnable" -s "$preferredShell"; then
  _PRINT_HELP=no die "[Error] Failed to change the shell for '$_arg_userToEnable' to '$preferredShell'." 1
fi

# Attempt to unlock the user account using usermod.
if ! usermod -U "$_arg_userToEnable"; then
  _PRINT_HELP=no die "[Error] Failed to unlock '$_arg_userToEnable' using usermod." 1
fi

# Check if the user has been successfully enabled by confirming 'nologin' is no longer set.
enabledUser=$(grep -w "$_arg_userToEnable" /etc/passwd | grep -v "nologin")
if [[ -n $enabledUser ]]; then
  echo "Successfully enabled '$_arg_userToEnable'."
else
  _PRINT_HELP=no die "[Error] Failed to enable '$_arg_userToEnable'." 1
fi

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The provided Bash script accomplishes its task through several well-defined steps. Let’s break down each part of the script to understand its functionality:

1. Help Text and Error Handling Functions:

  • The script begins by defining functions to display help text (print_help) and handle errors (die). These functions ensure that the user is informed about the correct usage of the script and can troubleshoot issues effectively.

2. Parameter Parsing:

  • The parse_commandline function processes the script’s command-line arguments. It checks for the –helpflag, unexpected arguments, and ensures that only one username is provided.

3. Username Validation:

  • The script validates the provided username to ensure it only contains lowercase letters, digits, hyphens, and underscores. This step prevents potential security issues arising from invalid characters.

4. User Existence Check:

  • The script checks if the user exists in the /etc/passwd file. If the user does not exist, it exits with an error message.

5. Account Expiry Check:

  • The script uses the chage command to determine if the account is expired. If expired, it warns the user, though it continues to attempt enabling the account.

6. Login Shell and Account Status Check:

  • It verifies if the user’s login shell is set to nologin and if the account is already unlocked. If the user is already enabled, it exits with an error.

7. Shell Selection:

  • The script checks for the existence of /bin/bash and /bin/sh, preferring /bin/bash if available.

8. Changing the Shell and Unlocking the Account:

  • The script attempts to change the user’s login shell to the preferred shell and unlock the account using the usermod command.

9. Final Verification:

  • It verifies if the user has been successfully enabled by checking that nologin is no longer set. If successful, it prints a confirmation message.

Potential Use Cases

Imagine a scenario where an IT professional manages a large team with frequent changes in personnel. An employee returning from extended leave needs their account re-enabled. Using this script, the IT professional can quickly enable the account without manually navigating through multiple commands, ensuring the process is both swift and error-free.

Comparisons

This script provides a streamlined, automated approach to enabling user accounts compared to manual methods. Manually enabling a user involves multiple steps: editing /etc/passwd, changing the shell, and unlocking the account. Each step is prone to human error. In contrast, this script encapsulates all these steps into a single, repeatable process, enhancing reliability and efficiency.

FAQs

1) What happens if the username is invalid?

The script exits with an error message indicating that the username contains invalid characters.

2) Can this script be used to enable multiple users at once?

No, the script is designed to enable one user at a time to ensure accuracy and security.

3) What if the preferred shell /bin/bash is not available?

The script falls back to using /bin/sh if /bin/bash is not found.

4) Does the script handle all account-related errors?

The script handles common errors such as invalid usernames, non-existent users, and already enabled accounts.

Implications

Enabling user accounts securely is critical for maintaining system integrity. Automated scripts like this reduce the risk of human error, ensuring that accounts are enabled correctly and promptly. This contributes to overall system security and operational efficiency, which are paramount in any IT environment.

Recommendations

When using this script, follow these best practices:

  • Test in a Controlled Environment: Before deploying the script in a production environment, test it in a staging environment to ensure it behaves as expected.
  • Regular Audits: Periodically review user accounts and the script’s functionality to ensure compliance with security policies.
  • Documentation: Keep detailed documentation of any customizations made to the script to facilitate future maintenance.

Final Thoughts

Effective user account management is essential for maintaining a secure and efficient IT environment. This Bash script offers a reliable and automated solution for enabling user accounts in Linux. For organizations looking to streamline their IT operations further, tools like NinjaOne can provide comprehensive management solutions, enhancing efficiency and security across the board.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).