Linux Command Guide: su
- Switching User Identities
1. Introduction
The su
command in Linux and Unix-like systems allows a user to switch their current user ID to that of another user. If no username is specified, su
defaults to switching to the superuser (root account), which has unrestricted access to the system. This command is a powerful tool for system administration, enabling users to perform tasks that require different privilege levels without logging out and back in.
su
stands for substitute user or switch user (historically, also superuser as it was primarily used to become root). Understanding how su
operates, particularly the difference between a login shell and a non-login shell, its options, and its security implications is vital for proper system management. This guide provides a comprehensive exploration of the su
command, including its syntax, use cases, options, and best practices.
2. Basic Syntax
The basic syntax for the su
command is:
$ su [OPTIONS] [-] [USERNAME [ARG...]]
- [OPTIONS]…: Optional flags that modify
su
’s behavior (e.g.,-l
,-c
,-s
). - - (Hyphen): Also written as
-l
or--login
. This option simulates a full login as the target user, providing a clean environment. - [USERNAME]: The username of the account to switch to. If omitted,
su
defaults to root. - [ARG…]: Optional arguments to be passed to the new shell. If
-c
is used, these are arguments for the command specified by-c
.
When su
is invoked to switch to another user (especially root), it will typically prompt for the password of the target user.
3. Core Use Cases with Examples
su
is primarily used to gain root privileges or to operate as another specific user. Below are common use cases with examples.
Setup for Examples
For these examples, assume you are logged in as a regular user (e.g., user1
). We’ll also assume another regular user user2
exists and the root user has a password set.
# Create a test user for some examples (run these commands as root or with sudo)
$ sudo useradd user2 -m -s /bin/bash # Create user2 with home dir and bash shell
$ sudo passwd user2 # Set a password for user2
Explanation of the Command: sudo useradd user2 -m -s /bin/bash
-
Command Overview: This is a Linux command used to create a new user account on the system. It requires administrative privileges, specifies the username, and includes options to configure the user’s environment. Here’s the detailed explanation:
-
Components and Options
sudo
: Thesudo
prefix allows the command to be executed with superuser (root) privileges. Creating a new user involves modifying system files (e.g.,/etc/passwd
,/etc/shadow
) and creating directories in restricted locations (e.g.,/home
), which typically require root access. Withoutsudo
, a regular user would lack the necessary permissions.useradd
: This is the core command for adding a new user account to a Linux system. It’s a low-level utility (as opposed to the more interactiveadduser
) that creates the user and updates system configuration files.user2
: This is the username of the new account being created. In this case, the new user will be nameduser2
.-m
: The-m
option instructsuseradd
to create a home directory for the new user if it doesn’t already exist. By default, this directory is typically located at/home/user2
. The home directory is populated with template files from/etc/skel
(e.g.,.bashrc
,.profile
), providing the user with a basic environment setup.-s /bin/bash
: The-s
option specifies the login shell for the user, and/bin/bash
sets it to the Bash shell. The shell is the program that runs when the user logs in, allowing them to interact with the system via commands. Bash is a popular choice, but if-s
isn’t specified, the system uses a default shell (often/bin/sh
), which may vary by distribution.
-
What the Command Does When executed,
sudo useradd user2 -m -s /bin/bash
:- Creates a new user account named
user2
. - Sets up a home directory for
user2
at/home/user2
(using-m
). - Configures the account to use the Bash shell as the default login shell (via
-s /bin/bash
). - Performs these actions with superuser privileges (thanks to
sudo
).
- Creates a new user account named
3.1. Switching to the Root User (Superuser)
This is the most common use of su
.
3.1.1. Non-Login Shell as Root
# Switch to root user (non-login shell)
$ su
Password: # <-- Enter the ROOT user's password
root@ubuntu:~# whoami
root
root@ubuntu:~# pwd
/home/user1 # Current directory is usually retained
root@ubuntu:~# echo $PATH # PATH variable might still include user1's paths
# ... (some environment variables from user1 might be kept)
root@ubuntu:~# exit # Exit the root shell
$ whoami
user1
Observation: Without -
or -l
, su
starts a root shell but doesn’t fully reinitialize the environment. The current directory is often kept, and some environment variables from the original user might persist. This can sometimes lead to unexpected behavior, such as commands not being found if the PATH is not set correctly for root.
In Ubutu, the root account is disabled by default. If you attempt to log in as the root user directly—such as with su -
or at a login prompt—you’ll receive an authentication failure error.
Go to the FAQ 8.13-8.18 section for more information.
3.1.2. Login Shell as Root (Recommended)
Using -
, -l
, or --login
provides a cleaner, more complete environment as if you logged in directly as root.
# Switch to root user (login shell)
$ su -
# OR
$ su -l
# OR
$ su --login
Password: # <-- Enter the ROOT user's password
root@ubuntu:~# whoami
root
root@ubuntu:~# pwd
/root # Current directory changes to root's home
root@ubuntu:~# echo $PATH # PATH is typically reset to root's default
root@ubuntu:~# exit # Exit the root shell
$ whoami
user1
Observation: The environment is fully initialized for root:
- The current directory changes to root’s home directory (
/root
). - Shell startup files for root (e.g.,
/root/.bashrc
,/root/.profile
) are sourced. - Environment variables like
HOME
,SHELL
,USER
,LOGNAME
,PATH
are set as if root logged in directly. - The previous user’s environment is largely cleared.
This is generally the preferred and safer way to become root interactively because it avoids potential conflicts from inherited environment settings.
3.2. Switching to Another Regular User
You can use su
to switch to another user (e.g., user2
) without needing root privileges, provided you know the target user’s password.
# Switch to user2 (non-login shell)
$ su user2
Password: # <-- Enter USER2's password
user2@ubuntu:~# whoami
user2
user2@ubuntu:~# pwd
/home/user1 # Current directory is usually retained from user1
user2@ubuntu:~# exit
$
# Switch to user2 (login shell)
$ su - user2
# OR
$ su -l user2
Password: # <-- Enter USER2's password
user2@ubuntu:~# whoami
user2
user2@ubuntu:~# pwd
/home/user2 # Current directory is user2's home
user2@ubuntu:~# exit
$
Use Case:
- Testing application behavior as a different user, such as running a program to ensure it works correctly under another user’s permissions.
- Managing files owned by another user (if you have their password or are root).
- Performing tasks that require a specific user context, like accessing user-specific configuration files.
3.3. Executing a Single Command as Another User (-c command)
Instead of starting an interactive shell, you can execute a single command as the target user.
# Execute 'whoami' and 'pwd' as root
$ su -c "whoami; pwd"
Password: # <-- Enter ROOT's password
root
/home/user1 # pwd reflects the original user's directory unless su - -c "..." is used
# Execute 'whoami' and 'pwd' as root with a login shell environment for the command
$ su - -c "whoami; pwd"
Password: # <-- Enter ROOT's password
root
/root # pwd now reflects root's home due to the '-' (login shell context)
# Execute 'whoami' and 'pwd' as user2 with a login shell environment for the command
$ su - user2 -c "whoami; pwd"
Password: # <-- Enter user2's password
user2
/home/user2 # pwd now reflects user2's home due to the '-' (login shell context)
# Execute 'ls /home/user1' as user2
$ su - user2 -c "ls /home/user1"
Password: # <-- Enter USER2's password
# (Output of ls /home/user1, subject to user2's permissions on that directory)
# e.g., if no access, it will show "ls: cannot access '/home/user1': No such file or directory"
Use Case:
- Running specific administrative scripts or commands that need to run as root or another user without needing a full interactive shell. For example, updating system packages as root:
$ su -c "apt update"
. - Common in automation scripts where a specific command needs to be executed with another user’s privileges.
3.4. Additional Use Case: Testing Permissions
You can use su
to verify file or directory permissions for another user.
# As user1, attempt to access a file owned by user2
$ su - user2 -c "cat /home/user2/private.txt"
Password: # <-- Enter USER2's password
# (Contents of private.txt, if user2 has read permissions)
Use Case: Debugging permission issues or ensuring that a user can access specific resources as intended.
4. Key Options Explained (with Examples)
The su
command has several options to control its behavior, primarily related to the environment of the new shell.
4.1. -, -l, —login
Purpose: Make the shell a login shell. This is the most important option for interactive use.
- Clears most environment variables, except for
TERM
and possibly others likeDISPLAY
,XAUTHORITY
if configured. - Initializes
HOME
,SHELL
,USER
,LOGNAME
, andPATH
for the target user. - Changes to the target user’s home directory.
- Sources the target user’s shell startup files (e.g.,
.bash_profile
,.bashrc
,.profile
).
Syntax:
$ su - [USERNAME]
$ su -l [USERNAME]
$ su --login [USERNAME]
Use Case: The recommended way to switch to root or another user for interactive work, as it provides a clean and predictable environment, avoiding issues from inherited settings.
Example:
# Switch to user 'apache' with a full login environment
$ su - apache
Password: # apache's password
apache@ubuntu:~# pwd
/var/www # Or wherever apache's home is configured
4.2. -c COMMAND, —command=COMMAND
Purpose: Pass a single COMMAND (as a string) to the shell for execution, instead of starting an interactive shell. The shell is invoked with its -c
option.
Syntax:
$ su [USERNAME] -c "COMMAND_STRING [ARGS...]"
Use Case: Running a specific command with the privileges of another user, often used in scripts or automation tasks.
Example:
# As user1, create a file in /tmp as user2
$ su - user2 -c "touch /tmp/file_by_user2.txt"
Password: # user2's password
# Verify the file ownership (run as root or user1 with sudo)
$ ls -l /tmp/file_by_user2.txt
-rw-r--r-- 1 user2 user2 0 May 3 22:30 /tmp/file_by_user2.txt
Note: If you combine -
with -c
(e.g., su - USER -c "cmd"
), the command cmd
runs within the context of a login shell for USER
, ensuring the target user’s environment is fully initialized.
4.3. -s SHELL, —shell=SHELL
Purpose: Run the specified SHELL instead of the target user’s default login shell (as defined in /etc/passwd
).
Syntax:
$ su [USERNAME] -s /path/to/shell
Use Case:
- Switching to a user who has a restricted shell (e.g.,
/sbin/nologin
) but you need to run commands as them using a standard shell like/bin/bash
. This usually requires being root to invokesu
. - Testing scripts or behavior with a different shell, such as ensuring a script works in
sh
instead ofbash
.
Example:
# Assume user 'restricteduser' has /sbin/nologin as their shell.
# As root, switch to 'restricteduser' but use /bin/bash.
$ sudo su - # Become root first
Password: # root's password
# Now, as root, switch to 'restricteduser' with a bash shell
root@ubuntu:~# su - restricteduser -s /bin/bash
restricteduser@ubuntu:~# whoami
restricteduser
restricteduser@ubuntu:~# echo $SHELL
/bin/bash
restricteduser@ubuntu:~# exit # back to root
root@ubuntu:~# exit # back to original user
4.4. -m, -p, —preserve-environment
Purpose: Preserve the current environment variables (except for a few like $PATH
which might be reset for security by default, and $IFS
). This means variables like HOME
, SHELL
, USER
, LOGNAME
from the original user are not changed to those of the target user. This option is particularly useful in scripts where the original environment needs to be maintained.
Syntax:
$ su -m [USERNAME]
Use Case: When you need to run a command as another user but require that command to see and use the environment variables from your original user’s session. This can be a security risk if not handled carefully, as inherited variables might cause unexpected behavior. Generally, using su -
(login shell) is safer as it provides a clean environment.
Example:
# Set a variable in user1's environment
$ export MY_ORIGINAL_VAR="Hello from user1"
# Switch to root, preserving environment
$ su -m
Password: # root's password
root@ubuntu:~# echo $MY_ORIGINAL_VAR
Hello from user1
root@ubuntu:~# echo $HOME # Will likely still be /home/user1
/home/user1
root@ubuntu:~# whoami
root
root@ubuntu:~# exit
Contrast: With su -
, MY_ORIGINAL_VAR
would not be set, and HOME
would be /root
.
4.5. -f, —fast (Specific to csh/tcsh)
Purpose: This option is primarily for users of csh
or tcsh
. It prevents the shell from reading its startup file (e.g., .cshrc
). This is less relevant for users of bash
, which is the default shell in most Linux distributions.
Syntax:
$ su -f [USERNAME]
Use Case: Speeding up shell startup for csh
/tcsh
if the startup files are slow or not needed for the specific su
session. For bash
users, this option has no effect.
4.6. —help
Purpose: Displays a help message summarizing usage and options, then exits.
Syntax:
$ su --help
Use Case: Quickly checking the available options and syntax for su
.
4.7. —version
Purpose: Displays version information for the su
utility and exits.
Syntax:
$ su --version
Use Case: Verifying the version of su
installed on the system, which can be useful for troubleshooting or ensuring compatibility.
5. Combining Options
Combining options allows for more flexible usage of su
. Common combinations include:
-
$ su - USERNAME -c "COMMAND"
: ExecuteCOMMAND
asUSERNAME
within a full login shell environment forUSERNAME
. This is a common and recommended way to run a single command as another user with their proper environment.# Update package lists as root with a login shell $ su - -c "apt update" Password: # root's password # (Output of apt update command)
-
$ su -m -s /bin/sh USERNAME
: Switch toUSERNAME
, preserve the original user’s environment (-m
), and use/bin/sh
as the shell (-s
).# Switch to user2 with sh shell, preserving environment $ su -m user2 -s /bin/sh Password: # user2's password user2@ubuntu:~# echo $SHELL /bin/sh user2@ubuntu:~# exit
6. Handling Special Cases
6.1. Root Password Requirement
To switch to root (or any other user), you generally need to know the password for that target user. However, Pluggable Authentication Modules (PAM) can be configured to allow certain users or groups (e.g., “wheel”) to use su
without a password, though this is not standard and requires specific setup. This is typically done for administrative convenience but should be approached with caution due to security risks.
6.2. PAM Configuration
The behavior of su
(e.g., who can use it, logging, password policies) is often controlled by PAM configuration, typically found in /etc/pam.d/su
or /etc/pam.d/su-l
. For example:
- To restrict
su
to members of the “wheel” group, you can addauth required pam_wheel.so use_uid
to/etc/pam.d/su
. - PAM can also enforce logging of
su
attempts or set delays after failed authentications.
6.3. Wheel Group
On some systems, only users belonging to a special group (often named “wheel” or “sudo”) are permitted to su
to root, even if they know the root password. This is a security measure configured via PAM, enhancing control over who can access privileged accounts.
6.4. Environment Variables
su -
(login shell): Drastically changes the environment to match the target user’s login environment, resetting variables likePATH
,HOME
, andUSER
.su
(non-login shell): Preserves more of the original user’s environment, which can sometimes lead to issues if paths or library settings conflict.su -m
: Explicitly tries to preserve most of the original environment, useful for scripts but potentially risky.
6.5. Shell Startup Files
su -
: Sources the target user’s login startup files (e.g.,.bash_profile
,.profile
, then.bashrc
if called by them). This ensures the environment is set up as if the user logged in directly.su
(non-login, interactive): May source non-login startup files like.bashrc
for the target user, depending on the shell.su -c "command"
: Behavior regarding startup files can vary.su - -c "command"
is more likely to source login files before running the command, as it initializes a login shell.
7. su
vs. sudo
: Key Differences and When to Use Which
The choice between su
and sudo
is a common point of confusion and has significant security implications. Below is a detailed comparison.
Feature | su (Substitute User) | sudo (Superuser Do) |
---|---|---|
Password | Requires target user’s password (e.g., root’s password). | Requires your own (invoking user’s) password. |
Privilege Scope | Grants a full shell with all privileges of the target user. | Grants privileges for specific commands as defined in /etc/sudoers . |
Default Target | Root | Root |
Environment | su - creates a clean login environment. su is partial. | Resets environment by default (configurable via sudoers ). |
Logging | Basic logging (often just the switch itself). | Detailed logging of each command executed via sudo . |
Configuration | Less granular control (PAM for basic access). | Highly granular control via /etc/sudoers (who, what, where). |
Security Model | ”All or nothing” for the session. Sharing root password is risky. | Principle of Least Privilege. Users only get rights they need. |
Typical Use | Becoming root for an extended interactive session (use su - ). | Executing single administrative commands. Preferred for most tasks. |
When to Use su
- When you need a full, interactive login shell as another user (especially root) for an extended period to perform multiple tasks that all require those privileges.
su -
is preferred for its clean environment. - In situations where
sudo
is not configured or available, such as on minimal systems. - When you legitimately know and are authorized to use the target user’s password.
When to Use sudo
- For executing single administrative commands without needing a full root shell. This is the recommended approach for most day-to-day administrative tasks, such as installing packages or editing system files.
- When you want to grant specific, limited privileges to users without giving them the full root password.
- For better auditing and logging of privileged command execution, as
sudo
logs each command. - When following the principle of least privilege, ensuring users only have the access they need.
In modern Linux systems, sudo
is generally favored over direct root logins or extensive su
sessions for security and accountability. For example, Ubuntu disables the root account by default, encouraging sudo
usage.
8. Frequently Asked Questions (FAQ)
8.1. What is the difference between su
and su -
?
su
: Switches user but largely keeps the original user’s environment (current directory, some variables). It starts a non-login shell, which may inherit settings that cause unexpected behavior.su -
(orsu -l
): Switches user and provides a full login shell environment for the target user, as if they logged in directly. This is generally preferred for interactive sessions due to its clean environment.
8.2. Why does su
ask for the target user’s password, while sudo
asks for my password?
su
authenticates you as the target user. To become root, you must prove you know root’s password, ensuring only authorized users can switch.sudo
authenticates you (the invoking user) against the/etc/sudoers
policy. If you are authorized, it runs the command as root (or another specified user) using your own password.
8.3. How can I execute just one command as root using su
?
- Use the
-c
option:su - -c "your_command_here"
(the first-
ensures a root login environment for the command).# Restart a service as root $ su - -c "systemctl restart apache2" Password: # root's password # (Service restarts, no output if successful)
8.4. What if I don’t know the root password? Can I still use su
?
- Generally, no. If you don’t know the root password, you cannot use
su
to become root. In such cases, if your user is configured in/etc/sudoers
, you should usesudo
to run commands with root privileges. Many systems, like Ubuntu, disable direct root login and encourage usingsudo
for administrative tasks.
8.5. Can I switch to a user who has /sbin/nologin
or /bin/false
as their shell?
- Directly, no, as these shells are designed to prevent logins, immediately terminating the session.
- However, if you are already root (or can become root via
sudo
), you can usesu -s /bin/bash targetuser
to get a shell astargetuser
using/bin/bash
instead of their restricted default shell.$ sudo su - # Become root Password: # root's password root@ubuntu:~# su -s /bin/bash restricteduser restricteduser@ubuntu:~# whoami restricteduser restricteduser@ubuntu:~# exit
8.6. How does su
affect environment variables like PATH
?
su -
(login shell): ResetsPATH
to the target user’s defaultPATH
, typically defined in their shell startup files or system defaults.su
(non-login shell): ThePATH
might be a mix of the original user’s and target user’s, which can lead to issues if commands are not found.su -m
: Tries to preserve the original user’sPATH
, useful for scripts but potentially problematic.sudo
also has its own way of handlingPATH
, often viasecure_path
in/etc/sudoers
.
8.7. Is it safe to put su
commands with passwords in scripts?
- No, this is highly insecure. Storing passwords in plaintext in scripts is a major security risk, as they can be exposed to unauthorized users. For automated tasks requiring different user privileges, use
sudo
withNOPASSWD
configured very carefully for specific commands in/etc/sudoers
, or use SSH keys for remote execution if applicable.
8.8. What is the “wheel” group in relation to su
?
- On some older Unix systems and some Linux configurations, PAM may be configured so that only users who are members of the “wheel” group (or a similarly named administrative group) are allowed to
su
to root, even if they know the root password. This is an additional layer of security to restrict root access. - In Linux, this behavior is controlled by PAM configuration (e.g.,
/etc/pam.d/su
), not by default group membership.
8.9. How do I exit an su
session?
- Type
exit
or pressCtrl+D
to return to the original user’s session.$ su - Password: # root's password root@ubuntu:~# whoami root root@ubuntu:~# exit $ whoami user1
8.10. Why does su
still ask for a password even if I’m in the “wheel” group?
- In Linux, the “wheel” group does not automatically allow passwordless access to
su
. The behavior is controlled by PAM configuration. By default, PAM requires the target user’s password forsu
, regardless of group membership. To allow certain groups like “wheel” to usesu
without a password, you need to configure PAM accordingly, typically by editing/etc/pam.d/su
and adding appropriate rules (e.g.,auth required pam_wheel.so use_uid
).
8.11. How can I disable su
for non-admin users?
- To restrict who can use
su
, you can configure PAM. For example, you can use thepam_wheel
module to allow only members of the “wheel” group to usesu
. This involves editing/etc/pam.d/su
and adding lines like:auth required pam_wheel.so use_uid
- This will require that the user is in the “wheel” group to use
su
. Note that exact configuration may vary depending on the distribution and PAM setup.
8.12. Is su
available on all Linux distributions?
- Yes,
su
is a standard command in Linux, part of theutil-linux
package, and is available on all major distributions, including Ubuntu, Debian, Fedora, and CentOS.
8.13. What if there is no root user setup in Ubuntu or Kali Linux?
By default, the root account password is locked in Ubuntu and Kali Linux (starting with 2020.1 Kali). This means that you cannot login as root directly or use the su command to become the root user and has no password set, as a security measure to prevent direct logins.
However, since the root account physically exists, it is still possible to run programs with root-level privileges. Administrative tasks are handled using the sudo
command, which allows authorized users to perform actions with elevated privileges. As long as your user account has sudo
privileges (i.e., it’s in the sudoers file), the system operates normally without needing a “setup” root user.
In case where root account login is disabled by default, if you attempt to log in as the root user directly—such as with su -
or at a login prompt—you’ll receive an authentication failure error. This happens because the root account is locked by default and has no password. For example:
- Running
su -
will prompt for a password and fail with:su: Authentication failure
This is normal behavior until the root account is explicitly enabled.
8.14. How to check if root user is locked or enabled in Ubuntu or Kali Linux?
You can check whether root account is locked or enabled by examining the /etc/shadow
file. Here’s how:
-
Open a terminal.
-
Run:
sudo grep '^root:' /etc/shadow
-
Check the output:
- If the second field (after
root:
) is*
or!
(e.g.,root:*:...
), the account is locked (default state). - If it shows a hashed password (e.g.,
root:$6$...
), the account is enabled.
Example (locked state):
root:!:19109:0:99999:7:::
- If the second field (after
Alternatively:
- Run
sudo -i
. If it prompts for your password and gives a root shell (e.g.,root@hostname
),sudo
is working, though the root account remains locked.
8.15. How can you enable the root user if it is disabled?
To enable the root user in Ubuntu or Kali, which is disabled by default, you need to set a password for the root account. This can be done using the following command:
- Open a terminal.
- Run:
sudo passwd root
- When you run this command, you will be prompted to enter and confirm a new password for the root user.
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully
- After setting the password, the root account will be enabled, and you can log in as root using below command or by selecting the root user at the login prompt (if applicable).
su -
Security Risks: Enabling the root account increases the risk of unauthorized access, especially if the password is weak or the system is exposed (e.g., via SSH). It is generally recommended to keep the root account disabled and use sudo
for administrative tasks (e.g., sudo apt update
).
8.16. How do I lock the root account again?
If you decide to disable the root account login, you can lock it again by running beloiw command. This will prevent login as root while retaining the account’s existence.
sudo passwd -l root
The command sudo passwd -l root
is used on Linux systems to lock the root account, preventing anyone from logging in as the root user using a password. Let’s break it down step by step:
sudo
: This part runs the command with superuser (root) privileges. You need administrative access to modify user accounts, andsudo
provides that.passwd
: This is the command to manage user passwords. Normally, it’s used to change a password, but it can also lock or unlock accounts with specific options.-l
: This option means “lock.” When you usepasswd -l
, it locks the specified user’s password by adding an exclamation mark (!
) to the password field in the/etc/shadow
file. This makes the password unusable for logging in.root
: This tells the command to target the root account, which is the superuser account with full system access.
What it does: When you run sudo passwd -l root
, the root account’s password is locked. After this, you can’t log in directly as root using a password, even if one was set before. This is often done as a security measure to prevent unauthorized access to the root account.
8.17. How do I gain root access after running sudo passwd -l root
?
Once the root account’s password is locked, direct login as root using a password is disbaled. However, you can still gain root access or perform administrative tasks using alternative methods. Here’s how:
-
Using
sudo
from Another Account
If your user account hassudo
privileges (meaning it’s allowed to run commands as root), you can usesudo
to access root privileges without logging in as root directly.- To run a single command as root:
sudo <command>
- To open a root shell (like logging in as root):
or
sudo -i
sudo su -
This is the most common and recommended way to manage a system after locking the root account.
- To run a single command as root:
-
SSH with Key-Based Authentication
If your system allows SSH logins to the root account and you’ve set up key-based authentication for root before locking the password, you can still log in using your private key:- Run:
ssh root@<hostname>
- This works only if SSH is configured to permit root logins with keys (check
/etc/ssh/sshd_config
forPermitRootLogin yes
orPermitRootLogin without-password
).
- Run:
-
Using Another Privileged User
If there’s another account withsudo
privileges, log in as that user and usesudo -i
orsudo su -
to switch to root.
Note: The traditional su -
command (which switches to root using the root password) won’t work because the root password is locked.
8.18. How to unlock root login (enable root account) if I have locked it using sudo passwd -l root
?
If you need to unlock the root account after running sudo passwd -l root
, you can do so by running the following command:
sudo passwd -u root
This command will unlock the root account and you could use previously set root password to log in as root.
If you have not set a password for the root account, you will need to set one before you can log in as root.
sudo passwd root
This will prompt you to enter a new password for the root account.
This is useful if you need to revert the lock and allow password logins to root again.
- Note:
sudo passwd root
both sets a new password and unlocks the account in a single step, you don’t need to runsudo passwd -u root
first.sudo passwd -u root
is useful for unlocking the root account if you remember the root password and only need to unlock the account.
8.19. What if I need to perform emergency maintenance on a system with a locked root account?
If you need to perform emergency maintenance on a system with a locked root account, you can use one of the following methods:
- Boot into Recovery Mode: Most Linux distributions allow you to boot into a recovery mode or single-user mode, where you can gain root access without needing the password. This is typically done by selecting a specific kernel option at boot time (e.g., “Recovery mode” in GRUB).
- Use a Live CD/USB: Boot the system from a live CD or USB drive. This allows you to access the filesystem and make changes, including unlocking the root account or resetting the password.
- Access via SSH: If SSH is enabled and you have another user with
sudo
privileges, you can log in remotely and usesudo
to perform administrative tasks.
9. Conclusion
The su
command provides a direct way to switch user identities within a terminal session, most notably to gain superuser (root) privileges. Its most important distinction is the behavior with and without the -
(or -l/--login
) option, which determines whether a full login environment is established for the target user. While sudo
is generally preferred for executing individual commands with elevated privileges due to its finer-grained control and better logging, su -
remains a common method for obtaining an interactive root shell when extensive administrative work is required. Always use su
with an understanding of the security implications, especially when switching to the root account.
10. su Command: Reference Table of Key Options
Below is a comprehensive reference table summarizing the key options of the su
command, along with their descriptions, example commands, and use cases.
Option(s) | Description | Example Command | Use Case |
---|---|---|---|
(none) | Switch to root user (non-login shell) | $ su | Become root, retaining much of the current environment |
USERNAME | Switch to specified USERNAME (non-login shell) | $ su otheruser | Become otheruser, retaining much of the current environment |
-, -l, —login | Provide a full login environment for the target user | $ su - /$ su -l otheruser | Recommended way to switch user for interactive sessions (clean env) |
-c CMD, —command=CMD | Execute CMD as the target user, then exit | $ su - root -c "ls /root" | Run a single command as another user |
-s SHELL, —shell=SHELL | Run specified SHELL instead of target user’s default | $ su -s /bin/sh root | Use a specific shell, or access account with restricted default shell |
-m, -p, —preserve-environment | Preserve current environment (except some variables) | $ su -m root | Run as target user but keep most of original user’s environment variables |
-f, —fast | (csh/tcsh only) Do not read shell startup file (.cshrc) | $ su -f (if using csh) | Speed up csh/tcsh startup for the su session |
—help | Display help message and exit | $ su --help | Get quick usage information |
—version | Output version information and exit | $ su --version | Check the version of the su utility |