使用 Bash 检查 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
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 - $remote_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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你没有引用你的变量,所以 awk 没有看到你认为它看到的东西:你需要
这可能更干净并且不需要 awk:
You're not quoting your variables, so awk is not seeing what you think it sees: you need
This might be cleaner and does not require awk:
应该是:
鉴于涉及到 awk,您可以在 awk 中完成所有操作:
should be:
Given awk is involved, you could do it all in awk: