Execute after upload script on vsftpd

Premessa/Disclaimer: da un po' di tempo a questa parte sto "coltivando" una cartella chiamata "Appunti di informatica" sul mio Mac. In questa cartella raccolgo appunti sui più svariati argomenti e mini-guide per ricordarmi "come si fa" qualcosa, man mano che mi ritrovo ad affrontarle. Gli argomenti spaziano dalla gestione sistemistica in ambito Windows-Linux-OSX, allo sviluppo software su iOS e PHP, con qualche variazione sul tema. Le mini-guide saranno spesso brevi e molto pratiche, soprattutto perchè non ho molto tempo per abbellirle e renderle accattivanti per il pubblico, se vi servono dettagli non esitate a contattarmi.

First thing to do: go inside your vsftpd.conf file and enable the xfer log

xferlog_enable=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=NO

then, create this bash script (i’m not a bash expert so many things can be not optimized, but the important thing is that this script works 😉

#!/bin/bash
#put inside this dir the list of directories where you want to change permissions
#since vsftpd logfile doesn’t give us the full path, we have to try to apply the permissions to all directories
function changePermission {
local finalfilename=$1
chown www-data:www-data "/path/without/lasts_lash$finalfilename"
chmod 775 "/path/without/last_slash$finalfilename"
}

#tail -F on the log file,
tail -F /var/log/vsftpd.log | while read line; do
#if OK UPLOAD or OK MKDIR is found in the log line
if echo "$line" | grep -q 'OK UPLOAD:'; then
#cut the found line to find the start of the file name (-d, search for a comma delimiter, -f2 takes the second parameter delimited by the previously configured delimiter)
filename=$(echo "$line" | cut -d, -f2)
#cut the found line to remove the first space and the “
filename2=$(echo "$filename" | cut -c 3-)

#cut the found line to remove the last “
finalfilename=${filename2%?}
#executes the function
changePermission "$finalfilename"
fi
if echo "$line" | grep -q 'OK MKDIR:'; then
filename=$(echo "$line" | cut -d, -f2)
filename2=$(echo "$filename" | cut -c 3-)
finalfilename=${filename2%?}
changePermission "$finalfilename"
fi
done

This script must be executed one time (at the boot, for example).
It will monitor the ftp log, and when “OK UPLOAD:” or “OK MKDIR:” is found, applies the permission to the files.