Cómo detectar las cuentas de usuario inactivas en Linux: guía completa del script

La gestión eficaz de las cuentas de usuario es una piedra angular de la seguridad informática. Entre las diversas medidas para mantener un entorno seguro, el control de las cuentas inactivas o no utilizadas es fundamental. Las cuentas de usuario inactivas en Linux pueden ser potenciales puntos de entrada para actividades maliciosas si no se controlan. Para solucionarlo, vamos a explorar un sólido script Bash que alerta a los administradores cuando las cuentas de usuario permanecen inactivas durante un número determinado de días.

Background

Las cuentas de usuario inactivas en Linux plantean riesgos importantes en cualquier infraestructura informática. Pueden aprovecharse para obtener accesos no autorizados, lo que podría dar lugar a una violación de los datos. Los proveedores de servicios gestionados (MSP) y los profesionales de TI necesitan herramientas eficaces para realizar el seguimiento y la gestión de estas cuentas. Este script sirve como una solución poderosa, ofreciendo alertas automatizadas para cuentas de usuario inactivas en Linux, mejorando la postura general de seguridad.

El script para detectar las cuentas de usuario inactivas en Linux

#!/usr/bin/env bash
#
# Description: Alerts when there is an inactive/unused account that has not logged in for the specified number of days.
#
# Preset Parameter: --daysInactive "90"
#   Alert if account has been inactive for x days.
#
# Preset Parameter: --showDisabled
#   Includes disabled accounts in alert and report.
#
# Preset Parameter: --multilineField "ReplaceMeWithNameOfYourMultilineField"
#   Name of an optional multiline custom field to save the results to.
#
# Preset Parameter: --wysiwygField "ReplaceMeWithNameOfYourWYSIWYGField"
#   Name of an optional WYSIWYG custom field to save the results to.
#
# Preset Parameter: --help
#   Displays some help text.
#
# 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).
#

# These are all our preset parameter defaults. You can set these = to something if you would prefer the script defaults to a certain parameter value.
_arg_daysInactive=
_arg_showDisabled="off"
_arg_multilineField=
_arg_wysiwygField=

# Help text function for when invalid input is encountered
print_help() {
  printf '\n\n%s\n\n' 'Usage: --daysInactive|-d <arg> [--multilineField|-m <arg>] [--wysiwygField|-w <arg>] [--showDisabled] [--help|-h]'
  printf '%s\n' 'Preset Parameter: --daysInactive "90"'
  printf '\t%s\n' "Alert if account has been inactive for x days."
  printf '%s\n' 'Preset Parameter: --showDisabled'
  printf '\t%s\n' "Includes disabled accounts in alert and report."
  printf '%s\n' 'Preset Parameter: --multilineField "ReplaceMeWithNameOfYourMultilineField"'
  printf '\t%s\n' "Name of an optional multiline custom field to save the results to."
  printf '%s\n' 'Preset Parameter: --wysiwygField "ReplaceMeWithNameOfYourWYSIWYGField"'
  printf '\t%s\n' "Name of an optional WYSIWYG custom field to save the results to."
  printf '\n%s\n' 'Preset Parameter: --help'
  printf '\t%s\n' "Displays this help menu."
}

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

# Converts a string input into an HTML table format.
convertToHTMLTable() {
  local _arg_delimiter=" "
  local _arg_inputObject

  # Process command-line arguments for the function.
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --delimiter | -d)
      test $# -lt 2 && echo "[Error] Missing value for the required argument" >&2 && return 1
      _arg_delimiter=$2
      shift
      ;;
    --*)
      echo "[Error] Got an unexpected argument" >&2
      return 1
      ;;
    *)
      _arg_inputObject=$1
      ;;
    esac
    shift
  done

  # Handles missing input by checking stdin or returning an error.
  if [[ -z $_arg_inputObject ]]; then
    if [ -p /dev/stdin ]; then
      _arg_inputObject=$(cat)
    else
      echo "[Error] Missing input object to convert to table" >&2
      return 1
    fi
  fi

  local htmlTable="<table>\n"
  htmlTable+=$(printf '%b' "$_arg_inputObject" | head -n1 | awk -F "$_arg_delimiter" '{
    printf "<tr>"
    for (i=1; i<=NF; i+=1)
      { printf "<th>"$i"</th>" }
    printf "</tr>"
    }')
  htmlTable+="\n"
  htmlTable+=$(printf '%b' "$_arg_inputObject" | tail -n +2 | awk -F "$_arg_delimiter" '{
    printf "<tr>"
    for (i=1; i<=NF; i+=1)
      { printf "<td>"$i"</td>" }
    print "</tr>"
    }')
  htmlTable+="\n</table>"

  printf '%b' "$htmlTable" '\n'
}

