/
unblock.py
55 lines (40 loc) · 1.48 KB
/
unblock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import argparse
import os
import subprocess
def CMD(cmd) :
p = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=False)
return (p.stdin, p.stdout, p.stderr)
denyhost_files = ['/etc/hosts.deny', 'hosts', 'hosts-restricted', 'hosts-root', 'hosts-valid', 'users-hosts', '/var/log/auth.log']
def remove_line(text, path):
temp_file_path = path + ".temp"
read_file = file(path, 'r')
write_file = file(temp_file_path, 'w+')
for line in read_file.readlines():
if text not in line:
write_file.write(line)
read_file.close()
write_file.close()
os.remove(path)
os.rename(temp_file_path, path)
def check_sudo():
flag = False
if os.getenv('USER') == 'root':
flag = True
return flag
def unblock(ip_address):
os.chdir('/var/lib/denyhosts/')
for deny_file in denyhost_files:
remove_line(ip_address, deny_file)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Remove an IP address from DenyHost, allowing access to the machine from that IP again")
parser.add_argument("ip_address", help="The IP address to be removed from denyhost files", type=str)
args = parser.parse_args()
if not check_sudo() and args.host_addr is None:
print "If you want to run this locally, please run with `sudo`"
CMD("sudo service denyhosts stop")
unblock(args.ip_address)
CMD("sudo service denyhosts start")