Shell脚本ssh $ SERVER >> EOF

问题描述 投票:3回答:2

我这里有一个方便的脚本,可以返回将在7天后过期或已过期的帐户。我想允许它在多台主机上运行,​​而无需将脚本放置在每台主机上,我添加了for loopssh $SERVER >> EOF部分,但它只会在运行脚本的系统之外运行命令。

我相信ssh $SERVER >> EOF是错误的,但是我不确定语法看起来是否正确。

#!/bin/bash

for SERVER in `cat /lists/testlist`
do
  echo $SERVER

  ssh $SERVER >> EOF
    sudo cat /etc/shadow | cut -d: -f1,8 | sed /:$/d > /tmp/expirelist.txt
    totalaccounts=`sudo cat /tmp/expirelist.txt | wc -l`
    for((i=1; i<=$totalaccounts; i++ ))
    do
      tuserval=`sudo head -n $i /tmp/expirelist.txt | tail -n 1`
      username=`sudo echo $tuserval | cut -f1 -d:`
      userexp=`sudo echo $tuserval | cut -f2 -d:`
      userexpireinseconds=$(( $userexp * 86400 ))
      todaystime=`date +"%s"`
      if [[ $userexpireinseconds -ge $todaystime ]] ;
      then
        timeto7days=$(( $todaystime + 604800 ))
        if [[ $userexpireinseconds -le $timeto7days ]];
        then
          echo $username "is going to expire in 7 Days"
        fi
      else
        echo $username "account has expired"
      fi
    done
    sudo rm /tmp/expirelist.txt
  EOF
done
linux bash ssh eof
2个回答
11
投票

这里的文档以<< EOF开始(或者最好是<< 'EOF',以防止此处文档的主体被(本地)外壳扩展),并且结束标记必须在第1列中。

[您正在做的是运行ssh,并将标准输出附加到文件EOF(>>是输出重定向; <<是输入重定向)。然后,它在本地运行sudo,等等。它可能无法执行本地文件EOF(不能执行,有人希望),并且可能也找不到任何其他命令。

[我认为您所追求的是(现在我已经用$(...)表示法替换了脚本中的反引号,并稍微优化了服务器列表的生成以与Bash一起使用):

#!/bin/bash

for SERVER in $(</lists/testlist)
do
  echo $SERVER

  ssh $SERVER << 'EOF'
    sudo cat /etc/shadow | cut -d: -f1,8 | sed '/:$/d' > /tmp/expirelist.txt
    totalaccounts=$(sudo cat /tmp/expirelist.txt | wc -l)
    for ((i=1; i<=$totalaccounts; i++))
    do
      tuserval=$(sudo head -n $i /tmp/expirelist.txt | tail -n 1)
      username=$(sudo echo $tuserval | cut -f1 -d:)
      userexp=$(sudo echo $tuserval | cut -f2 -d:)
      userexpireinseconds=$(( $userexp * 86400 ))
      todaystime=$(date +"%s")
      if [[ $userexpireinseconds -ge $todaystime ]]
      then
        timeto7days=$(( $todaystime + 604800 ))
        if [[ $userexpireinseconds -le $timeto7days ]]
        then
          echo $username "is going to expire in 7 Days"
        fi
      else
        echo $username "account has expired"
      fi
    done
    sudo rm /tmp/expirelist.txt
EOF
done

非常接近,但是差异真的很重要!请特别注意,结束标记EOF在第1列中,完全没有缩进。


0
投票

我尝试使用'EOF or 'EOF' or EOF (the first after <<) but it doesn't work for me, ubuntu 20.04 says "unexpected EOF while looking for matching''。我正在寻找一种将EOF与SSH结合使用的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.