16

I can do an su with su <username> and it asks for my password. Is there a password parameter for su such that i wont be prompted for a password?

e.g. su <username> -p <password>

3
14

If you want to write a script that runs as a different user something like this works, though it dows output the word "password" without a newline to standard out

su - username <<!
enterpasswordhere
enter commands to run as the new user
!

if you have a user named fred with a password of 1234 and want to get an ls of fred's home directory as fred, without the password string displayed, it would look like

su - fred <<! >/dev/null 2>&1
1234
whoami > /dev/tty
ls > /dev/tty
!
4
  • 2
    hmm, 'standard in must be a tty' – John Lawrence Aspden Feb 9 '17 at 13:46
  • I get the same error – MaxV Nov 2 '17 at 13:09
  • 16
    Getting Error: su: must be run from a terminal. – Abhishek Kashyap Feb 5 '18 at 10:04
  • Getting su: Sorry – Alec Jacobson Jun 3 '20 at 17:16
6

I belive, there is not and it would not be a good idea. Here's why:
If you write a password in a command like su <username> -p <password>, it would be stored in plain text in your bash history. This is certainly a huge security issue.

If you need to run commands with su (or sudo) in an automated way, write a shellscript containig the commands without su or sudo and run su <username> script.sh

6
  • 3
    su root script still need to enter passwd. – Dai Kaixian Feb 15 '17 at 5:00
  • @DaiKaixian yes, but it is not saved anywhere and nobody can read it – Wayne_Yux Feb 15 '17 at 7:45
  • 2
    you can try something like : echo <passwd> | sudo -S <command-line>.Althought it is not safe, but it works. – Dai Kaixian Feb 15 '17 at 7:53
  • 1
    the whole point of my answer is, that it is not save to write a password in a command. So I advise to not do that – Wayne_Yux Feb 15 '17 at 7:58
  • It's only a security issue if you care about the user not being accessed by anyone else. In my case, for example, I just want a new user with no permissions to use for running an external script that I don't trust. – Jezor Aug 11 '20 at 8:58
-3

If you want to execute some specific commands as a new user, use the following command:
sudo -u {username} {command to be executed as the new user}

1
  • This does not answer the question. The question is about how to handle the password. – Stephen C Aug 30 '18 at 1:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.