2

I want to write a shell script that can login to root user and it should carry password inside the same script. It should not ask for password on the terminal.

I have written a script that works fine, but it is asking for password on the terminal, I want to automate this process by giving the password inside script only.

id
sudo -s <<EOF
echo Now i am root
id
mkdir someDir
whoami
EOF

note: i want to get it done without touching /etc/sudoers file.

6
  • 3
    You can use expect for that
    – annahri
    Jun 21, 2020 at 21:41
  • 2
    Please note that writing the root password into a file (and without file encryption) is a big security risk! Any program started by you can read that file.
    – Ned64
    Jun 21, 2020 at 22:29
  • @annahri can you please provide an example. I have tried to use expect like this spawn ./c.sh expect "[sudo] password for divyaa:\r" send -- "mypass\r" expect eof but its giving this error spawn ./c.sh invalid command name "sudo" while executing "sudo" invoked from within "expect "[sudo] password for divyas:\r"" (file "./a.sh" line 7) Jun 21, 2020 at 22:43
  • @Ned64 thanku for the information. i will keep this mind, for now there is a need to do this. Jun 21, 2020 at 22:46
  • 5
    Usually I hate when ppl tell me alternative ways to do my goal, but this just seems plain wrong. Something is incorrect, there has to be a better way than scripting roots pwd. Heck use ssh root@localhost and RSA keys. Jun 22, 2020 at 6:45

1 Answer 1

2

I want to automate this process by giving the password inside script only.

id
echo your_password_here |sudo --stdin bash -c "
echo Now i am root
id
mkdir someDir
whoami
"

man sudo :

 -S, --stdin
             Write the prompt to the standard error and read the password from the standard input in‐
             stead of using the terminal device.
3
  • 1
    Why the { } braces? Jun 21, 2020 at 22:54
  • 3
    No warning about how bad an idea this is? There has to be a better way. Create a specific user or use ssh via RSA, something! Jun 22, 2020 at 17:43
  • 1
    @FreeSoftwareServers Could add it as answer?
    – GAD3R
    Jun 22, 2020 at 19:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .