Reputation: 11
i have this script that its goal is to compare /var/adm/messages and check if the current last line is equal or not to the latest line that was checked. the problem is that even if the strings are identical still the script treat them as not equal and continue to the if statement. here's the script:
#!/usr/bin/perl
use strict;
use warnings;
open (MESSAGES, "tail -1 /var/adm/messages |" ) || die "failed to open alarms file \n$!\n\a";
open (ERRORLOG, ">>/usr/local/bin/mcdl_errors.log") || die "failed to open errorlog file \n$!\n\a";
my $last_line = `cat /usr/local/bin/line.txt`;
while (my $this_line = <MESSAGES>) {
chomp($this_line);
if ($this_line =~ m/inet|hyena|root/i) {
if ($this_line ne $last_line) {
print "$this_line\n";
print "$last_line\n";
`echo $this_line > /usr/local/bin/line.txt`;
}
}
}
close (MESSAGES);
close (ERRORLOG);
Upvotes: 0
Views: 144
Reputation: 908
Issue 1: You need to chomp $last_line (echo will add a \n) as someone already pointed out.
Issue 2: Passing an unquoted string on a command line will cause the shell to parse it, which will likely lose characters that get interpreted by the shell (multiple spaces or tabs reduced to one space, quotes removed etc). When that happens, the last_line that you read in next time will not match the line in the log anymore.
Issue 3: Passing an untrusted string to the shell is a very bad idea as it is easy for an attacker to inject an extra command to run into the string and hence gain unauthorised access. Passing log strings to a shell unescaped is very dangerous.
All in all, you would be much better off writing line.txt using perl file operations rather than the shell.
Upvotes: 6