Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for reading hosts/subnets from a file #130

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions vpn_slice/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ def net_or_host_param(s):
except ValueError:
return s

def file_path_param(path):
if isinstance(path, str) and os.path.exists(path):
return path
else:
raise ValueError("path not valid")

def names_for(host, domains, short=True, long=True):
if '.' in host: first, rest = host.split('.', 1)
Expand All @@ -109,6 +114,22 @@ def names_for(host, domains, short=True, long=True):
elif rest in domains: names.append(first)
return names

def read_routes_file(filename):
hosts = []
with open(filename) as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
Comment on lines +120 to +121

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to read the entire file in memory beforehand, you can just iterate over the lines like this:

Suggested change
lines = [x.strip() for x in f.readlines()]
for line in lines:
for line in f:
line = line.strip()

# ignore empty lines
if not len(line.strip()):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant strip:

Suggested change
if not len(line.strip()):
if not line:

continue
# ignore comment lines
if line.strip().startswith('#'):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant strip:

Suggested change
if line.strip().startswith('#'):
if line.startswith('#'):

continue
# ignore comments at the end of the line
host = line.split('#', 1)[0].strip()
hosts.append(host)
return hosts

########################################

def do_pre_init(env, args):
Expand Down Expand Up @@ -444,6 +465,7 @@ def parse_args_and_env(args=None, environ=os.environ):
p = argparse.ArgumentParser()
p.add_argument('routes', nargs='*', type=net_or_host_param, help='List of VPN-internal hostnames, included subnets (e.g. 192.168.0.0/24), excluded subnets (e.g. %%8.0.0.0/8), or aliases (e.g. host1=192.168.1.2) to add to routing and /etc/hosts.')
g = p.add_argument_group('Subprocess options')
p.add_argument('-f', '--routes-file', default=None, type=file_path_param, help='Path to List of VPN-internal hostnames, subnets (e.g. 192.168.0.0/24), or aliases (e.g. host1=192.168.1.2) to add to routing and /etc/hosts.')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FileType might be better for handling file as arguments, like this one:

Suggested change
p.add_argument('-f', '--routes-file', default=None, type=file_path_param, help='Path to List of VPN-internal hostnames, subnets (e.g. 192.168.0.0/24), or aliases (e.g. host1=192.168.1.2) to add to routing and /etc/hosts.')
p.add_argument('-f', '--routes-file', default=None, type=argparse.FileType('r'), help='Path to List of VPN-internal hostnames, subnets (e.g. 192.168.0.0/24), or aliases (e.g. host1=192.168.1.2) to add to routing and /etc/hosts.')

g.add_argument('-k', '--kill', default=[], action='append', help='File containing PID to kill before disconnect (may be specified multiple times)')
g.add_argument('-K', '--prevent-idle-timeout', action='store_true', help='Prevent idle timeout by doing random DNS lookups (interval set by $IDLE_TIMEOUT, defaulting to 10 minutes)')
g = p.add_argument_group('Informational options')
Expand Down Expand Up @@ -487,6 +509,14 @@ def parse_args_and_env(args=None, environ=os.environ):
args.exc_subnets = []
args.hosts = []
args.aliases = {}

# read routes from a file
if args.routes_file:
args.routes.extend([
net_or_host_param(x)
for x in read_routes_file(args.routes_file)
])

for x in args.routes:
if isinstance(x, str):
args.hosts.append(x)
Expand Down