简体   繁体   中英

How to run multiple sudo command over ssh using bash script securely and only entering password once

I'm trying to write a local Bash script to automatically (set to run by cron) do multiple remote tasks via SSH including some that require sudo. I want the password to be read from file, then logon via ssh, and then any remote sudo commands. I also want to make sure the password isn't being sent over network by clear text or in the history of the remote computer.

(something like below which doesn't work)

#! /bin/bash

sshpass -f mypasswordfile ssh -tt remoteid@remotesever  << EOF
$hostname  # remote server name 
sudo apt update
sudo apt upgrade -y
whoami
# etc.. etc.. assortment of health, security and other maintenance tasks
EOF

You need use quotes for this and one -t is enough:

#! /bin/bash

ssh -t remoteid@remotesever "\
  sudo -S apt update; \
  sudo -S apt upgrade -y; \
  sudo -S whoami" <<< $(cat mypasswordfile)

i came up with this using heredoc but @wuseman solution looks much cleaner

#!/bin/bash
password=`cat sudopasswordfile`

ssh -t user@host  <<EOF
  echo "$password" | sudo -S whoami
  echo "$password" | sudo df -hT
EOF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM