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.

ajay_t
  • 2,347
  • 7
  • 37
  • 62
  • 2
    Think about installing packages using sudo – Raman Sailopal Nov 27 '20 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. – ajay_t Nov 27 '20 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. – chepner Nov 27 '20 at 22:57
  • 1
    Look into `expect` instead. – Shawn Nov 28 '20 at 00: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. – Nic3500 Nov 28 '20 at 02:31
  • Your current script would execute `cd ~` etc only after `su` finishes. See also https://stackoverflow.com/questions/37586811/pass-commands-as-input-to-another-command-su-ssh-sh-etc – tripleee Nov 30 '20 at 08:20
  • Saving a script in a variable is almost never the correct thing to do; see also http://mywiki.wooledge.org/BashFAQ/050 – tripleee Nov 30 '20 at 08:21

1 Answers1

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250