Skip to content

Instantly share code, notes, and snippets.

@kacchan822
Last active October 25, 2017 02:53
Show Gist options
  • Save kacchan822/f9240646cfd78a5290a2ec95d844b1a0 to your computer and use it in GitHub Desktop.
Save kacchan822/f9240646cfd78a5290a2ec95d844b1a0 to your computer and use it in GitHub Desktop.
check_geoip.py
#!/usr/bin/env python3
#
# install required packeges:
# sudo apt-get install python3-geoip geoip-database libgeoip1
#
# download script:
# sudo curl -sS -o /usr/local/bin/check_geoip.py https://gist.githubusercontent.com/kacchan822/f9240646cfd78a5290a2ec95d844b1a0/raw/check_geoip.py
# sudo chmod +x /usr/local/bin/check_geoip.py
#
# setting up hosts.allow and hosts.deny:
# sudo sh -c 'echo "sshd: ALL: aclexec /usr/local/bin/check_geoip.py %a" >> /etc/hosts.allow'
# sudo sh -c 'echo "sshd: ALL" >> /etc/hosts.deny'
#
import ipaddress
import sys
import GeoIP
# CHANGE if allow from other countory.
ALLOWED_COUNTORY = ['JP',]
# Check Value
try:
ip = ipaddress.ip_address(sys.argv[1])
except ValueError:
sys.exit(1)
# Local IP is permitted
if ip.is_private:
sys.exit(0)
# Check IP address version
if ip.version == 4:
gi = GeoIP.new(GeoIP.GEOIP_STANDARD)
cc = gi.country_code_by_addr(str(ip))
else:
gi = GeoIP.open('/usr/share/GeoIP/GeoIPv6.dat', GeoIP.GEOIP_STANDARD)
cc = gi.country_code_by_addr_v6(str(ip))
# Chaeck Countory Code
if cc in ALLOWED_COUNTORY:
sys.exit(0)
else:
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment