1

I am writing the shell script to automate few tasks. I am logging into the remote server and installing a few packages. But to install I need to get the root access. I am able to login using my credentials with ssh keys. Once I login I need to switch to root, and then it asks for the password. I tried using echo it still asks for the password.

SCRIPT="pwd; ls; echo 'rootpass' | su -; cd ~; pwd; yum -y install <package>"

How can I pass the password on prompt. I need to maintain the same session, so not sure spawn/expect/send is gonna work.

UPDATE: I tried using printf 'rootpass' | ./script.sh, but it is not working.

7
  • 2
    Think about installing packages using sudo Commented Nov 27, 2020 at 20:36
  • users can not be a part of sudoer's so we can not add that. we want to read it from a variable and pass it on when prompted. Commented Nov 27, 2020 at 20:52
  • 1
    Typically, you configure sudo so that the user can run yum -y install (and more importantly, no or few other commands) without a password. Commented Nov 27, 2020 at 22:57
  • 1
    Look into expect instead. Commented Nov 28, 2020 at 0:17
  • Security wise, this is bad, very bad. It means you will have to store the root password somewhere on the origin server to send it to the remote server. sudo is the way to go since it allows you to limit what commands can be used as well as protect the root password. Commented Nov 28, 2020 at 2:31

1 Answer 1

1

As commented, and illustrated here, expect is a better option.

pw="Password1234"

expect -f - <<-EOF
  set timeout 10

  spawn sudo yum -y install <package>
  expect "*?assword*"
  send -- "$pw\r"
  expect eof
EOF

However, It is best for any script to not include the password itself directly, but rather to fetch that password from an external source, preferable a vault.
Typically, such a script would be run by a tool like Ansible, using ansible-community/ansible-vault. Only Ansible would have the Vault password, Valut which in turn would have the sudo password.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.