Commit 1557dd8c authored by Josué Ortega's avatar Josué Ortega

CleanUP repo

parent 3e6b93cd
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>
```
hostsed for Debian
Please edit this to provide information specific to
this hostsed Debian package.
(Automatically generated by debmake Version 4.3.1)
-- Josue Ortega <josue@debian.org> Thu, 25 Apr 2019 17:16:24 -0600
hostsed (0.2.0-1) UNRELEASED; urgency=low
* Initial release. Closes: #916259
-- Josue Ortega <josue@debian.org> Thu, 25 Apr 2019 17:16:24 -0600
Source: hostsed
Section: unknown
Priority: optional
Maintainer: Josue Ortega <josue@debian.org>
Build-Depends: debhelper-compat (= 12),
dh-python,
python3-setuptools,
python3-all
Standards-Version: 4.1.4
Homepage: https://github.com/socrateslee/hostsed
X-Python3-Version: >= 3.6
Package: hostsed
Architecture: all
Multi-Arch: foreign
Depends: ${misc:Depends}, ${python3:Depends}
Description: A hosts file editing tool for command line shell
Simple Python tool for editing hosts file (/etc/hosts), you can add or delete
a DNS entry via command line shell.
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: hostsed
Source:https://github.com/socrateslee/hostsed
Files: *
Copyright: 2016 Li
License: MIT
Files: debian/*
Copyright: 2019 Josue Ortega <josue@debian.org>
License: MIT
License: MIT
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.
# You must remove unused comment lines for the released package.
#!/usr/bin/make -f
export DH_VERBOSE = 1
%:
dh $@ --with python3 --buildsystem=pybuild
# You must remove unused comment lines for the released package.
version=3
'''
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