Who is attacking your server?
The lastb command in Linux displays a list of failed login attempts by users. It retrieves the information from the /var/log/btmp file, which records unsuccessful login attempts. We can use lastb to generate a list of crackers’ IP addresses, and then generate a configuration file for iptables to block them.
def getBadIPAddresses(stdout):
# dealing with the output of "lastb"
cracker = {}
for line in stdout.split('\n'):
if not line: continue
cols = line.split()
if not len(cols) > 2: continue
username = cols[0]
ip = cols[2]
try:
cracker[ip].add(username)
except KeyError:
cracker[ip] = set([username])
# do statistics
badIPAddresses = []
keys = list(cracker.keys())
keys.sort()
for ip in keys:
## add the ip into list if it tried over 5 names
if len(cracker[ip]) > 5:
badIPAddresses.append(ip)
return badIPAddresses
password = '123456'
$.connect('user@host',password):
with $.sudo(password) as sudo:
sudo('lastb -1000')
badIPAddresses = getBadIPAddresses(sudo.stdout)
## rules for iptables
rules = []
for ip in badIPAddresses:
rules.append(f'-A INPUT -s {ip}/32 -j DROP')
print('\n'.join(rules))
Last Updated: 2026-07-25 16:59:40
Table of contents
- SSHScript Documentation
- Accounts (legacy URL)
- Checking the syncing status of two MySQL servers
- Documentation Repository
- Getting Started with SSHScript
- Page not found
- Q: What can it do that Netmiko doesn’t do? (origin)
- SSHScript 5.0.0
- SSHScript Documents
- SSHScript v2.0 CLI(Draft)
- SSHScript v2.0 Commands Execution and Console
- SSHScript v2.0 Console of sudo and su
- SSHScript v2.0 Getting Started
- SSHScript v2.0 Interactive Commands and Foreground Commands
- SSHScript v2.0 Make Connections
- SSHScript v2.0 Recipes
- SSHScript v2.0 Reference Guide
- SSHScript v2.0 Stdout, Stderr and Exitcode
- SSHScript v2.0 Threading Support
- SSHScript v2.0 Upload and Download Files
- SSHScript v2.0.2 Release Notes
- SSHScript v3.0 Interactive and Foreground Commands
- SSHScript v3.0 Reference Guide
- SSHScript v3.0.0 Release Notes
- SSHScript vs. Ansible
- 用 Python 作系統自動化