Reputation: 1463
I have 2 script. Script "A", Script "B".
Script A is regulary watching the dhcpacks
[dhcp release is configured to 2mins] in the logs, for the past 2 minutes. It writes the MAC addresses to a file [/dev/shm/dhcpacks-in-last-2min.txt
] every 2 minutes. Ok, this is working, active clients are in this file. Super!
Script B: On pastebin
I'm trying to create a script, that watches the changes in /dev/shm/dhcpacks-in-last-2min.txt
file ( every 1 sec). Ok. But: my watcher script the pastebined is not working fine - sometime it works, sometime it sends that someone XY logged out
, but it's not true! Nothing happened, and the problem is not in the Script A.
Can someone help me point out, what am I missing? How can I watch a file (in every sec), that contains only MAC addresses, and if someone doesn't get dhcpack
in 2 minutes, the file /dev/shm/dhcpacks-in-last-2min.txt
changes, and that clients MAC address will be gone from it, and i need to know, who was it [pastebined my script - but somethings wrong with it].
Thank you for any help..I've been pathing my script for days now.. :\
Upvotes: 1
Views: 2043
Reputation: 16562
Make sure the files you are comparing are sorted. The best way is to modify script A.
Your script is attempting to parse an unified diff. Unless specified otherwise (with -u
), diff
outputs a "normal" diff, with changes marked by <
and >
.
You have to separate the mail header and body with two newlines.
On Linux, the best way to watch files is through Inotify, either inotifywait
or incron
.
My attempt at rewriting the script:
#!/usr/bin/env bash
[email protected]
file=/dev/shm/dhcpacks-in-last-2min.txt
cp "$file" "$file.old"
inotifywait -qme modify "$file" | while read -r _; do
if ! cmp -s "$file.old" "$file"; then
changes=$(diff "$file.old" "$file" | sed -n "s/^</logged out:/p; s/^>/logged in:/p" | tr A-Z a-z)
subj="$(date) - $(hostname) - $(echo "$changes" | sed "s/$/,/" | tr "\n" " ")"
# In a well-configured system, this would be enough:
#mail -s "$subj" "$rcpt" <<< "$changes"
# But if yours is not,
echo -e "From: <$rcpt>\nSubject: $subj\nTo: <$rcpt>\n\n$changes\n" | ssmtp "$rcpt"
cp "$file" "$file.old"
fi
done
Upvotes: 4