summaryrefslogtreecommitdiff
path: root/ssh-check
blob: df5274bbf1f7206116cb9117e716676ef051e199 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash

CFG_FILE=$HOME/.config/ssh-check.list
TIMEOUT=5 # seconds


read_all='read -N2147483647'

$read_all SSH_OPTIONS <<END
-o ConnectTimeout=$TIMEOUT
-o ControlPath=none
-o PasswordAuthentication=no
-o StrictHostKeyChecking=yes
END

quietly()
{
    "$@" </dev/null >/dev/null 2>&1
}

match()
{
    local search_text="$1" search_pattern
    shift
    for search_pattern in "$@"
    do
        case "$search_text" in
            $search_pattern) return ;;
        esac
    done
    false
}

main()
{
    local h hosts
    $read_all -r hosts < "$CFG_FILE"
    host_field_width=1
    for h in $hosts
    do
        if [ ${#h} -gt $host_field_width ]
        then
            host_field_width=${#h}
        fi
    done
    while true; do
        {
            for h in $hosts
            do
                [ $# = 0 ] || match "$h" "$@" || continue

                ( if uptime=$(ssh $SSH_OPTIONS -n "$h" -- uptime 2>/dev/null)
                then
                    printf "%-15s %-${host_field_width}s  %s\n" "Succeeded:" "$h" "${uptime# }"
                else
                    printf "%-15s %-${host_field_width}s\n"    "Failed:"    "$h"
                fi ) &
            done
            wait
        } | column -t -s'$'
        tty -s && break
        sleep 5
    done
}

edit_config()
{
    set -e
    f=$(mktemp)
    if [ -e "$CFG_FILE" ]
    then
        cp "$CFG_FILE" "$f"
    fi
    touch -r "$f" "$f".timestamp
    $EDITOR "$f"
    [ -e "$f" -a "$f" -nt "$f".timestamp ]
    mv "$f" "$CFG_FILE"
    set +e
    rm "$f".timestamp
}

unset run_anyway do_edit
while [ $# -gt 0 ]
do
    case "$1" in
        --edit) do_edit=y;;
        --run) run_anyway=y;;
        --) shift; break;;
        -*) exit 1 ;;
        *) break;;
    esac
    shift
done

if [ "$do_edit" ]
then
    edit_config
    r=$?
    if ! [ "${run_anyway}" ]
    then
        exit $r
    fi
elif [ ! -e "$CFG_FILE" -a -t 0 ]
then
    edit_config
fi

main "$@"