What is the difference between sudo command and sudo bash -c command?
Solution 1
Sudo won’t allow you to natively do command redirection; for example, the following won’t work — permission is still denied on write attempt:
sudo echo -e “\x23\x21/usr/bin/sudo /bin/bash\napt-get update\napt-get -y dist-upgrade” > /usr/bin/distupgrade && sudo chmod a+x /usr/bin/distupgrade
Wrapping everything in sudo bash -c
solves this problem:
sudo bash -c “echo -e \”\x23\x21/usr/bin/sudo /bin/bash\napt-get update\napt-get -y dist-upgrade\” > /usr/bin/distupgrade && chmod a+x /usr/bin/distupgrade”
Solution 2
sudo su
lauches su
directly with super user privileges, while sudo bash
lauches the shell first and then executes the command with bash -c
.
The main difference would be that your .bashrc
script will be run before executing the su - root
command. The outcome depends on that.
Use cases:
Lauch
bash
with elevated privilges, using your own password:sudo bash
Lauch shell as user
root
, with root's password:su - root
Lauch shell as user
root
, with your own password:sudo su - root
Everything already covered, no really need for:
sudo bash -c 'su - root'
Solution 3
You should, instead, use
sudo -i
su and sudo are two very different ways to escalate privileges, but in the end both allow you to run commands as your target user - in your case root.
sudo uses your username and your groups to decide wether or not you can execute a command, while su expects you to know the password of your target user - except for root, who can become anyone without password.
When you run sudo su - root
you are authenticating twice, in practice to create a shell as root, which you can do by running sudo -i
Related videos on Youtube
Kramer Li
Updated on September 18, 2022Comments
-
Kramer Li over 1 year
Is there any difference between the following two commands?
sudo su - root
and
sudo bash -c 'su - root'
It looks like a silly question but I believe there is some benefit on security by only allowing the second one. I just do not know what is the benefit for that. So could you give me some advice on this?
-
David Ferenczy Rogožan over 4 yearsI need to get an elevated shell. My user is in
sudoers
so I can usesudo
. The only way to keep defined aliases (and as a bonus also the prompt and other things defined in my user's.bashrc
) I have found is to usesudo -E bash
. When I usesudo -E su
, those things are not preserved. Is it wrong to usesudo -E bash
for any reason, please?