# Parses command-line arguments and sets script variables accordingly.
parse_commandline() {
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --daysInactive | --daysinactive | --days | -d)
      test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
      _arg_daysInactive=$2
      shift
      ;;
    --daysInactive=*)
      _arg_daysInactive="${_key##--daysInactive=}"
      ;;
    --multilineField | --multilinefield | --multiline | -m)
      test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
      _arg_multilineField=$2
      shift
      ;;
    --multilineField=*)
      _arg_multilineField="${_key##--multilineField=}"
      ;;
    --wysiwygField | --wysiwygfield | --wysiwyg | -w)
      test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
      _arg_wysiwygField=$2
      shift
      ;;
    --wysiwygField=*)
      _arg_wysiwygField="${_key##--wysiwygField=}"
      ;;
    --showDisabled | --showdisabled)
      _arg_showDisabled="on"
      ;;
    --help | -h)
      _PRINT_HELP=yes die 0
      ;;
    *)
      _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
      ;;
    esac
    shift
  done
}

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

# If dynamic script variables are used replace the commandline arguments with them.
if [[ -n $daysInactive ]]; then
  _arg_daysInactive="$daysInactive"
fi

if [[ -n $includeDisabled && $includeDisabled == "true" ]]; then
  _arg_showDisabled="on"
fi

if [[ -n $multilineCustomFieldName ]]; then
  _arg_multilineField="$multilineCustomFieldName"
fi

if [[ -n $wysiwygCustomFieldName ]]; then
  _arg_wysiwygField="$wysiwygCustomFieldName"
fi

# Check if _arg_daysInactive contains any non-digit characters or is less than zero.
# If any of these conditions are true, display the help text and terminate with an error.
if [[ -z $_arg_daysInactive || $_arg_daysInactive =~ [^0-9]+ || $_arg_daysInactive -lt 0 ]]; then
  _PRINT_HELP=yes die "FATAL ERROR: Days Inactive of '$_arg_daysInactive' is invalid! Days Inactive must be a positive number." 1
fi

# Check if both _arg_multilineField and _arg_wysiwygField are set and not empty.
if [[ -n "$_arg_multilineField" && -n "$_arg_wysiwygField" ]]; then
  # Convert both field names to uppercase to check for equality.
  multiline=$(echo "$_arg_multilineField" | tr '[:lower:]' '[:upper:]')
  wysiwyg=$(echo "$_arg_wysiwygField" | tr '[:lower:]' '[:upper:]')

  # If the converted names are the same, it means both fields cannot be identical.
  # If they are, terminate the script with an error.
  if [[ "$multiline" == "$wysiwyg" ]]; then
    _PRINT_HELP=no die 'FATAL ERROR: Multline Field and WYSIWYG Field cannot be the same name. https://ninjarmm.zendesk.com/hc/en-us/articles/360060920631-Custom-Fields-Configuration-Device-Role-Fields'
  fi
fi

# Retrieves the list of user accounts with UniqueIDs greater than 499 (typically these are all not service accounts) from the local user directory.
userAccounts=$(cut -d ":" -f1,3 /etc/passwd | grep -v "nobody" | awk -F ':' '$2 >= 1000 {print $1}')

# Sets up a header string for the table that will display user account information.
header=$(printf '%s' "Username" ';' "Password Last Set" ';' "Last Logon" ';' "Enabled")

# Initializes an empty string to store information about relevant user accounts.
relevantAccounts=

