RDP Monster

How to Switch User in Ubuntu: su, sudo & Privilege Escalation

How to Switch User in Ubuntu: su, sudo & Privilege Escalation

Introduction

Managing multiple user accounts and switching between them is a fundamental aspect of Linux system administration. Ubuntu, the world’s most popular Linux distribution, provides several methods for changing active users, each with distinct use cases and security implications. Understanding these switching mechanisms enables efficient multi-user workflows, secure administrative operations, and proper privilege management.

This comprehensive guide explores every method for switching users in Ubuntu, from basic command-line approaches to advanced permission escalation techniques. Whether managing shared systems, administrative tasks, or multi-tenant environments, mastering user switching is essential for Ubuntu proficiency.

 

Understanding Ubuntu User Management

User Account Types

Regular Users: Standard accounts with limited privileges, restricted file access, and inability to modify system configuration.

Root User: Superuser with unrestricted access to all system resources, capable of any operation including dangerous ones.

System Users: Special accounts for system services (www-data for web servers, mysql for databases).

Sudo Users: Regular accounts with delegated superuser privileges through sudo configuration.

Privilege Escalation

Why Escalate?: Most administrative tasks require elevated privileges. Rather than logging in as root (dangerous), Ubuntu uses privilege escalation to grant specific elevated permissions temporarily.

Principles: Execute operations with minimum necessary privileges; minimize time with elevated access; audit all privileged operations.

 

su (Switch User) Command

Basic Syntax

su [OPTIONS] [USERNAME]
Switching to Another User
 
su john
Prompts for the target user’s password, then switches to that account. The environment remains the user’s original environment (not recommended).
 

Switching User with New Environment

su - john


The hyphen (-) loads the complete environment of the target user, including:

  • HOME variable pointing to user’s home directory

  • PATH variable with user’s command paths

  • Shell configuration files (.bashrc, .profile)

  • Working directory changed to user’s home

Best Practice: Always use su - to ensure proper environment configuration.


Switching to Root User

su -


Switches to root user with root’s complete environment. Prompts for root password.

su Command Options

-c (Command): Execute single command as another user without full session

su - john -c "ls -la /home/john"
 

-l (Login): Identical to using hyphen; creates login shell

su --login john

 

-s (Shell): Specify shell for session

su - john -s /bin/zsh

 

-m (Preserve environment): Keep current environment while switching

su -m john
 

sudo (Superuser Do) Command

Basic Syntax
sudo [OPTIONS] COMMAND


Executing Command with Elevated Privileges

sudo apt-get update # Update package lists (requires root)
sudo systemctl restart ssh # Restart SSH service
sudo reboot # Reboot system


Running Interactive Root Shell

sudo -i

Initiates interactive root shell without logging in as root.

Running Command as Different User

sudo -u username command

Executes command with specified user’s privileges (not just root).


sudo Command Options

-l (List): Display allowed commands

sudo -l
 

-k (Invalidate): Clear sudo credentials (requires password on next use)

sudo -k

 

-p (Prompt): Custom password prompt

sudo -p "Enter admin password: " apt-get update
 
 
-v (Validate): Extend sudo timeout
sudo -v

 

-H (Home): Set HOME to target user’s home

sudo -H -u username command
 
 

su – vs su: Key Differences

Feature su su –
Environment Keeps parent shell environment Loads target user’s environment
HOME Variable Remains original user’s home Changes to target user’s home
PATH Variable May include original user’s paths Contains target user’s standard paths
Shell Config Doesn’t load .bashrc or .profile Loads ~/.bashrc, ~/.profile
Working Directory Remains current directory Changes to user’s home
Recommended Rarely; potential confusion Always for user switching
Risk Level Higher (mixed environments) Lower (clean environment)

 

Example Difference

# Using su (BAD)
$ su john
Password:
$ echo $HOME
/root # Still shows original home!
$ pwd
/path/to/original # Still in original directory
 
# Using su - (GOOD)
$ su - john
Password:
$ echo $HOME
/home/john # Correct home directory
$ pwd
/home/john # Correct directory
 
 

Switching to Root User

Using su

su - Password: (enter root password)
root@hostname:~#

 

Using sudo

