awk remote ssh command

2019-09-10 19:22发布

I have a bash script that run a remote awk command but I guess I haven't correctly escape specials characters since no file is generated on the remote server. Still I have no error.

My variables are declared locally and can be used remotely without issue (other part of the script confirm this).

ssh -q -t server '
        logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -'"$past"')
        for log in $logfiles;
             awk -vDate=\`date -d'now-'"$past"' minutes' +[%d/%b/%Y:%H:%M:%S\` ' { if \(\$4 > Date\) print \$0}' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16
        done
'

Thank you!


EDIT1:

passing this script

#!/bin/bsh

logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -120)
for log in $logfiles; do
        awk -vDate=`date -d'now-120 minutes' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print $0}' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16 > /root/httpd.log;
done

like this works

ssh user@host < script.sh

When I run the same script from the console :

ssh -q -t $apache '     
logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -120)
for log in $logfiles; do
awk -vDate=`date -d'now-120 minutes' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print $0}' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16 > /root/httpd.log;
done'

    -bash: syntax error near unexpected token `('

So I tried to escape the parenthesis

ssh -q -t $apache '
logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -120)
for log in $logfiles; do
awk -vDate=`date -d'now-120 minutes' +[%d/%b/%Y:%H:%M:%S` ' { if \($4 > Date\) print $0}' /var/log/httpd/royalcanin_com.access_log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16 > /root/httpd.log;
done'

but then nothing is generated.


EDIT2:

Having the file generated on the server but empty with this:

awk -vDate=\`date -d'now-120 minutes' +[%d/%b/%Y:%H:%M:%S\` ' { if '"($4 > Date)"' print $0}' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16 > /root/httpd.log;done'

标签: bash shell ssh awk
1条回答
做个烂人
2楼-- · 2019-09-10 19:53

You also need to escape your single quotes. For example, the first script…

ssh -q -t server '
        logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -'"$past"')
        for log in $logfiles;
             awk -vDate=\`date -d'now-'"$past"' minutes' +[%d/%b/%Y:%H:%M:%S\` ' { if \(\$4 > Date\) print \$0}' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16
        done
'

… must really be written as:

ssh -q -t server '
        logfiles=$(find /var/log/httpd/ -type f -name *access_log -cmin -'\''"$past"'\'')
        for log in $logfiles;
             awk -vDate=\`date -d'\''now-'\''"$past"'\'' minutes'\'' +[%d/%b/%Y:%H:%M:%S\` '\'' { if \(\$4 > Date\) print \$0}'\'' $log | sort  |uniq -c |sort -n | tail | cut -d " " -f 11,15,16
        done
'
查看更多
登录 后发表回答