ajay_t
ajay_t

Reputation: 2385

How to provide password when prompted in shell script

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.

Upvotes: 1

Views: 2011

Answers (1)

VonC
VonC

Reputation: 1323753

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.

Upvotes: 1

Related Questions