2013-07-16 58 views
0

當我將ssh發送到服務器後,如何從腳本遠程運行一段代碼?不知道它是否可能。在SSH連接後運行一段代碼Bash

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 
+0

[通過bash腳本SSH命令]的可能重複(http://stackoverflow.com/questions/4225652/ssh-commands-via-bash-script) – devnull

+1

問題還要求對[UNIX和Linux](HTTP: //unix.stackexchange.com/q/83228/4667) –

+0

[在SSH中運行多個命令的最簡潔的方法是什麼?](http://stackoverflow.com/questions/4412238/whats-the- CLEARSTEST-way-to-ssh-and-run-multiple-commands-in-bash) – mnagel

回答

1

您可以通過使用here-document(未經測試)執行此操作。請記住,你將不得不逃避在ssh服務器上定義的變量。

ssh $server <<ENDSSH 
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 
ENDSSH 
+0

我不斷收到這個錯誤../ test.bsh:第3行:語法錯誤在第24行:'<<'無法匹配 It不喜歡<< ENDSSH – mkrouse

+0

@mkrouse將最後一個'ENDSSH'放在它自己的行上,並確保它之前或之後沒有字符。 –

+0

必須小心哪些變量應該由本地運行的shell進行擴展,哪些需要轉義,以便在遠程shell上進行擴展。 –

相關問題