【问题标题】:How to run multiple sudo command over ssh using bash script securely and only entering password once如何安全地使用 bash 脚本在 ssh 上运行多个 sudo 命令并且只输入一次密码
【发布时间】:2020-10-12 17:21:43
【问题描述】:

我正在尝试编写一个本地 Bash 脚本以自动(设置为由 cron 运行)通过 SSH 执行多个远程任务,包括一些需要 sudo 的任务。我希望从文件中读取密码,然后通过 ssh 登录,然后使用任何远程 sudo 命令。我还想确保密码不是通过网络以明文形式或在远程计算机的历史记录中发送的。

(类似下面的东西不起作用)

#! /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

【问题讨论】:

    标签: linux bash ubuntu ssh


    【解决方案1】:

    您需要为此使用引号,一个 -t 就足够了:

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

    【讨论】:

    • 我应该提到一些我需要做的任务需要 sed、awk、grep 和其他有时需要单引号和双引号的实用程序(为什么我使用 heredoc)。您的代码是否有一些调整可以让我在某些命令中同时使用单引号和双引号?
    • 只需在远程服务器上运行的命令上转义双引号,它会正常工作,在 whoami 后面尝试添加 |sed 's/root/user/g' "
    • 工作就像一个魅力。非常感谢。
    • 欢迎您,如果它工作正常,请不要忘记将其设置为已解决。 // wuseman
    【解决方案2】:

    我使用 heredoc 想出了这个,但@wuseman 解决方案看起来更干净

    #!/bin/bash
    password=`cat sudopasswordfile`
    
    ssh -t user@host  <<EOF
      echo "$password" | sudo -S whoami
      echo "$password" | sudo df -hT
    EOF
    

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2023-03-26
      • 1970-01-01
      • 2016-11-09
      • 2012-10-01
      • 2011-09-10
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多