Linux su Commands

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Linux su Commands

The su command allows you to run a shell as another user.

Syntax:

su <username>

Example:

su jtp

Linux su Commands1

Look at the above snapshot, user account is changed from sssit to jtp.


su to root

You can change the user to root when you know the root password.

Syntax:

su root 

Linux su Commands2


su as root

The root user can become any existing user without knowing that user's password. Otherwise, password is needed.

Example:

  1. su - sssit  

Linux su Commands3

Look at the above snapshot, it is asking for password while switching from user jtp to sssit.

Now let's look at the following example.

Example:

su - jtp

Linux su Commands4

Look at the above snapshot, we are at user root. While switching from root to jtp it didn't ask for password and we're successfully arrived at user jtp.

su - $username

By default, the su command maintains the same shell environment. To access the target user's shell environment use the su command with (-) followed by the target user name.

Example:

  1. su - jtp  
  2. su jtp

Linux su Commands5

Look at the above snapshot, with the command "su - jtp" current shell environment is /home/jtp and user is also jtp. With the command "su jtp" current shell environment is /home/sssit and user is sssit.


su -

If any user name is not mentioned then by default, it will assume root as the target user.

Example:

  1. su -  

Linux su Commands6

Look at the above snapshot, command "su -" has assumed root as the target.


Running Program As Another User / sudo Command

The sudo command allows a user to start programs with the credentials of another user.

Example:

/usr/sbin/useradd -m akki 

Linux su Commands7

Look at the above snapshot, shell gives the above message while creating usr 'akki'.


Command With sudo

With sudo command we're allowed to create new users on the system without becoming root or without knowing the root password.

Example:

sudo /usr/sbin/useradd -m akki 

Linux su Commands8

Look at the above snapshot, user 'akki' is created with sudo command.


sudo su -

By default, some Linux systems like Ubuntu, don't have a password set for root user. It means you can't login as root user.

To perform root like task, a user is given all sudo rights via etc/sudoers. All the users that are members of the admin group can use sudo command for performing root tasks.

Syntax:

  1. grep admin /etc/sudoers  

Linux su Commands9

Look at the above snapshot, commnd "grep admin /etc/sudoers" allows all the admin group users to gain root peivileges.

By typing sudo su - a user can become root user without typing password for root. The sudo command will ask for the user's own password.

Syntax:

sudo su -

Linux su Commands10

Look at the above snapshot, bash is asking for sssit password not for root password, after that we are logged in as root user.