如何使用 shell 脚本 ping 一个文件中的多个 IP,并仅打印另一个文件中的在线 IP?
How to ping many IPs in a file, and print only the online ones in another file using shell script?
我有一个包含很多 ip 的文件,我想遍历它们,对它们执行 ping 命令,然后打印到另一个在线文件。我知道循环文件,ping 它们,但我不知道如何读取输出以了解 ip 是否在线。
只需检查ping 命令的退出状态。
if ping ...; then echo online; fi
请注意,您必须使用 -c
和 -w
标志来限制 ping 时间。
你可以使用 nmap
:
cat queryips.txt
192.168.1.1
192.168.20.7
10.2.4.6
google.com
nmap -iL queryips.txt -sn -n -oG upips.txt
-iL queryips.txt
从 queryips.txt
文件加载主机列表
-sn
执行 ping 扫描
-n
不要进行反向 DNS 查找
-oG upips.txt
生成 grepable 输出到 upips.txt
文件
cat upips.txt
# Nmap 6.47 scan initiated Thu Dec 31 12:12:27 2015 as: nmap -iL queryips.txt -sn -n -oG upips.txt
Host: 192.168.1.1 () Status: Up
Host: 192.168.20.7 () Status: Up
Host: 173.194.116.72 () Status: Up
# Nmap done at Thu Dec 31 12:12:28 2015 -- 4 IP addresses (3 hosts up) scanned in 1.26 seconds
或者打印符合标准输出的主机:
nmap -iL queryips.txt -sn -n -oG - | awk -F" " '!/#/ {print }'
使用这个脚本
1. File full of IP's
[root@localhost scripts]# cat iplist.txt
172.31.57.63
localhost
127.0.0.1
172.31.57.62
2. Create the script
[root@localhost scripts]# cat pingips.sh
#!/bin/bash
up_ipfile='online_server.txt'
while IFS= read -r ips; do
ping -c 1 $ips > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo $ips >> $up_ipfile
fi
done < iplist.txt
3. Run the script after making it executable
[root@localhost scripts]# ./pingips.sh
4. It will create a file with IP's which are alive
[root@localhost scripts]# cat online_server.txt
172.31.57.63
localhost
127.0.0.1
我有一个包含很多 ip 的文件,我想遍历它们,对它们执行 ping 命令,然后打印到另一个在线文件。我知道循环文件,ping 它们,但我不知道如何读取输出以了解 ip 是否在线。
只需检查ping 命令的退出状态。
if ping ...; then echo online; fi
请注意,您必须使用 -c
和 -w
标志来限制 ping 时间。
你可以使用 nmap
:
cat queryips.txt
192.168.1.1
192.168.20.7
10.2.4.6
google.com
nmap -iL queryips.txt -sn -n -oG upips.txt
-iL queryips.txt
从queryips.txt
文件加载主机列表-sn
执行 ping 扫描-n
不要进行反向 DNS 查找-oG upips.txt
生成 grepable 输出到upips.txt
文件
cat upips.txt
# Nmap 6.47 scan initiated Thu Dec 31 12:12:27 2015 as: nmap -iL queryips.txt -sn -n -oG upips.txt
Host: 192.168.1.1 () Status: Up
Host: 192.168.20.7 () Status: Up
Host: 173.194.116.72 () Status: Up
# Nmap done at Thu Dec 31 12:12:28 2015 -- 4 IP addresses (3 hosts up) scanned in 1.26 seconds
或者打印符合标准输出的主机:
nmap -iL queryips.txt -sn -n -oG - | awk -F" " '!/#/ {print }'
使用这个脚本
1. File full of IP's
[root@localhost scripts]# cat iplist.txt
172.31.57.63
localhost
127.0.0.1
172.31.57.62
2. Create the script
[root@localhost scripts]# cat pingips.sh
#!/bin/bash
up_ipfile='online_server.txt'
while IFS= read -r ips; do
ping -c 1 $ips > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo $ips >> $up_ipfile
fi
done < iplist.txt
3. Run the script after making it executable
[root@localhost scripts]# ./pingips.sh
4. It will create a file with IP's which are alive
[root@localhost scripts]# cat online_server.txt
172.31.57.63
localhost
127.0.0.1