Use hosts. deny to reject ssh test Logon
This is mainly to take into account the fact that, after opening ssh on the public network, some people keep trying to connect and automatically refuse.
#! /Bin/bash
# Zhao Yun
# Automatically monitor ssh test logon and add it to/etc/hosts. deny to reject
# Set the number of attempts. If you attempt to perform the operation three times, the connection is denied.
Number = 3
# Set the running interval, in seconds
Sleep = 1
# Set the time (in seconds) for locking the test IP Address
Locktime = 15
Lockfile =/tmp/lock-ipadd
Touch $ lockfile
While true
Do
Www.2cto.com
# Execute the lock check
For badip in 'lastb | awk' {print $3} '| grep-v ^ $ | grep-v [A-Z] | sort | uniq-c | awk-vn = "$ number "'$1> n {print $2 }''
Do
Time = 'date + % s'
Bip = 'echo $ badip | head-n $ I | tail-n1'
Echo $ bip | grep [0-9] &>/dev/null
If [$? -Eq 0]; then
Grep $ bip $ lockfile &>/dev/null
If [$? -Eq 1]; then
Echo $ bip. $ time >>$ lockfile
Fi
Grep $ bip/etc/hosts. deny &>/dev/null
[! $? -Eq 0] & (echo "SSHD: $ bip">/etc/hosts. deny; logger "lock ip address $ bip ")
Cat/var/log/btmp>/var/log/btmp. bak
>/Var/log/btmp
Fi
Done
# Unlock
Nowtime = 'date + % s'
Rows = 'wc-l $ lockfile | awk '{print $1 }''
For (I = 1; I <= rows; I ++ ))
Do
Line = 'cat-n $ lockfile | head-n $ I | tail-n1 | awk-F. '{print $5 "" $1}' | awk-vt = "$ nowtime" '{print t-$1 "" $2}' | awk-vt = "$ locktime "'$1> t {print $2 }''
Echo $ line | grep [0-9] &>/dev/null
If [$? -Eq 0]; then
Unlockip = 'cat-n $ lockfile | column-t | grep ^ $ line | awk '{print $2}' | awk-F. '{print $1 ". "$2 ". "$3 ". "$4 }''
Sed-I "/SSHD: $ unlockip/d"/etc/hosts. deny
Logger "unlock ip address $ unlockip"
Sed-I "/$ unlockip/d" $ lockfile
Fi
Done
Sleep $ sleep
Done
View logs
Tail/var/log/messages
Apr 6 19:49:58 localhost sess: lock ip address 192.168.0.31
Apr 6 19:50:47 localhost sess: unlock ip address 192.168.0.31
Apr 6 19:51:02 localhost sess: unlock ip address 192.168.0.56