0

在我 ssh 到服务器后,如何从我的脚本远程运行一段代码?不确定它是否可能。

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
4

1 回答 1

2

您可以使用 a 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
于 2013-07-16T14:51:33.857 回答