sudo -i
[sudo] password for john: (enter john's password)
root@hostname:~#

 

Differences Between su – and sudo -i

Aspect su – sudo -i
Password Required Root password Current user’s password
Logging Not logged Logged by sudo
Audit Trail Minimal Complete audit trail
Security Lower (requires sharing root password) Higher (individual accountability)
Typical Enterprise Setup Discouraged Recommended

Security Note: Modern Ubuntu systems typically don’t require root password; instead, sudoers are granted authority through sudo configuration.

 

Running Commands as Another User

Execute Single Command

sudo -u apache /usr/bin/apache2ctl restart
su - testuser -c "python /home/testuser/script.py"

Running Multiple Commands

sudo bash -c "echo 'Line 1' > /tmp/file; cat /tmp/file"
 

Running Commands Preserving Current Directory

sudo -u john pwd # Prints john's home (working directory changed)
sudo -u john -C pwd # Prints current directory (with -C flag)
 
 

Changing User Password

Change Own Password

passwd

Prompts for current password, then new password (twice for confirmation).

Change Another User’s Password (Root Required)

sudo passwd john

No current password required; prompts for new password (root authority).

Set Expiration Policy

sudo chage -l john # View password aging info
sudo chage -M 90 john # Force password change every 90 days
sudo chage -d 0 john # Force password change on next login
 
 

User Permissions and Groups

View User Groups

groups john # Show groups current user belongs to
groups # Show own groups
id john # Detailed UID, GID, groups

 

Add User to Group

sudo usermod -aG groupname username

 

Example: Add user to sudo group

sudo usermod -aG sudo john

 

Remove User from Group

sudo deluser username groupname

 

Create New User

sudo useradd -m -s /bin/bash newuser
sudo passwd newuser

Options:

  • -m: Create home directory

  • -s: Specify shell

  • -G: Assign to groups

 

Practical Examples

Example 1: Administrative Task with Privilege Escalation

#!/bin/bash
 
# Install software update as regular user with privilege escalation
sudo apt-get update
sudo apt-get upgrade -y
echo "System update complete"

 

Example 2: Running Web Server Tasks

# Stop web server as specific service user
sudo -u www-data /opt/webapp/stop.sh
 
# Check web server permissions as www-data
sudo -u www-data ls -la /var/www/html
 

Example 3: Running Database Maintenance

# Backup database as specific user
sudo -u mysql mysqldump -u root -p database_name > backup.sql
 
# Run database optimization
sudo -u mysql mysql -u root -p -e "OPTIMIZE TABLE table_name;"
 

Example 4: Batch User Management

#!/bin/bash
# Create multiple users
for user in user1 user2 user3; do
sudo useradd -m -s /bin/bash "$user"
     echo "Please set password for $user:"
sudo passwd "$user"
done
 
# Add all to sudo group
for user in user1 user2 user3; do
    sudo usermod -aG sudo "$user"
done
 
 

Security Considerations

Password Security

Root Password: Keep secure; never share with untrusted individuals

Sudo Configuration: Delegate specific privileges rather than full root access

Password Aging: Enforce periodic password changes

# Configure password aging
sudo chage -M 90 -m 1 -W 7 username
# Forces change every 90 days, minimum 1 day between changes, 7-day warning
 

Audit and Logging

All sudo commands are logged:

sudo grep COMMAND /var/log/auth.log

 

View detailed sudo history:

sudo journalctl _COMM=sudo
 

Restricting Privilege Escalation

Configure sudoers file safely:

sudo visudo # Always use visudo for editing sudoers

 

Example sudoers configuration (limiting what john can run):

john ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
john ALL=(ALL) /usr/bin/apt-get

 

Session Timeout

# Set sudo timeout
sudo -v # Extend timeout
sudo -k # Invalidate sudo credentials
 
 

Why Remote Infrastructure Uses User Switching

RDP and SSH infrastructure frequently requires:

  • Multiple administrative users with different privilege levels

  • Service accounts for automated processes

  • Audit trails for compliance (sudo logging)

  • Privilege escalation for administrative tasks

 

Infrastructure Management Through RDP.Monster

Managing Ubuntu systems remotely requires robust, secure access:

SSH Access for Command Execution

  • Execute user-switching commands remotely

  • Automated administration through scripts

  • Full control over user management

Multiple User Account Support

  • Create administrative users

  • Delegate privileges appropriately

  • Maintain audit trails

Secure Remote Administration

  • SSH encryption for all user switching operations

  • Key-based authentication for programmatic access

  • Comprehensive logging and monitoring

Deploy Ubuntu VPS infrastructure with secure user management capabilities via RDP.Monster

 

Conclusion

User switching and privilege escalation are fundamental Ubuntu administration skills. Understanding the differences between su, sudo, and password management enables effective multi-user system administration while maintaining security through proper privilege delegation and audit trails.

Modern Ubuntu best practices strongly favor sudo over su for privilege escalation, enabling accountability and comprehensive logging while minimizing root password sharing. Proper configuration of sudoers delegating specific privileges provides excellent security balance between usability and access control.

Managing complex Ubuntu infrastructure requiring sophisticated user management and secure administrative access? RDP.Monster provides SSH-based Ubuntu VPS solutions enabling seamless user management and privilege escalation across your infrastructure. Deploy professionally-managed Ubuntu systems today.

Powerful Ubuntu VPS Hosting

Experience full control and blazing performance with our Linux VPS. Perfect for hosting applications, managing servers, and optimizing your workflow.

Dedicated Servers

High-Performance Dedicated Servers

Need maximum control and power? Our Dedicated Servers offer unmatched performance for demanding tasks.

Frequently Asked Questions

Should I use su or sudo?

sudo is preferred in modern systems.

It enables accountability, requires individual passwords, and provides complete audit trails.

Why doesn't my su command work?

You might not know the target user's password.

Try sudo -u username instead if you have sudo privileges.

Can I switch users without a password?

Yes, with sudo: configure sudoers with NOPASSWD.

For su, you always need the target user's password.

What's the difference between su - and su --login?

They're identical; both create login shells with full environment loading.

How long does sudo privilege last?

Default is 15 minutes. Customizable in sudoers configuration.

Can I run multiple commands as another user?

Yes: sudo bash -c "command1 && command2 && command3"

How do I see my sudo permissions?

Run sudo -l to display allowed commands.

Why does my PATH change when switching users?

Use su - to load the target user's complete environment, including correct PATH.

Register to our reseller program

Your informations

If you have any question, contact us by clicking here !
Name(Required)
Enter your email address, you must have an account on manager.rdp.monster !

Your company

Enter your website address if you have one
Quickly explain how you're going to sell services to your customers. For example, talk to people on forums.

We're using cookies!

We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic. By clicking "Accept", you consent to our use of cookies.