Skip to content

Instantly share code, notes, and snippets.

@VeryCB
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VeryCB/f5e32c534b741233a093 to your computer and use it in GitHub Desktop.
Save VeryCB/f5e32c534b741233a093 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
from optparse import OptionParser
config_path = '/etc/switch-host/'
default_backup_file = 'default-hosts'
default_hosts_path = '/etc/hosts'
def check_config_path():
if not os.path.exists(config_path):
os.mkdir(config_path)
def check_config_file(filename):
file_path = config_path + filename
if not os.path.exists(file_path):
raise ValueError('Config file %s in not found in %s' %
(filename, config_path))
def switch_hosts(filename):
check_config_file(filename)
file_path = config_path + filename
shutil.copyfile(file_path, default_hosts_path)
print 'Your hosts has beed switched to %s successfully!' % filename
def backup_hosts(target_file):
file_path = config_path + target_file
shutil.copyfile(default_hosts_path, file_path)
print 'Your hosts has beed backuped to %s successfully!' % file_path
def list_hosts_config():
print 'Available hosts configs:'
for config in os.listdir(config_path):
print config
def main(list_hosts, config_file, backup_file):
check_config_path()
if list_hosts:
list_hosts_config()
return
if config_file:
switch_hosts(config_file)
return
if backup_file:
backup_hosts(backup_file)
return
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-c', '--config', dest='config_file',
help='Specify your hosts config name')
parser.add_option('-b', '--backup', dest='backup_file',
default=default_backup_file,
help='Backup your current hosts config to')
parser.add_option('-l', '--list', dest='list_hosts',
action='store_true',
help='Specify your hosts config name')
options, args = parser.parse_args()
config_file = None
if len(args) > 0:
config_file = args[0]
if options.config_file:
config_file = options.config_file
backup_file = options.backup_file
list_hosts = options.list_hosts
try:
main(list_hosts, config_file, backup_file)
except ValueError as e:
print e.message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment