【问题标题】:Dectect OS from ping with bash script?使用 bash 脚本从 ping 中检测操作系统?
【发布时间】:2020-07-09 13:39:34
【问题描述】:
  1. 问题:所以最近我想尝试编写一个简单的脚本来从 ping 脚本中检测操作系统(基于 TTL(生存时间))

  2. 我尝试过的事情:我尝试过一些类似的事情

#!/bin/bash                                                                    

sn=${1:-$1}

for host in $(seq 1 255); do
                            
    ttlstr=$(ping -c1 -w1 $sn.$host | grep -o 'ttl=[0-9][0-9]*') || {
        printf "%s is Offline\n" "$sn.$host"
        continue;
    }
    ttl="${ttlstr#*=}"           
    printf "%s is Online, ttl=%d\n" "$sn.$host" "$ttl"
    if [ $ttl -eq 64 ]
            then
                echo "Operating is Linux"
            elif [ $ttl -eq 128 ]
            then
                echo "Operating is Windows"
            else
                echo "Operating is IOS"
                fi

done
  1. 所以你可以看到它可以用给定的IP地址ping每个IP。但是如果用户想输入:192.168.1.0/24 我该如何解决?

最后,感谢您的回答:D

【问题讨论】:

  • 除非您想编写自己的解析器,否则为什么不使用像 ipcalc 这样的 CLI 工具?
  • 我有一个关于 bash 脚本的作业:D Tks 为您解答:D
  • 你想用${1:-$1}实现什么? ${1:-x} 表示$1 的值,如果它已定义且不为空,否则为x。但是您的x$1,这使得表达式的意思是“如果设置了则使用$1,否则使用$1”。
  • @axiac 感谢您指出我的错误。我对 bash 很陌生,所以我仍然会犯错误:D。仍在努力提高我的 Bash 技能

标签: bash


【解决方案1】:

你可以使用这个脚本:

#!/bin/bash                                                                    

if [ -z $1 ] ; then 
    echo "Please enter ip address"
    exit 1
fi 

function print_os_type() {
    case $2  in 
       64) echo "$1 Linux" ;;
       128) echo "$1  Windows" ;;
       *) echo "$1 Unknown os type";;
    esac
}

function get_ttl() {
    ping -c1 -w1 $1 | grep ttl | awk '{print $6}' | tr -d "ttl="
}

if [ ! -z $2 ] ; then 
    IPS=$(nmap -sL -n $1/$2 | grep report | awk '{print $5}')  
    for I in ${IPS[@]}
    do
        ttl=$(get_ttl $I) 
        print_os_type $I $ttl
    done
else
    ttl=$(ping -c1 -w1 $1 | grep ttl | awk '{print $6}' | tr -d "ttl=")
    print_os_type $1 $ttl
fi

用法:

./script.sh 192.168.1.1 #For single ip 
./script.sh 172.16.10.0 24 #For subnet of ips

或者直接使用这个命令:

nmap -n -O 192.168.1.0/24 | grep 'OS details'

注意:
这是使用 ttl 检测操作系统类型的可怕想法。
像我这样的人手动更改此 ttl:

root@HOSTNAME:~# echo 110 >  /proc/sys/net/ipv4/ip_default_ttl
root@HOSTNAME:~# ping -c1 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=110 time=0.069 ms

--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.069/0.069/0.069/0.000 ms

【讨论】:

  • 好吧,就是说,如果您使用的是nmap,那么只需使用nmap 检测操作系统即可。
  • @mah454 但是如果我没有nmap,脚本将无法工作。你怎么解决这个问题?谢谢你:D
  • @Ta219 太难了!请看这个:stackoverflow.com/questions/16986879/…
猜你喜欢
  • 2010-09-28
  • 2012-05-31
  • 1970-01-01
  • 2020-09-19
  • 2012-04-29
  • 2012-03-29
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多