简体   繁体   English

如何使用 bash 脚本安全地在 ssh 上运行多个 sudo 命令并且只输入一次密码

[英]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.我正在尝试编写一个本地 Bash 脚本以自动(设置为由 cron 运行)通过 SSH 执行多个远程任务,包括一些需要 sudo 的任务。 I want the password to be read from file, then logon via ssh, and then any remote sudo commands.我希望从文件中读取密码,然后通过 ssh 登录,然后通过任何远程 sudo 命令登录。 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:您需要为此使用引号,一个 -t 就足够了:

#! /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我使用heredoc想出了这个,但@wuseman解决方案看起来更干净

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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