Commit db250b4c authored by Josué Ortega's avatar Josué Ortega

Import Upstream version 0.2.0

parents
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
venv/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#Ipython Notebook
.ipynb_checkpoints
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(/etc/hosts), you can add or delete a DNS entry via command line shell(e.x. bash).
Install:
```
sudo pip install hostsed
```
Usage:
```
# 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
# Delete an entry
sudo hostsed del <ip address> <hostname>
Example:
hosted remove 192.168.1.1 gateway
# Get the ip address of a docker container
sudo hostsed docker <docker-container-name>
```
'''
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_INET, 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 add(self, ip, *hostnames):
'''
Add an entry to hosts file.
'''
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
def delete(self, ip, hostname):
'''
Delete an entry from hosts file.
'''
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
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)))
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 main():
he = HostEditor()
if len(sys.argv) >= 4 and sys.argv[1] == 'add':
he.add(sys.argv[2], *sys.argv[3:])
he.write()
he.output()
elif len(sys.argv) == 4 and sys.argv[1] in ('rm', 'remove',
'del', 'delete'):
he.delete(sys.argv[2], sys.argv[3])
he.write()
he.output()
elif len(sys.argv) == 3 and sys.argv[1] == 'docker':
he.output_docker_ip(sys.argv[2])
else:
he.output()
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.2.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