MCPcopy
hub / github.com/sshuttle/sshuttle / rewrite_etc_hosts

Function rewrite_etc_hosts

sshuttle/firewall.py:25–67  ·  view source on GitHub ↗
(hostmap, port)

Source from the content-addressed store, hash-verified

23
24
25def rewrite_etc_hosts(hostmap, port):
26 BAKFILE = '%s.sbak' % HOSTSFILE
27 APPEND = '# sshuttle-firewall-%d AUTOCREATED' % port
28 old_content = ''
29 st = None
30 try:
31 old_content = open(HOSTSFILE).read()
32 st = os.stat(HOSTSFILE)
33 except IOError as e:
34 if e.errno == errno.ENOENT:
35 pass
36 else:
37 raise
38 if old_content.strip() and not os.path.exists(BAKFILE):
39 try:
40 os.link(HOSTSFILE, BAKFILE)
41 except OSError:
42 # file is locked - performing non-atomic copy
43 shutil.copyfile(HOSTSFILE, BAKFILE)
44 tmpname = "%s.%d.tmp" % (HOSTSFILE, port)
45 f = open(tmpname, 'w')
46 for line in old_content.rstrip().split('\n'):
47 if line.find(APPEND) >= 0:
48 continue
49 f.write('%s\n' % line)
50 for (name, ip) in sorted(hostmap.items()):
51 f.write('%-30s %s\n' % ('%s %s' % (ip, name), APPEND))
52 f.close()
53
54 if sys.platform != 'win32':
55 if st is not None:
56 os.chown(tmpname, st.st_uid, st.st_gid)
57 os.chmod(tmpname, st.st_mode)
58 else:
59 os.chown(tmpname, 0, 0)
60 os.chmod(tmpname, 0o644)
61 try:
62 os.rename(tmpname, HOSTSFILE)
63 except OSError:
64 # file is locked - performing non-atomic copy
65 log('Warning: Using a non-atomic way to overwrite %s that can corrupt the file if '
66 'multiple processes write to it simultaneously.' % HOSTSFILE)
67 shutil.move(tmpname, HOSTSFILE)
68
69
70def restore_etc_hosts(hostmap, port):

Callers 2

restore_etc_hostsFunction · 0.85
mainFunction · 0.85

Calls 3

logFunction · 0.90
writeMethod · 0.80
closeMethod · 0.80

Tested by

no test coverage detected