How to provide password directly to the sudo su -<someuser> in shell scripting

14,760

Solution 1

Use -S

man sudo:

-S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.

so you can use:

echo <myPassword> | sudo -S su <someuser>

Edit: This above did not work on a testing Ubuntu. It seems like the second command "su " is to fast after prompting password query.

I did a workaround to wait a second so the echoed password could be filled in, and then second sudo should be able, to run sudo su - foobar:

echo "password" | sudo -S sleep 1 && sudo su - foobar

Solution 2

With expect. A stub command may be like this:

expect -c '
 log_user 0
 spawn /usr/bin/sudo su - someuser
 expect "*: "
 send "thepassword\n"
 interact
'

See this answer to a similar question.


Another approach is with sudo -A.

  1. Create a file, say pass.
  2. Make the file accessible only to you: chmod go-rwx pass.
  3. Make it executable to you: chmod u+x pass
  4. Edit the file and make it a script that prints your password:

    #!/bin/sh
    printf '%s\n' 'yourpassword'
    
  5. Now you can do this:

    SUDO_ASKPASS="./pass" sudo -A su - someuser
    

Note: in this case you provide password for sudo (not for su); use the one sudo wants.

Solution 3

Can you use the :NOPASSWD option of sudo so you don't need a password. Like: %wheel ALL=(ALL) NOPASSWD: ALL in /etc/sudoers

Share:
14,760

Related videos on Youtube

raamsaara
Author by

raamsaara

Updated on September 18, 2022

Comments

  • raamsaara
    raamsaara over 1 year

    I got a requirement to automate in shell script for sudo su -<someuser> which asks for password.

    How to provide password directly to the sudo su - in shell scripting for IBM AIX servers. I have tried using echo <password> | sudo su -<someuser> it did not work. kindly help on this.

  • Kamil Maciorowski
    Kamil Maciorowski over 5 years
    In my Debian su exits. However sudo su - invoked just after works thanks to cached credentials. It may be a workaround if you can rely on this behavior.
  • raamsaara
    raamsaara over 5 years
    it is not working.
  • raamsaara
    raamsaara over 5 years
    Thanks . But where can i incorporate the <someuser>
  • chloesoe
    chloesoe over 5 years
    @raamsaara: what did exactly not work? did you get an error? meanwhile I edited my answer to add a workaround, which worked on my machine.
  • Kamil Maciorowski
    Kamil Maciorowski over 5 years
    @raamsaara In su syntax. Answer improved.
  • Binita Bharati
    Binita Bharati over 2 years
    Works great with Ubuntu 20.04. Thanks!