I am trying to write a bash script which will take the output of who, parse it with awk pulling the IP address and then checking it against an array of IP addresses...sounds simple but they script I have put together does not seem to work, I have tested it on OSX and Ubuntu, can anyone spot why?
ip_address_is_safe() {
local address_to_test=$1;
for safe_ip in "${safe_ips[@]}"
do
if [[ $safe_ip == $address_to_test ]];
then
return 0;
fi
done;
return 1;
}
who="root pts/0 2011-10-03 23:13 (99.99.999.999)
root pts/0 2011-10-03 23:13 (12.12.121.121)
root pts/0 2011-10-03 23:13 (14.14.141.141)
root pts/0 2011-10-03 23:13 (127.0.0.1)
";
safe_ips=("(14.14.141.141)" "(127.0.0.1)")
old_ifs=$IFS;
export IFS="
";
for word in $who; do
remote_connected_ip=`echo $word | awk '/(23)/ {print $5}'`;
if (ip_address_is_safe "$remote_connected_ip")
then
echo "ip was ok - $remot开发者_StackOverflowe_connected_ip"
else
echo "ip was not ok - $remote_connected_ip"
fi
done;
It keeps reporting every IP as "ip was not ok"
Cheers!3
You're not quoting your variables, so awk is not seeing what you think it sees: you need
for word in "$who"; do
remote_connected_ip=`echo "$word" | awk '/(23)/ {print $5}'`
This might be cleaner and does not require awk:
who | while read name tty date time ip; do
if ip_address_is_safe $ip; then
echo $ip ok
else
echo $ip not ok
fi
done
if [[ $safe_id == ...
should be:
if [[ $safe_ip ==
Given awk is involved, you could do it all in awk:
who |
awk 'BEGIN {
n = split("(14.14.141.141) (127.0.0.1)", t)
for (i = 0; ++i <= n;) safe_ips[t[i]]
}
$NF {
print "ip was", ($NF in safe_ips ? x : "not"), "OK"
}'
精彩评论