我想做的是使用 netstat -an | grep ESTABLISHED
从 whois
搜索中检查我系统中的所有 IP 地址,并禁止任何属于中国的 IP 地址。
所以我想知道如何实现这一目标?可能通过将字符串传递到彼此的命令中?但我该怎么做呢?
(试图在不添加 ssh 安全性的情况下禁止中国,我希望在 bash 或 python 中实现这一点)
我目前的代码:
#!/bin/bash
netstat -an | grep ESTABLISHED > log.txt;
myvar=$(awk -F"|" '{print $NF}' log.txt)
whois $myvar
我正在努力使检查该国家/地区是否为中国并禁止 ip 的过程自动化。
最佳答案
这是一个写在 bash 中的例子,
#!/bin/bash
# shellcheck disable=SC2155
# Automatically ban IP from country
# Copyright (C) 2019 Lucas Ramage <ramage.lucas@protonmail.com>
# SPDX-License-Identifier: MIT
set -euo pipefail
IFS=$'\n\t'
# netstat output:
# Proto Recv-Q Send-Q Local Address Foreign Address State
get_ip_addr() {
# Awk splits the 5th column, Foreign Address, to get the IP
echo "${1}" | awk '{ split($5, a, ":"); print a[1] }'
}
# whois output:
# OrgName: Internet Assigned Numbers Authority
# OrgId: IANA
# Address: 12025 Waterfront Drive
# Address: Suite 300
# City: Los Angeles
# StateProv: CA
# PostalCode: 90292
# Country: US <-- We want this one
# RegDate:
# Updated: 2012-08-31
# Ref: https://rdap.arin.net/registry/entity/IANA
get_country() {
# Returns nothing if Country not set
whois "${1}" | awk '/Country/ { print $NF }'
}
check_country() {
# Implements a whitelist, instead of a blacklist
local COUNTRIES="US"
# Iterate through whitelist
for country in $COUNTRIES; do
# Check entry to see if its in the whitelist
if [ "${country}" == "${1}" ]; then
echo 1 # true
fi
done
}
block_ip() {
# Remove the `echo` in order to apply command; must have proper privileges, i.e sudo
echo sudo iptables -A INPUT -s "${1}" -j "${2}"
}
main() {
# Established Connections
local ESTCON=$(netstat -an | grep ESTABLISHED)
for entry in $ESTCON; do
local ip=$(get_ip_addr "${entry}")
local country=$(get_country "${ip}")
local is_allowed=$(check_country "${country}")
local policy='DROP' # or REJECT
if [ ! "${is_allowed}" -eq "1" ]; then
block_ip "${ip}" "${policy}"
fi
done
}
main
我会亲自跑 shellcheck对其进行进一步测试。
此外,您可能想查看 fail2ban或类似的东西。
关于python - How to grab string(ip) from netstat pipe the string(ip) to whois command, grab a string(country) 从 whois 输出。并使用 iptables 禁止 ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546052/