Linux扫描网段主机是否可通

  1. 单纯扫描

    #!/bin/sh
    
    declare -i I=1
    declare -i S=100
    while [ $I -le $S ] ; do
        IP="192.168.1.$I"
        STATE=`ping $IP -c 1 | grep time=0. | awk '{print $8}'`
        echo -n "$IP            "
        if [ "$STATE" = "ms" ] ; then
                echo "yes"
        else
                echo "no"
        fi
    I+=1
    done
    
    
  2. 扫描并打印

    #!/bin/sh
    
    declare -i I=1
    declare -i S=100
    while [ $I -le $S ] ; do
        IP="192.168.1.$I"
        STATE=`ping $IP -c 1 | grep time=0. | awk '{print $8}'`
        echo -n "$IP            "
        if [ "$STATE" = "ms" ] ; then
                echo "yes"
        else
                echo "no"
        fi
    I+=1
    done
    [root@jk-zhengwu03 ~]# cat scan2.sh
    #!/bin/bash
    
    echo $$
    NETADDR=172.19.66.
    IP=0
    while [ $IP -lt 100 ]
    do
    let IP++
    if ping -c2 -i0.2 -w2 $NETADDR$IP &> /dev/null
    then   echo $NETADDR$IP >> /root/upiplist.txt
    else echo -e "$NETADDR$IP down"
    fi
    done
    
    

扫描批量主机端口开放情况

示例代码:

#!/bin/bash

port=22
if [ $# -eq 0 ]
then
        echo "您没有输入参数,将使用默认端口扫描,默认端口是22"
else
        echo "您自定了端口,您的端口是:"
        echo 'port=$1'
        port=$1
fi

echo $port

NETADDR=172.19.66.
IP=0

while [ $IP -lt 256 ]

trap 'onCtrlC' INT
function onCtrlC () {
        echo 'Ctrl+C is captured'
        exit 1
}

do
        let IP++
        echo $NETADDR$IP
        echo -e "\n" | telnet $NETADDR$IP $port | grep -i "connected" >> /root/telnetIP.log
done


exit 0

扫描指定主机所有端口开放情况

脚本解释:扫描主机172.19.66.60,端口从1到8888的开放情况

#!/bin/bash

IP=172.19.66.60

PORT=0

while [ $PORT -le 8888 ]

trap 'onCtrlC' INT
function onCtrlC () {
        echo 'Ctrl+C is captured'
        exit 1
}

do
        if [ $PORT -eq 8888 ]
                then exit 1
        fi

        let PORT++
        echo '当前端口:'$IP:$PORT
        echo -e "\n" | telnet $IP $PORT | grep -i "connected" && echo $IP:$PORT >> /root/telnetPort.log
done

echo "执行结束"

exit 0