Skip to content

Instantly share code, notes, and snippets.

@Veticus
Created April 13, 2020 01:43
Show Gist options
  • Save Veticus/dcabf30873bce1784e5919504d954dc2 to your computer and use it in GitHub Desktop.
Save Veticus/dcabf30873bce1784e5919504d954dc2 to your computer and use it in GitHub Desktop.
# This is to get a list of IP's, banned by fail2ban on a remote machine.
#
# It connects via SSH, so sqlite3 won't need to be exposed.
#
# Authentication is handled by the local machine, so in this case a keyfile is used.
#
# In addition the user has been granted NOPASSWD in the /etc/sudoers file. Below is an example
# username ALL=(ALL:ALL) NOPASSWD:ALL
# This allows the user to use sudo, without having to submit a password.
#
# However, this isn't blindly advisable in all environments,
# so i'd recommend taking this into account, when performing a security evaluation.
import subprocess
import time
def getlist(hoststring, dumplist):
process = subprocess.Popen(['ssh', hoststring, 'sudo', 'sqlite3', '-csv', '/var/lib/fail2ban/fail2ban.sqlite3', '"SELECT ip FROM bans;"'],
stdout=subprocess.PIPE,
universal_newlines=True)
while True:
output = process.stdout.readline()
dumplist.append(output.strip())
# print(output.strip())
return_code = process.poll()
if return_code is not None:
# print('RETURN CODE', return_code)
for output in process.stdout.readlines():
# print(output.strip())
dumplist.append(output.strip())
break
return return_code
def getlistfromhosts():
hosts = ['USERNAME@HOSTNAME1', 'USERNAME@HOSTNAME2']
dumplist = []
for h in hosts:
getlist_returncode = getlist(h, dumplist)
if getlist_returncode != 0:
time.sleep(2)
getlistfromhosts()
nonduplist = list(dict.fromkeys(dumplist))
print(nonduplist)
print(len(nonduplist))
if __name__ == "__main__":
getlistfromhosts()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment