Created
July 29, 2011 06:47
-
-
Save tokibito/1113337 to your computer and use it in GitHub Desktop.
network setup script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding:utf8 | |
import os | |
import sys | |
FILE_HOSTNAME = '/etc/hostname' | |
FILE_HOSTS = '/etc/hosts' | |
FILE_NETWORK = '/etc/network/interfaces' | |
CMD_RESTART_NETWORK = 'ifdown eth0&&ifup eth0' | |
CMD_UPDATE_HOSTNAME = 'hostname %s' | |
def readfile(filename): | |
f = open(filename, 'r') | |
data = f.read() | |
f.close() | |
return data | |
def writefile(filename, data): | |
f = open(filename, 'w') | |
f.write(data) | |
f.close() | |
def readvalue(data, key): | |
for line in data.splitlines(): | |
if line.startswith(key): | |
val = line[len(key):] | |
return val.strip() | |
def writevalue(data, key, value): | |
lines = data.splitlines() | |
for i in range(len(lines)): | |
if lines[i].startswith(key): | |
lines[i] = '%s\t%s' % (key, value) | |
return '\n'.join(lines) | |
def main(): | |
hostname_data = readfile(FILE_HOSTNAME) | |
hosts_data = readfile(FILE_HOSTS) | |
network_data = readfile(FILE_NETWORK) | |
hostname = hostname_data.strip() | |
ip_address = readvalue(network_data, 'address') | |
sys.stdout.write('Input new hostname[%s]:' % hostname) | |
hostname_new = sys.stdin.readline().strip() or hostname | |
sys.stdout.write('Input new IP address[%s]:' % ip_address) | |
ip_address_new = sys.stdin.readline().strip() or ip_address | |
# confirm | |
sys.stdout.write('New hostname: %s\nNew IP address: %s\nOk? [Y/n]:' % (hostname_new, ip_address_new)) | |
confirm = sys.stdin.readline().strip() | |
if confirm != 'Y': | |
return | |
sys.stdout.write('updating hostname...\n') | |
hostname_data_new = '%s' % hostname_new | |
writefile(FILE_HOSTNAME, hostname_data_new) | |
sys.stdout.write('updating hosts...\n') | |
hosts_data_new = writevalue(hosts_data, '127.0.1.1', hostname_new) | |
writefile(FILE_HOSTS, hosts_data_new) | |
os.system(CMD_UPDATE_HOSTNAME % hostname_new) | |
sys.stdout.write('updating network interface...\n') | |
network_data_new = writevalue(network_data, 'address', ip_address_new) | |
writefile(FILE_NETWORK, network_data_new) | |
sys.stdout.write('restart networking...\n') | |
os.system(CMD_RESTART_NETWORK) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment