Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply password to sudo in one line command and execute su root?

Tags:

linux

bash

I've created an user named samX with root privilege (have appended "samX ALL=(ALL:ALL) ALL" in visudo).

I'm trying to apply password to sudo, then su root and execute whoami sequentially in one line command. My current command is somewhat as follows, but it complains error: sudo: su root; whoami: command not found

echo 'CbEYKFKt' | sudo -S 'su root; whoami'

In which, 'CbEYKFKt' is the password for user samX.

Is there anyway to solve this problem? Thanks a lot.

like image 321
Judking Avatar asked Apr 29 '15 08:04

Judking


3 Answers

echo 'CbEYKFKt' | sudo -S su -c whoami

should work - -c specifies a command for su whereas in your example you seem to be running a command 'root; whoami' which does not exist - there is no shell to break that up into two separate commands.

like image 109
DavidC Avatar answered Oct 11 '22 09:10

DavidC


You should really add a line to your sudoers file such as

samX ALL=(ALL:ALL)  NOPASSWD: /sbin/su

instead of saving your password in the bash history or any other file. With that, there is no need to enter the password at all.

If you want to perform a different command, add that.

like image 4
martin Avatar answered Oct 11 '22 09:10

martin


When you login into a shell session via putty or moba where you have stored the login credentials for a non root account, simply add this command to be executed upon login in by putty or moba and it will switch your access to root right away.

echo "PASSWORD" | sudo -S su - && sudo su

like image 2
Andy Avatar answered Oct 11 '22 11:10

Andy