如何使用shell脚本从vsftpd日志中提取文件名?

时间:2018-02-06 14:19:57

标签: linux shell vsftpd

我正在使用vsftpd,我想从成功上传中提取文件名。 记录示例:

Tue Feb  6 11:49:25 2018 [pid 13018] [xyz] OK UPLOAD: Client "1.2.3.4", "/filename.zip", 131072000 bytes, 19607.40Kbyte/sec
Tue Feb  6 11:49:25 2018 [pid 13017] [xyz] OK UPLOAD: Client "1.2.3.4", "/filename.zip", 131072000 bytes, 24426.38Kbyte/sec
Tue Feb  6 11:49:30 2018 [pid 13018] [xyz] OK UPLOAD: Client "1.2.3.4", "/filename.zip", 131072000 bytes, 25387.19Kbyte/sec

我正在使用此代码:

#!/bin/sh

tail -F /var/log/vsftpd.log | while read line; do
  if echo "$line" | grep -q 'OK UPLOAD:'; then
    line=$(echo "$line" | tr -s " ")
    filename=$(echo "$line" | cut -d, -f2)
    echo "$filename"
  fi
done

问题是如果文件名里面有逗号,它将无法正常工作。

1 个答案:

答案 0 :(得分:2)

不要使用bash命令,最好将此gnu awk解决方案与FPAT一起使用:

tail /var/log/vsftpd.log |
awk -v FPAT='\\[[^]]*\\]|"[^"]*"' '/OK UPLOAD/{gsub(/[][]/, "", $2);
gsub(/"/, "", $4); cmd=sprintf("echo php /path/to/my/script.php \"%s\" \"%s\"", $2, $4);
cmd | getline result; close(cmd); print result}'

php /path/to/my/script.php xyz /filename.zip
php /path/to/my/script.php xyz /filename.zip
php /path/to/my/script.php xyz /filename.zip

对输出感到满意后,请在echo之前删除php