SSH接続後にスクリプトを実行する方法

SSH接続後にスクリプトを実行する方法

いろいろな正解と誤解を聞きましたが、これが可能かどうかはまだわかりません。 SSH経由でサーバーに接続してスクリプトを実行したいと思います。

while read server <&3; do   #read server names into the while loop    
serverName=$(uname -n)
 if [[ ! $server =~ [^[:space:]] ]] ; then  #empty line exception
    continue
 fi   
 echo server on list = "$server"
 echo server signed on = "$serverName"
 if [ $serverName == $server ] ; then #makes sure a server doesn't try to ssh to itself
    continue
 fi
    echo "Connecting to - $server"
    ssh "$server"   #SSH login
    echo Connected to "$serverName"
    exec < filelist.txt
    while read updatedfile oldfile; do
    #   echo updatedfile = $updatedfile #use for troubleshooting
    #   echo oldfile = $oldfile   #use for troubleshooting
               if [[ ! $updatedfile =~ [^[:space:]] ]] ; then  #empty line exception
                continue # empty line exception
               fi
               if [[ ! $oldfile =~ [^[:space:]] ]] ; then  #empty line exception
                continue # empty line exception
               fi 
            echo Comparing $updatedfile with $oldfile
            if diff "$updatedfile" "$oldfile" >/dev/null ; then
                echo The files compared are the same. No changes were made.
            else
                echo The files compared are different.
                cp -f -v $oldfile /infanass/dev/admin/backup/`uname -n`_${oldfile##*/}_$(date +%F-%T)
                cp -f -v $updatedfile $oldfile 
            fi          
    done        
 done 3</infanass/dev/admin/servers.txt

サーバーにSSHで接続したら、コードブロックを実行したいと思います。

ベストアンサー1

現在経験している問題は、SSH接続がスクリプトを「一時停止」し、スクリプトはecho Connected to "$serverName"SSHセッションが終了した後にのみその行を再開することです。

2つのオプションがあるようです。 (おそらくもっとあるようですが、現在思い出しているのはこの2つです。)

オプション 1 は、expectスクリプト可能な SSH セッションを開始して、基本スクリプトから SSH セッションにコマンドを効果的に転送することです。オプション2は、リモートで実行したいブロックをリモートサーバー上の他のスクリプトとして配置し、SSHを介して非対話式に実行することですssh $server $script-to-run

おすすめ記事