使用Bash检查数组中的IP是否正确

时间:2011-10-04 09:49:42

标签: arrays bash awk ip

我正在尝试编写一个bash脚本,它将获取who的输出,用awk解析IP地址,然后根据IP地址数组进行检查...听起来很简单但是我把它放在一起的脚本确实似乎不起作用,我已经在OSX和Ubuntu上测试过,有人能找到原因吗?

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 - $remote_connected_ip"
   else
      echo "ip was not ok - $remote_connected_ip"
   fi
done;

它不断报告每个IP为" ip不正常"

干杯!3

2 个答案:

答案 0 :(得分:2)

你没有引用你的变量,所以awk没有看到你认为它看到的东西:你需要

for word in "$who"; do
   remote_connected_ip=`echo "$word" | awk '/(23)/ {print $5}'`

这可能更干净,不需要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  

答案 1 :(得分:1)

if [[ $safe_id == ...

应该是:

if [[ $safe_ip ==

如果涉及 awk ,您可以在 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"
     }'