仅从 nmap IP 地址返回值并将其传递到 Bash 中的循环中

仅从 nmap IP 地址返回值并将其传递到 Bash 中的循环中

我有一个 nmap 脚本,它只从网络中检索活动的 IP 设备。

nmap -sP 192.168.1.0/24 | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}'

我想从 nmap 获取结果 IP 地址以循环执行以下命令,据我了解,多个结果可能没有来自 nmap 的任何返回值。

echo "# This script checks if a remote device is alive"
read va * This is suppose to receive the IP address one by one
echo "Checking Device "$va
if [ $(nc -z "$va" 22; echo $?) -eq 0 ]; then
echo $va" is Online !"
else
echo "Cannot proceed with remote connection device "$va" is Offline !"
fi

答案1

您也可以使用 nmap 检查打开的 tcp 端口 22。

nmap -p 22 192.168.1.0/24 -oG - | grep -oP "Host: \K[^ ]+(?=.* 22/open/tcp.*)"

答案2

欢迎来到 unix.stackexchange !

xargs是你的朋友吗?

但首先对您的脚本进行一些更改:

$ cat test.sh
#!/bin/bash
echo "# This script checks if a remote device is alive"
va=$1 # passing it as an argument is the right thing to do here
echo "Checking Device "$va
if [ $(nc -z "$va" 22; echo $?) -eq 0 ]; then
    echo $va" is Online !"
else
    echo "Cannot proceed with remote connection device "$va" is Offline !"
fi

现在xargs魔术(%将被每次调用时的每个地址替换):

$ nmap -sP 172.20.10.1-2 | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}' |xargs -I % bash test.sh %
# This script checks if a remote device is alive
Checking Device 172.20.10.1
Cannot proceed with remote connection device 172.20.10.1 is Offline !
# This script checks if a remote device is alive
Checking Device 172.20.10.2
Connection to 172.20.10.2 port 22 [tcp/ssh] succeeded!
172.20.10.2 is Online !

您还可以替换bash test.sh %echo ">>>%<<<"以试验随后会发生什么。

然而,Ipor Sircer 的答案实施起来较短。

但与 Unix 一样:每个问题都有很多解决方案

相关内容