{"id":353789,"date":"2024-09-17T12:45:39","date_gmt":"2024-09-17T12:45:39","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/deshabilitar-cuentas-de-usuario\/"},"modified":"2024-10-13T19:07:20","modified_gmt":"2024-10-13T19:07:20","slug":"deshabilitar-cuentas-de-usuario","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/deshabilitar-cuentas-de-usuario\/","title":{"rendered":"Gu\u00eda completa para deshabilitar cuentas de usuario en Linux para profesionales de TI"},"content":{"rendered":"<p>La gesti\u00f3n de cuentas de usuario es un aspecto crucial de la administraci\u00f3n de sistemas, especialmente cuando se trata de garantizar la seguridad y la integridad de un entorno Linux. <strong>Deshabilitar cuentas de usuario<\/strong> que ya no se utilizan o que pueden estar en peligro es una pr\u00e1ctica habitual entre los profesionales de TI y los <a href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\/\" target=\"_blank\" rel=\"noopener\">proveedores de servicios gestionados (MSP)<\/a>.<\/p>\n<p>Este post explora un script completo dise\u00f1ado para deshabilitar cuentas de usuario en Linux, proporcionando una comprensi\u00f3n en profundidad de su funcionalidad, casos de uso y mejores pr\u00e1cticas.<\/p>\n<h2>Comprender la importancia de la gesti\u00f3n de cuentas de usuario<\/h2>\n<p>En cualquier infraestructura inform\u00e1tica, la gesti\u00f3n de las cuentas de usuario es primordial para <a href=\"https:\/\/www.ninjaone.com\/es\/blog\/lista-de-verificacion-de-seguridad-de-ti\/\" target=\"_blank\" rel=\"noopener\">mantener la seguridad<\/a> y la <a href=\"https:\/\/www.ninjaone.com\/es\/eficiencia\/\" target=\"_blank\" rel=\"noopener\">eficacia<\/a> operativa. El acceso no autorizado o el uso indebido de las cuentas de usuario pueden provocar filtraciones de datos, p\u00e9rdida de informaci\u00f3n confidencial y posibles ca\u00eddas del sistema. Por lo tanto, deshabilitar cuentas de usuario inactivas o comprometidas es una medida proactiva para salvaguardar el sistema.<\/p>\n<h2>Contexto<\/h2>\n<p>El script que estamos examinando est\u00e1 dise\u00f1ado para deshabilitar una cuenta de usuario espec\u00edfica cambiando su shell de inicio de sesi\u00f3n a \/sbin\/nologiny bloqueando la cuenta. Este proceso impide que el usuario inicie sesi\u00f3n, al tiempo que conserva la cuenta para posibles reactivaciones o auditor\u00edas. Este m\u00e9todo es preferible a la eliminaci\u00f3n total, ya que mantiene intactos el historial de la cuenta y los archivos relacionados.<\/p>\n<h2>El script para deshabilitar cuentas de usuario en Linux<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\">#!\/usr\/bin\/env bash\r\n\r\n# Description: Disables a user account by changing its shell to \/sbin\/nologin and locking the account.\r\n#\r\n# Release Notes: Initial Release\r\n# 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.\r\n# 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. \r\n# 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. \r\n# 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. \r\n# Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n# 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. \r\n# 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. \r\n# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#\r\n# Below are all the valid parameters for this script.\r\n#\r\n# Preset Parameter: \"ReplaceMeWithUsernameToDisable\"\r\n#   Username of the user you would like to disable.\r\n#\r\n\r\n# Help text function for when invalid input is encountered\r\nprint_help() {\r\n  printf '\\n### Below are all the valid parameters for this script. ###\\n'\r\n  printf '\\nPreset Parameter: \"ReplaceMeWithUsernameToDisable\" \\n'\r\n  printf '\\t%s\\n' \"Username of the user you would like to disable.\"\r\n}\r\n\r\n# Determines whether or not help text is nessessary and routes the output to stderr\r\ndie() {\r\n  local _ret=\"${2:-1}\"\r\n  echo \"$1\" &gt;&amp;2\r\n  test \"${_PRINT_HELP:-no}\" = yes &amp;&amp; print_help &gt;&amp;2\r\n  exit \"${_ret}\"\r\n}\r\n\r\n_arg_userToDisable=\r\n\r\n# Grabbing the parameters and parsing through them.\r\nparse_commandline() {\r\n  while test $# -gt 0; do\r\n    _key=\"$1\"\r\n    case \"$_key\" in\r\n    --help | -h)\r\n      _PRINT_HELP=yes die 0\r\n      ;;\r\n    --*)\r\n      _PRINT_HELP=yes die \"FATAL ERROR: Got an unexpected argument '$1'\" 1\r\n      ;;\r\n    *)\r\n      if [[ -z $_arg_userToDisable ]]; then\r\n        _arg_userToDisable=$1\r\n      else\r\n        _PRINT_HELP=yes die \"FATAL ERROR: Got an unexpected argument '$1' but user '$_arg_userToDisable' was already specified!\" 1\r\n      fi\r\n      ;;\r\n    esac\r\n    shift\r\n  done\r\n}\r\n\r\n# Parse the command-line arguments passed to the script.\r\nparse_commandline \"$@\"\r\n\r\nif [[ -n $usernameToDisable ]]; then\r\n  _arg_userToDisable=\"$usernameToDisable\"\r\nfi\r\n\r\n# Check if the username to disable is empty and display an error if it is.\r\nif [[ -z $_arg_userToDisable ]]; then\r\n  _PRINT_HELP=yes die \"[Error] The username of the user you would like to disable is required!'\" 1\r\nfi\r\n\r\n# Validate the username to ensure it only contains lowercase letters, digits, hyphens, and underscores.\r\nif [[ ! $_arg_userToDisable =~ ^[a-z0-9_-]+$ ]]; then\r\n  _PRINT_HELP=no die \"[Error] Invalid characters detected in '$_arg_userToDisable' usernames can only have a-z, 0-9 or -, _ characters!\" 1\r\nfi\r\n\r\n# Search for the user in the \/etc\/passwd file and ensure the user account is not already set to 'nologin'.\r\npasswdEntry=$(grep -w \"$_arg_userToDisable\" \/etc\/passwd)\r\nif [[ -z $passwdEntry ]]; then\r\n  _PRINT_HELP=no die \"[Error] User '$_arg_userToDisable' does not exist.\" 1\r\nfi\r\n\r\nunlockedaccount=$(passwd -S \"$_arg_userToDisable\" | cut -f2 -d \" \" | grep -v \"L\")\r\nnologin=$(grep -w \"$_arg_userToDisable\" \/etc\/passwd | cut -d \":\" -f7 | grep \"nologin\")\r\nif [[ -z $unlockedaccount &amp;&amp; -n $nologin ]]; then\r\n  _PRINT_HELP=no die \"[Error] User '$_arg_userToDisable' is already disabled. $nologin\" 1\r\nfi\r\n\r\n# Check if the 'sudo' command is available on the system.\r\nsudoAvailable=$(command -v sudo)\r\n\r\n# If 'sudo' is available, check if the specified user has sudo privileges and is not explicitly forbidden from using sudo.\r\nif [[ -n $sudoAvailable ]]; then\r\n  sudoAccess=$(sudo -l -U \"$_arg_userToDisable\" | grep -v \"is not allowed to run sudo\")\r\nfi\r\n\r\n# Initialize a flag to check for the availability of another administrative user.\r\nanotherAdminAvaliable=false\r\n\r\n# If the user to disable is 'root' or if they have sudo access, proceed to check for other admin users.\r\nif [[ \"$_arg_userToDisable\" == \"root\" || -n $sudoAccess ]]; then\r\n # Fetch all user accounts with UID &gt;= 1000 (typically regular users) and exclude the specified user and 'nobody'.\r\n  allAccounts=$(cut -d \":\" -f1,3 \/etc\/passwd | grep -v -w \"$_arg_userToDisable\" | grep -v \"nobody\" | awk -F ':' '$2 &gt;= 1000 {print $1}')\r\n\r\n  # If the user to disable is not 'root', add 'root' to the list of all accounts if it is enabled and not set to 'nologin'.\r\n  if [[ ! \"$_arg_userToDisable\" == \"root\" ]]; then\r\n    enabled=$(grep -w \"root\" \/etc\/passwd | grep -v \"nologin\")\r\n    if [[ -n $enabled ]]; then\r\n      allAccounts=$(echo \"$allAccounts\"; echo \"root\")\r\n    fi\r\n  fi\r\n\r\n  # Iterate over each account to check if there are other admin users available.\r\n  for account in $allAccounts; do\r\n    # Skip checking accounts if 'sudo' is not available.\r\n    if [[ -z $sudoAvailable ]]; then\r\n      continue\r\n    fi\r\n\r\n    # Check if the current account has sudo access.\r\n    sudoAccess=$(sudo -l -U \"$account\" | grep -v \"is not allowed to run sudo\")\r\n    if [[ -z $sudoAccess ]]; then\r\n      continue\r\n    fi\r\n\r\n    # Check if the current account is enabled (i.e., not set to 'nologin').\r\n    accountEnabled=$(grep -w \"$account\" \/etc\/passwd | grep -v \"nologin\")\r\n    if [[ -z $accountEnabled ]]; then\r\n      continue\r\n    fi\r\n\r\n    # If an admin account is available and enabled, set the flag to true.\r\n    anotherAdminAvaliable=\"true\"\r\n  done\r\n\r\n  # If no other admin users are available, output an error and suggest creating another admin account.\r\n  if [[ $anotherAdminAvaliable == \"false\" ]]; then\r\n    _PRINT_HELP=no die \"[Error] No other admins available. Please create another account to administer the system.\" 1\r\n  fi\r\nfi\r\n\r\n# Attempt to change the shell of the user to \/sbin\/nologin to disable login capabilities.\r\nif ! usermod \"$_arg_userToDisable\" -s \/sbin\/nologin; then\r\n  _PRINT_HELP=no die \"[Error] Failed to change the shell for '$_arg_userToDisable' to \/sbin\/nologin.\" 1\r\nfi\r\n\r\n# Attempt to lock the user account using usermod.\r\nif ! usermod -L \"$_arg_userToDisable\"; then\r\n  _PRINT_HELP=no die \"[Error] Failed to lock '$_arg_userToDisable' using usermod.\" 1\r\nfi\r\n\r\n# Check if the user has been successfully disabled by confirming 'nologin' is set.\r\ndisabledUser=$(grep -w \"$_arg_userToDisable\" \/etc\/passwd | grep \"nologin\")\r\nif [[ -n $disabledUser ]]; then\r\n  echo \"Successfully disabled '$_arg_userToDisable'.\"\r\nelse\r\n  _PRINT_HELP=no die \"[Error] Failed to disable '$_arg_userToDisable'.\" 1\r\nfi\r\n<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><\/div>\n<h2>An\u00e1lisis detallado<\/h2>\n<h3><em>Configuraci\u00f3n inicial y an\u00e1lisis de par\u00e1metros<\/em><\/h3>\n<p>El script comienza con la definici\u00f3n de una funci\u00f3n de texto de ayuda (print_help) y una funci\u00f3n die (die) para manejar errores y mostrar mensajes relevantes. La funci\u00f3n parse_commandline procesa los argumentos de la l\u00ednea de comandos para identificar el nombre de usuario de la cuenta que se va a desactivar.<\/p>\n<h3><em>Validar la cuenta de usuario<\/em><\/h3>\n<p>A continuaci\u00f3n, el script comprueba si el nombre de usuario especificado es v\u00e1lido y existe en el sistema. Se asegura de que el nombre de usuario contiene s\u00f3lo caracteres permitidos (letras min\u00fasculas, d\u00edgitos, guiones y guiones bajos) y verifica su existencia en el archivo \/etc\/passwd.<\/p>\n<h3><em>Garantizar que no haya conflictos con las cuentas administrativas<\/em><\/h3>\n<p>El script comprueba adem\u00e1s si el usuario a deshabilitar tiene privilegios administrativos. Verifica si hay otras cuentas de administrador disponibles para evitar el bloqueo del acceso administrativo esencial.<\/p>\n<h3><em>Desactivar la cuenta de usuario<\/em><\/h3>\n<p>Finalmente, el script desactiva la cuenta de usuario cambiando el shell a \/sbin\/nologin y bloqueando la cuenta. Verifica el \u00e9xito de estas operaciones y proporciona retroalimentaci\u00f3n.<\/p>\n<h2>Posibles casos de uso<\/h2>\n<p>Imaginemos que un profesional de TI necesita desactivar la cuenta de un empleado que ha dejado la empresa. El script proporciona un m\u00e9todo \u00e1gil y eficaz para garantizar que la cuenta se desactiva sin eliminarla. Esto permite al equipo de TI conservar los datos del usuario y el historial de la cuenta a efectos de cumplimiento y auditor\u00eda.<\/p>\n<h2>Comparaci\u00f3n con otros m\u00e9todos<\/h2>\n<p>El enfoque tradicional para desactivar una cuenta de usuario puede implicar la edici\u00f3n manual del archivo \/etc\/passwd o la ejecuci\u00f3n de varios comandos. Este script automatiza el proceso, reduciendo el riesgo de error humano y garantizando la coherencia entre los distintos sistemas.<\/p>\n<h2>FAQ<\/h2>\n<h3>P: \u00bfEste script puede eliminar una cuenta de usuario?<\/h3>\n<p>R: No, el script s\u00f3lo desactiva la cuenta cambiando el shell y bloque\u00e1ndola. Eliminar una cuenta requerir\u00eda comandos adicionales.<\/p>\n<h3>P: \u00bfEs seguro deshabilitar la cuenta root?<\/h3>\n<p>R: Deshabilitar la cuenta root puede hacer que el sistema sea inmanejable. El script incluye comprobaciones para asegurar que otra cuenta de administrador est\u00e1 disponible antes de proceder.<\/p>\n<h3>P: \u00bfQu\u00e9 ocurre si la cuenta de usuario ya est\u00e1 deshabilitada?<\/h3>\n<p>R: El script comprueba el estado de la cuenta y notifica si la cuenta ya est\u00e1 deshabilitada, evitando operaciones redundantes.<\/p>\n<h2>Implicaciones para la seguridad inform\u00e1tica<\/h2>\n<p>Deshabilitar cuentas de usuario inactivas o comprometidas es una medida de seguridad cr\u00edtica. Reduce la superficie de ataque e impide el acceso no autorizado, mejorando as\u00ed la seguridad general de la organizaci\u00f3n.<\/p>\n<h2>Recomendaciones<\/h2>\n<p>Cuando utilices este script, aseg\u00farate de:<\/p>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\">Disponer de otra cuenta administrativa.<\/li>\n<\/ul>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\">Revisar y actualizar peri\u00f3dicamente tus pol\u00edticas de gesti\u00f3n de cuentas de usuario.<\/li>\n<\/ul>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\">Probar el script en un entorno que no sea de producci\u00f3n antes de desplegarlo en un entorno activo.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p><a href=\"https:\/\/www.ninjaone.com\/es\/script-hub\/\" target=\"_blank\" rel=\"noopener\">La gesti\u00f3n de cuentas de usuario<\/a> es un aspecto fundamental de la administraci\u00f3n de sistemas. Este script simplifica el proceso de deshabilitar cuentas de usuario en Linux, ofreciendo una soluci\u00f3n robusta y automatizada. Herramientas como <a href=\"https:\/\/www.ninjaone.com\/es\/\" target=\"_blank\" rel=\"noopener\">NinjaOne<\/a> pueden agilizar a\u00fan m\u00e1s las operaciones de TI, proporcionando capacidades integrales de gesti\u00f3n y supervisi\u00f3n para garantizar que tus sistemas permanezcan seguros y eficientes.<\/p>\n<p>Siguiendo las mejores pr\u00e1cticas y usando scripts automatizados, los profesionales de TI pueden mantener un entorno Linux seguro y bien gestionado, salvaguardando su infraestructura frente a posibles amenazas y garantizando una continuidad operativa sin problemas.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"","_lmt_disable":""},"operating_system":[4211],"use_cases":[4267],"class_list":["post-353789","script_hub","type-script_hub","status-publish","hentry","script_hub_category-linux","use_cases-gestion-de-usuarios-y-accesos"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/353789","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=353789"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=353789"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=353789"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=353789"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}