# Iterates over each user account retrieved earlier.
for userAccount in $userAccounts; do
  # Extracts the last login information for that user, filtering out unnecessary lines and formatting.
  lastLogin=$(last -RF1 "$userAccount" | grep -v "wtmp" | grep "\S" | tr -s " " | cut -f3-7 -d " ")

  # Converts the last login date to seconds since the epoch, for easier date comparison.
  if [[ -n $lastLogin ]]; then
    lastLogin=$(date -d "$lastLogin" +"%s")
  fi

  # Calculates the cutoff date in seconds since the epoch for inactivity comparison, based on the days inactive argument.
  if [[ $_arg_daysInactive -gt 0 ]]; then
    cutoffDate=$(date -d "${_arg_daysInactive} days ago" +"%s")
  fi

  # Retrieves the timestamp when the password was last set for the user account and converts it to a readable format.
  passwordLastSet=$(passwd -S "$userAccount" | cut -f3 -d " ")

  # Checks if the user account is part of the group that defines disabled accounts, setting the 'enabled' variable accordingly.
  unlockedaccount=$(passwd -S "$userAccount" | cut -f2 -d " " | grep -v "L")
  nologin=$(grep "$userAccount" /etc/passwd | cut -d ":" -f7 | grep "nologin")
  if [[ -n $unlockedaccount && -z $nologin ]]; then
    enabled="true"
  else
    enabled="false"
  fi

  # Checks if the account is inactive based on the last login date and cutoff date or if the account should be included regardless of its active status.
  if [[ $_arg_daysInactive == "0" || -z "$lastLogin" || $lastLogin -le $cutoffDate ]]; then
    # Formats the last login date or sets it to "Never" if the user has never logged in.
    if [[ -n $lastLogin ]]; then
      lastLogin=$(date -d "@$lastLogin")
    else
      lastLogin="Never"
    fi

    # Skips adding disabled accounts to the output if they should not be shown.
    if [[ $_arg_showDisabled == "off" && $enabled == "false" ]]; then
      continue
    fi

    # Appends the account information to the 'relevantAccounts' string if it meets the criteria.
    relevantAccounts+=$(printf '%s' '\n' "$userAccount" ';' "$passwordLastSet" ';' "$lastLogin" ';' "$enabled")
    foundInactiveAccounts="true"
  fi
done

# Checks if there are any inactive accounts found.
if [[ $foundInactiveAccounts == "true" ]]; then
  # Formats a nice table for easier viewing
  tableView="$header"
  tableView+=$(printf '%s' '\n' "--------" ';' "-----------------" ';' "----------" ';' "-------")
  tableView+="$relevantAccounts"
  tableView=$(printf '%b' "$tableView" | column -s ';' -t)

  # Output to the activity log
  echo ""
  echo 'WARNING: Inactive accounts detected!'
  echo ""
  printf '%b' "$tableView"
  echo ""
else
  # If no inactive accounts were found, outputs a simple message.
  echo "No inactive accounts detected."
fi

# Checks if there is a multiline custom field set and if any inactive accounts have been found.
if [[ -n $_arg_multilineField && $foundInactiveAccounts == "true" ]]; then
  echo ""
  echo "Attempting to set Custom Field '$_arg_multilineField'..."

  # Formats the relevantAccounts data for the multiline custom field.
  multilineValue=$(printf '%b' "$relevantAccounts" | grep "\S" | awk -F ";" '{ 
      print "Username: "$1
      print "Password Last Set: "$2
      print "Last Logon: "$3
      print "Enabled: "$4 
      print ""
  }')

  # Tries to set the multiline custom field using ninjarmm-cli and captures the output.
  if ! output=$(printf '%b' "$multilineValue" | /opt/NinjaRMMAgent/programdata/ninjarmm-cli set --stdin "$_arg_multilineField" 2>&1); then
    echo "[Error] $output" >&2
    EXITCODE=1
  else
    echo "Successfully set Custom Field '$_arg_multilineField'!"
  fi
fi

