Commit 0771de40 authored by Josué Ortega's avatar Josué Ortega

Import Upstream version 0.3.0

parent 1557dd8c
The MIT License (MIT)
Copyright (c) 2016 Li
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# hostsed -- A tiny hosts file command line edit tool
hostsed is a simple python tool for editing hosts file(default /etc/hosts), you can add or delete a DNS entry via command line shell(e.x. bash). Editing hosts file with hostsed would be a more idemponent command line experience, i.e., add/del the same record won't result duplicated or missing entries in the hosts file. hostsed will check the validity ip address for both IPV4 and IPV6.
## Install
You may install hostsed via pip. Python3 is preferred:
```
sudo pip3 install hostsed
```
Or on system default pip command:
```
sudo pip install hostsed
```
## Usage
### Display the hosts file content
sudo hostsed
# specify a location other than /etc/hosts
hostsed --file hosts.example
### Add an entry
sudo hostsed add <ip address> <hostname1> <hostname2> ...
Example:
sudo hostsed add 192.168.1.1 gateway
sudo hostsed add 172.17.0.5 mongo-store-1 mysql-02
hostsed --file hosts.exmaple add 127.0.0.1 valarmorghulis.io
### Delete an entry
rm/delete/remove are all alias for del:
sudo hostsed del <ip address> <hostname>
Example:
sudo hostsed remove 192.168.1.1 gateway
hostsed --file rm ::1 localhost
### Get the ip address of a docker container
sudo hostsed docker <docker-container-name>
## Acknowledgement
Thanks for @noahfx provide some awesome improve for hostsed.
\ No newline at end of file
'''
Utilities for adding or deleting entries on hosts file
as /etc/hosts.
'''
import os
import sys
import json
import subprocess
import socket
import argparse
def is_valid_ip_address(ip):
'''
Check whether an ip address is valid, both for ipv4
and ipv6.
'''
try:
socket.inet_pton(socket.AF_INET, ip)
return True
except socket.error:
pass
try:
socket.inet_pton(socket.AF_INET6, ip)
return True
except socket.error:
pass
return False
def parse_line(line):
pos = line.find("#")
new_line = line[:pos].strip() if pos != -1 else line.strip()
comment = line[pos:] if pos != -1 else ''
if new_line:
parts = list(map(lambda x: x.strip(), new_line.split()))
return (line, parts, comment)
else:
return (line, None, comment)
class HostEditor(object):
def __init__(self, filename='/etc/hosts'):
self.filename = filename
self._parse()
def chk_user_permissions(self):
'''
Check if current user has sufficient permissions to
edit hosts file.
Raise an exception if user is invalid
'''
if not os.access(self.filename, os.W_OK):
msg = 'User does not have sufficient permissions, are you super user ?'
raise Exception(msg)
return
def add(self, ip, *hostnames):
'''
Add an entry to hosts file.
'''
self.chk_user_permissions()
if not is_valid_ip_address(ip):
raise Exception("IP %s is not valid." % ip)
if not self.entries:
return
ret = []
added = False
if not self.entries:
return
for (line, parts, comment) in self.entries:
if parts and parts[0] == ip and not added:
for hostname in hostnames:
if hostname not in parts[1:]:
parts.append(hostname)
line = ' '.join(['\t'.join(parts), comment])
added = True
ret.append((line, parts, comment))
if not added:
parts = [ip] + list(hostnames)
line = '\t'.join(parts)
ret.append((line, parts, comment))
self.entries = ret
self.write()
self.output()
def delete(self, ip, hostname):
'''
Delete an entry from hosts file.
'''
self.chk_user_permissions()
if not is_valid_ip_address(ip):
raise Exception("IP %s is not valid." % ip)
ret = []
for (line, parts, comment) in self.entries:
if parts and parts[0] == ip:
parts = list(filter(lambda x: x != hostname, parts))
if not parts[1:]:
continue
line = ' '.join(['\t'.join(parts), comment])
ret.append((line, parts, comment))
self.entries = ret
self.write()
self.output()
def _parse(self):
'''
Parse the files into entries.
'''
self.entries = []
for line in open(self.filename).readlines():
self.entries.append(parse_line(line))
def output(self, fd=None):
if fd is None:
fd = sys.stdout
fd.write('\n'.join(map(lambda x: x[0].strip(), self.entries)))
fd.write('\n')
def write(self):
fd = open(self.filename, 'w')
self.output(fd=fd)
fd.close()
def output_docker_ip(self, container):
proc = subprocess.Popen("docker inspect %s" % container,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode == 0:
ret = json.loads(stdout.decode('utf-8'))
ip = ret[0]['NetworkSettings']['IPAddress']
sys.stdout.write(ip)
def parse_cmdline():
'''
Parse cmd line arguments and returns a dictionary
with its parsed values
'''
parser = argparse.ArgumentParser(
prog='hostsed',
description='A hosts file editing tool for command line shell')
subparsers = parser.add_subparsers(dest='name')
add_parser = subparsers.add_parser(
name='add',
help='Add entry IPADDRESS HOSTNAME1 [HOSTNAME2 ...]'
)
add_parser.add_argument('add', type=str, nargs='+')
# subparser does not support aliasing
del_opts = ['del', 'rm', 'delete', 'remove']
for do in del_opts:
del_parser = subparsers.add_parser(
name=do,
help='Delete an IPADDRESS HOSTNAME entry'
)
del_parser.add_argument(do, nargs=2)
docker_parser = subparsers.add_parser(
name='docker',
help='Show docker cointainer IP address of the given name'
)
docker_parser.add_argument(
'docker',
help='Name of the Container to get IP address from',
metavar='CONTAINER',
type=str,
nargs=1
)
parser.add_argument("-f", "--file",
default="/etc/hosts",
help="The location of hosts file, default /etc/hosts",
type=str)
dparser = vars(parser.parse_args())
# normalize keys for del and its aliases:
name = dparser.get('name')
if name in del_opts:
dparser['name'] = 'del'
dparser['del'] = dparser.get(name)
return dparser
def main():
args = parse_cmdline()
f_name = args.get('name')
he = HostEditor(filename=args.get('file'))
funcs = {
'add': he.add,
'del': he.delete,
'docker': he.output_docker_ip
}
try:
if not args.get(f_name):
he.output()
else:
funcs.get(f_name)(*args.get(f_name))
except Exception as e:
fd = sys.stdout
fd.write('ERROR: {} \n'.format(e))
if __name__ == '__main__':
main()
#!/usr/bin/env python
import hosts.editor
if __name__ == '__main__':
hosts.editor.main()
[metadata]
description-file = README.md
\ No newline at end of file
#!/usr/bin/env python
long_description = ""
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except:
pass
sdict = {
'name': 'hostsed',
'version': "0.3.0",
'packages': ['hosts'],
'zip_safe': False,
'author': 'lichun',
'url': 'https://github.com/socrateslee/hostsed',
'scripts': ['hostsed'],
'long_description': long_description,
'classifiers': [
'Environment :: Console',
'Intended Audience :: Developers',
'Programming Language :: Python']
}
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(**sdict)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment