DEV Community

Cover image for Switching Users in Linux (su, sudo)
Aryan Vaishnani
Aryan Vaishnani

Posted on

Switching Users in Linux (su, sudo)

Linux allows users to:

  1. Switch to another user
  2. Run commands as another user
  3. Get administrative access securely

Main commands:

  1. su
  2. sudo

1. su Command

Meaning

su = substitute user

Used to switch from one user to another.

Basic Syntax

su username

Example

su devuser

System asks:

Password:

Requires target user's password.

Switch to Root User

su -

or

su root

Difference Between su and su -

Command Behavior
su Switch user only
su - Full login shell

Example

su - devuser

Loads:

  1. User environment
  2. PATH variables
  3. Home directory

Exit Switched User

exit

Real-World Usage

Switch to Application User

su - nginx

2. sudo Command

Meaning

sudo = Super User DO

Runs a command with elevated privileges.

Basic Syntax

sudo command

Example

sudo apt update

Important Difference

su sudo
Switches entire user Runs single command
Needs target password Needs current user password
Full shell access Controlled access

Why sudo is Preferred

  1. Better security
  2. Logging and auditing
  3. Limited root access
  4. Safer administration

Run Root Shell with sudo

sudo -i

or

sudo su

Run Command as Another User

sudo -u nginx whoami

Example Output

nginx

Sudo Permissions

Controlled by:

/etc/sudoers

Safe Editing

Use:

sudo visudo

Add User to sudo Group

Ubuntu/Debian:

sudo usermod -aG sudo devuser

RHEL/CentOS:

sudo usermod -aG wheel devuser

Real-World DevOps Usage

Restart Service

sudo systemctl restart nginx

Install Packages

sudo apt install docker.io

Kubernetes Admin Commands

sudo kubectl get nodes

Common sudo Options

Command Purpose
sudo -i Root shell
sudo -u user Run as another user
sudo -k Forget cached password
sudo -l Show allowed commands

Principle of Least Privilege

Give users:

  • Only required permissions
  • Not full root access

Real-World Example

DevOps User Setup

sudo useradd -m devops

sudo usermod -aG sudo,docker devops

Now user can:

sudo docker ps

Common Mistakes

Using Root Directly

Bad practice:

su -

for daily tasks.

Better:

sudo command

Security Risks

Improper sudo access can allow:

  1. Privilege escalation
  2. Full server compromise
  3. Accidental system damage

Best Practices

  1. Prefer sudo over direct root login
  2. Avoid sharing root password
  3. Audit sudo access regularly
  4. Use visudo for editing sudoers
  5. Grant minimum required permissions

Top comments (0)