# Checks if there is a WYSIWYG custom field set and if any inactive accounts have been found.
if [[ -n $_arg_wysiwygField && $foundInactiveAccounts == "true" ]]; then
  echo ""
  echo "Attempting to set Custom Field '$_arg_wysiwygField'..."

  # Initializes an HTML formatted string with headers and account details.
  htmlObject="$header"
  htmlObject+="$relevantAccounts"

  # Converts the text data to an HTML table format.
  htmlObject=$(convertToHTMLTable --delimiter ';' "$htmlObject")

  # Tries to set the WYSIWYG custom field using ninjarmm-cli and captures the output.
  if ! output=$(echo "$htmlObject" | /opt/NinjaRMMAgent/programdata/ninjarmm-cli set --stdin "$_arg_wysiwygField" 2>&1); then
    echo "[Error] $output" >&2
    EXITCODE=1
  else
    echo "Successfully set Custom Field '$_arg_wysiwygField'!"
  fi
fi

# Checks if an error code is set and exits the script with that code.
if [[ -n $EXITCODE ]]; then
  exit "$EXITCODE"
fi

 

Accede a más de 300 scripts en el Dojo de NinjaOne

Obtén acceso

Análisis detallado

Desglosemos cómo funciona este script para mantener la higiene de las cuentas de usuario en sus sistemas Linux.

Parámetros preestablecidos

El script para detectar las cuentas de usuario inactivas en Linux comienza definiendo los parámetros preestablecidos:

  • –daysInactive: el número de días que una cuenta tiene que estar inactiva para activar una alerta.
  • –showDisabled: si incluir o no las cuentas desactivadas en el informe.
  • –multilineField: el nombre de un campo personalizado multilínea para guardar los resultados.
  • –wysiwygField: el nombre de un campo personalizado WYSIWYG para guardar los resultados.
  • –help: muestra el texto de ayuda.

Análisis sintáctico de argumentos en la línea de comandos

El script para detectar las cuentas de usuario inactivas en Linux emplea una función para analizar los argumentos de la línea de comandos, configurando las variables del script en consecuencia. Si se proporcionan argumentos incorrectos, el script muestra un mensaje de ayuda y sale.

Detección de cuentas de usuario inactivas en Linux

La función principal consiste en detectar las cuentas de usuario inactivas en Linux. Recupera una lista de cuentas de usuario con UniqueID superiores a 499 (normalmente cuentas que no son de servicio) del directorio de usuarios local. A continuación, comprueba la última fecha de inicio de sesión de cada cuenta y la compara con la fecha actual menos el parámetro –daysInactive. Se marcan las cuentas que cumplen los criterios de inactividad.

Generación de informes

Si se detectan cuentas de usuario inactivas en Linux, el script genera una tabla formateada que muestra:

  • Nombre de usuario
  • Última contraseña establecida
  • Último inicio de sesión
  • Estado activado

Integración de campos personalizados

El script para detectar cuentas de usuario inactivas en Linux puede guardar los resultados en campos personalizados especificados. Formatea los datos en texto plano o HTML, dependiendo de si se guardan en un campo multilínea o WYSIWYG, respectivamente.

Posibles casos de uso

Pensemos en un administrador de TI que gestiona los servidores Linux de una empresa. Las auditorías periódicas de las cuentas de usuario forman parte del protocolo de seguridad. El administrador programa este script para que se ejecute semanalmente. Una semana, el script detecta varias cuentas inactivas que llevan más de 90 días sin conectarse. Tras revisar el informe, el administrador decide desactivar estas cuentas hasta una nueva verificación, mitigando así los posibles riesgos de seguridad.

Comparaciones

Otros métodos para lograr resultados similares podrían incluir la auditoría manual o el uso de herramientas de gestión de usuarios más complejas. La auditoría manual requiere mucho tiempo y es propensa a errores humanos. Las herramientas avanzadas pueden ser costosas y requerir una instalación y configuración exhaustivas. Este script para detectar las cuentas de usuario inactivas en Linux ofrece una solución sencilla y rentable, lo que lo convierte en un excelente término medio.

