在远程计算机上执行脚本

时间:2020-09-02 17:31:19

标签: bash

我有一堆需要在远程计算机上执行的脚本文件。脚本文件以服务器名称开头。它们位于/ opt / local目录

例如

server1.sh
server2.sh
server3.sh

使用循环,我需要遍历每个文件。

  1. 从列表中提取名称(例如server1)
  2. 在server1的名称后附加.example.com
  3. ssh user1@server1.example.com
  4. 执行/opt/local/server1.sh
  5. 如果成功写入/opt/files/success.log,则成功执行server1.sh 6.如果未成功写入/opt/files/errors.log,则server1.sh失败,包括无法登录,无法执行脚本或类似内容。

'''

#!/bin/bash
FILES=/opt/local
for f in $FILES
do
  name="${FILE%%.*}"
  name="${name}.example.com"
  ssh user1@name "bash -s" ./${f}

done

'''

2 个答案:

答案 0 :(得分:0)

#!/bin/bash
MYNAME=$(basename $0)
WRKDIR=/opt/local
SUF=".sh"
# LOGDIR: create and set permissions for user before running this script
LOGDIR="/var/log/$MYNAME"
LOGFILE="$LOGDIR/$MYNAME-$(date '+%Y-%m-%d').log"
exec 1>>$LOGFILE
exec 2>&1
find $WRKDIR -name "*$SUF" | while read SCRIPTNAME
do
   SERVER=$(basename $SCRIPTNAME $SUF)
   echo "$(date): started $SERVER ..."
   URL="$SERVER.example.com"
   echo CMD: ssh user1@$URL "bash -s" $SCRIPTNAME \
   && ssh user1@$URL "bash -s" $SCRIPTNAME
   echo "$(date): done $SERVER"
   echo "------------------------------------"
done

答案 1 :(得分:0)

您的脚本可能如下所示:

dir=/opt/local
for file in "$dir"/*; do
     # extract name from the list (e.g. server1)
     name="${file%%.*}"
     # append .example.com after the name of the server1
     addr="${name}.example.com"
     # execute /opt/local/server1.sh
     if ssh "user1@$addr" "bash -s" < "$file"; then
          # if successful write to /opt/files/success.log server1.sh successfully executed 6
          printf "%s %s\n" "$name" "successfully executed 6" >> /opt/files/success.log
     else
         # if not successful write to /opt/files/errors.log, server1.sh not successful including unable to login, unable to execute script or something like this.
         printf "%s %s\n" "$name" "not successful including unable to login, unable to execute script or something like this" >> /opt/files/error.log
     fi
done