最好的计时方法?

时间:2014-11-07 15:19:21

标签: bash

我正在尝试编写一个SSH版本的ICMP Ping,如下所示:

TARGET_IP=""  
count=0  
time_start=0  
time_end=0  
time_taken=0  
TARGET_IP=$1  
while [ $count -lt 5 ]
do  
    ((count=count+1))  
    time_start=$(date +%s%N)  
    temp_target_key=$(ssh-keyscan $TARGET_IP) > /dev/null 2>&1  
    time_end=$(date +%s%N)  
    time_taken=$((( $time_end - $time_start ) / 1000000))  
    echo "Time taken=$time_taken ms."  
    target_key=$(echo $temp_target_key | awk '{print $3}') > /dev/null 2>&1  
    echo $temp_target_key > target_key.txt  
    ssh-keygen -l -f target_key.txt > /dev/null 2>&1  
    test=$?  
    if [ $test -ne 0 ]  
    then  
        echo "Device returned invalid RSA Public Key"  
        echo -e "\n"  
        echo -e "\n"  
    else  
        echo "Device responding correctly."  
        echo -e "\n"  
    fi  
done  
exit  

ICMP Ping报告的ping时间为5ms,而此脚本报告的同一设备为300ms。我意识到我正在计算脚本和设备编程/固件响应时间,但我这样做是最好的方法吗? 谢谢

1 个答案:

答案 0 :(得分:0)

我看不到更好的方法来模拟ssh ping。不过我试图用更纯粹的bash风格来改进你的脚本:

#! /bin/bash

if (($# != 1)); then
    echo "Usage: ${0##*/} host" >&2
    exit 1
fi
TARGET_IP="$1"

target_key_file="target_key.txt"

for ((count=0; count < 5; count++))
do
    time_start=$(date +%s%N)  
    temp_target_key=$(ssh-keyscan "$TARGET_IP") > /dev/null 2>&1  
    time_end=$(date +%s%N)  
    time_taken=$(((time_end - time_start ) / 1000000))  
    echo "Time taken=$time_taken ms."

    read _ _ target_key _ <<< "$temp_target_key"
    echo "$target_key"

    echo "$temp_target_key" >| "$target_key_file" 
    if ! ssh-keygen -l -f "$target_key_file" > /dev/null 2>&1  
    then echo -e "Device returned invalid RSA Public Key.\n\n"  
    else echo -e "Device responding correctly.\n\n"
    fi  
done