FAQ

  1. ¿Y si quiero comprobar la inactividad durante un número diferente de días? Ajusta el parámetro –daysInactive en consecuencia. Por ejemplo, utiliza –daysInactive 60 para comprobar 60 días de inactividad.
  2. ¿Puedo excluir del informe las cuentas desactivadas? Sí, el script para detectar cuentas de usuario inactivas en Linux incluye el parámetro –showDisabled para alternar la inclusión de cuentas deshabilitadas.
  3. ¿Cómo guardo los resultados en un campo personalizado? Especifica los nombres de los campos personalizados mediante los parámetros –multilineField o –wysiwygField.
  4. ¿Qué ocurre si proporciono parámetros incorrectos? El script para detectar cuentas de usuario inactivas en Linux mostrará un mensaje de ayuda y saldrá, asegurándose de que proporcionas los datos correctos.

Implicaciones

Supervisar regularmente las cuentas de usuario inactivas en Linux tiene profundas implicaciones para la seguridad informática. Ayuda a impedir el acceso no autorizado, reduce la superficie de ataque y garantiza el cumplimiento de las políticas de seguridad. Utilizando este script, los administradores pueden automatizar un aspecto crucial de la gestión de cuentas de usuario, mejorando la seguridad y la eficacia generales.

Recomendaciones

  • Programa la ejecución del script para detectar cuentas de usuario inactivas en Linux a intervalos regulares, como semanal o mensualmente.
  • Revisa rápidamente el informe de cuentas inactivas y toma las medidas oportunas.
  • Utiliza la función de campos personalizados para integrar los resultados con tus herramientas de gestión de TI existentes.

Reflexiones finales

Gestionar eficazmente las cuentas de usuario inactivas es vital para mantener la seguridad informática. Este script para detectar cuentas de usuario inactivas en Linux ofrece una solución práctica y automatizada que permite a los administradores adelantarse a las posibles amenazas contra la seguridad. Si incorporas esta herramienta a tus protocolos de seguridad, podrás garantizar un entorno informático más seguro y conforme a las normas.

NinjaOne ofrece soluciones integrales de gestión de TI que se integran perfectamente con scripts como éste, proporcionando una funcionalidad mejorada y una gestión centralizada para su infraestructura de TI. Adopta la automatización y las prácticas de seguridad robustas con NinjaOne para proteger tu organización con eficacia.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Obtén más información sobre NinjaOne Endpoint Management, echa un vistazo a un tour en vivoo tu prueba gratuita de la plataforma NinjaOne.

Categorías:

Quizá también te interese…

Ver demo×
×

¡Vean a NinjaOne en acción!

Al enviar este formulario, acepto la política de privacidad de NinjaOne.

Términos y condiciones de NinjaOne

Al hacer clic en el botón «Acepto» que aparece a continuación, estás aceptando los siguientes términos legales, así como nuestras Condiciones de uso:

  • Derechos de propiedad: NinjaOne posee y seguirá poseyendo todos los derechos, títulos e intereses sobre el script (incluidos los derechos de autor). NinjaOne concede al usuario una licencia limitada para utilizar el script de acuerdo con estos términos legales.
  • Limitación de uso: solo podrás utilizar el script para tus legítimos fines personales o comerciales internos, y no podrás compartirlo con terceros.
  • Prohibición de republicación: bajo ninguna circunstancia está permitido volver a publicar el script en ninguna biblioteca de scripts que pertenezca o esté bajo el control de cualquier otro proveedor de software.
  • Exclusión de garantía: el script se proporciona «tal cual» y «según disponibilidad», sin garantía de ningún tipo. NinjaOne no promete ni garantiza que el script esté libre de defectos o que satisfaga las necesidades o expectativas específicas del usuario.
  • Asunción de riesgos: el uso que el usuario haga del script corre por su cuenta y riesgo. El usuario reconoce que existen ciertos riesgos inherentes al uso del script, y entiende y asume cada uno de esos riesgos.
  • Renuncia y exención: el usuario no hará responsable a NinjaOne de cualquier consecuencia adversa o no deseada que resulte del uso del script y renuncia a cualquier derecho o recurso legal o equitativo que pueda tener contra NinjaOne en relación con su uso del script.
  • CLUF: si el usuario es cliente de NinjaOne, su uso del script está sujeto al Contrato de Licencia para el Usuario Final (CLUF).