bash 在 shell 脚本中增加 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33056385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment IP address in a shell script
提问by Luca Giordano
It is possible to write this script in another way to increment ip address whitout loops like this? Script, a port scanner, works fine and mine is only a question about efficiency. Sorry for my english and thanks for your answers.
可以用另一种方式编写这个脚本来增加这样的 ip 地址 whitout 循环吗?脚本,一个端口扫描器,工作正常,我的只是一个关于效率的问题。对不起我的英语,感谢您的回答。
#!/bin/bash
ip=
IFS=. read i1 i2 i3 i4 <<< "$ip"
port=
max=255
while [ $i1 -le $max ];do
while [ $i2 -le $max ]; do
while [ $i3 -le $max ]; do
while [ $i4 -le $max ]; do
timeout 0.4 bash -c "echo >/dev/tcp/$i1.$i2.$i3.$i4/$port" && echo "on $i1.$i2.$i3.$i4 port $port is open"
i4=$(($i4+1))
done
i4=0
i3=$(($i3+1))
done
i3=0
i2=$(($i2+1))
done
i2=0
i1=$(($i1+1))
done
回答by kvaps
This function just prints next ip:
这个函数只是打印下一个ip:
nextip(){
IP=
IP_HEX=$(printf '%.2X%.2X%.2X%.2X\n' `echo $IP | sed -e 's/\./ /g'`)
NEXT_IP_HEX=$(printf %.8X `echo $(( 0x$IP_HEX + 1 ))`)
NEXT_IP=$(printf '%d.%d.%d.%d\n' `echo $NEXT_IP_HEX | sed -r 's/(..)/0x /g'`)
echo "$NEXT_IP"
}
So you can increment it like:
所以你可以像这样增加它:
FIRST_IP=192.168.1.250
NUM=10
IP=$FIRST_IP
for i in $(seq 1 $NUM); do
echo $IP
IP=$(nextip $IP)
done
Sample output:
示例输出:
192.168.1.250
192.168.1.251
192.168.1.252
192.168.1.253
192.168.1.254
192.168.1.255
192.168.2.0
192.168.2.1
192.168.2.2
192.168.2.3
回答by Cyrus
Take a look at:
看一眼:
i1=0; i2=0; i3=0; i4=0
max=255
eval printf -v ip "%s\ " {$i1..$max}.{$i2..$max}.{$i3..$max}.{$i4..$max}
for i in $ip; do
# do here somthing with $i
done