while读取文件时,可按行标分割赋值!!!
for读取文件时,默认按空格分割赋值!!!
使用while read来读取host.txt
[root@ffing ~]# cat host.txt
172.16.207.128 22
172.16.207.129 22
172.16.207.131 80
172.16.207.132 22
172.16.207.132 8080
172.16.207.132 8005
192.168.0.222 333
-------------------------------------------------------
[root@ffing ~]# cat while_read.sh
#定义变量名为ip
while read ip
do
echo "IP:$ip"
done <host.txt
[root@ffing ~]# bash while_read.sh
IP:
IP:172.16.207.128 22
IP:172.16.207.129 22
IP:172.16.207.131 80
IP:172.16.207.132 22
IP:172.16.207.132 8080
IP:172.16.207.132 8005
IP:192.168.0.222 333
while read也可使用EOF读取数据
[root@ffing ~]# cat while.sh
while read VAR
do
echo $VAR
done <<EOF
百度 www.baidu.com 80
腾讯 www.qq.com 80
新浪 www.sina.com 80
EOF
[root@ffing ~]# bash while.sh
百度 www.baidu.com 80
腾讯 www.qq.com 80
新浪 www.sina.com 80
for 利用` ` 或 $()执行命令来读取,但for默认以空格为分隔符!!!
注:` `等于$() ;cat host.txt等于 <host.txt
因此:`cat host.txt`==$(cat host.txt)==`< host.txt`==$(< host.txt)
[root@ffing ~]# cat host.txt
172.16.207.128 22
172.16.207.129 22
172.16.207.131 80
172.16.207.132 22
172.16.207.132 8080
172.16.207.132 8005
192.168.0.222 333
-------------------------------------------------------
[root@ffing ~]# cat for.sh
for VAR in `<host.txt`
do
echo $VAR
done
[root@ffing ~]# bash for.sh
172.16.207.128
22
172.16.207.129
22
172.16.207.131
80
172.16.207.132
22
172.16.207.132
8080
172.16.207.132
8005
192.168.0.222
333
理解上面的读取文件,执行telnet就简单了
避免telnet端口不通,而导致超时时间过过长,加入timeout命令。(也可以使用expect命令配合timeout也可以)
#[root@ffing ~]# cat telnet-while_read.sh
#`时间戳`
DATE=`date +%F_%T`
#定义变量名为ip
while read ip
do
echo "IP:$ip"
#使用timeout命令3秒后退出telnet,解决端口不通的等待延迟。(也可以配置timeout信号--signal=9 )
( timeout 3 telnet $ip >/tmp/telnet.$DATE."$ip".tmp 2>&1 )&
done <host.txt
wait
echo ----------------------------------------------
echo "telnet 成功如下:"
cat /tmp/telnet.$DATE.* |grep -B1 'Escape character is'|grep "Connected to"|awk '{print $NF}'
发表评论