]> git.datanom.net - netconf.git/blob - netconf
initial release
[netconf.git] / netconf
1 #!/usr/bin/env python
2
3 import sys, subprocess
4
5 def runcmd(cmd):
6 process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
7 output, error = process.communicate();
8
9 return (output.rstrip(), error.rstrip())
10
11 class ParserError(Exception):
12 pass
13
14 class Parser:
15 """ Parse nic information """
16
17 def __init__(self):
18 self.__dladm1 = "dladm show-phys -p -o link,media | sed 's/:/ /g'"
19 self.__dladm2 = "dladm show-phys -p -m -o link,address,inuse | sed 's/:/ /g' | sed 's/\\\[[:space:]]/:/g' | sed 's/\\\//g'"
20
21 def __parse_nics(self, text):
22 nics = {}
23 for line in text.splitlines():
24 parts = line.split()
25 #if parts[1] in ('Ethernet', 'Infiniband'):
26 if parts[1] in ('Ethernet'):
27 nics[parts[0]] = [parts[0], parts[1]]
28
29 return nics
30
31 def __parse_macs(self, obj, text):
32 list = []
33 if obj:
34 for line in text.splitlines():
35 parts = line.split()
36 try:
37 if parts[2] == 'yes':
38 del obj[parts[0]]
39 else:
40 obj[parts[0]].append(parts[1])
41 except KeyError:
42 pass
43 for k, v in obj.items():
44 list.append(v)
45
46 return list
47
48 def parse(self):
49 (nics, error) = runcmd(self.__dladm1)
50 if error:
51 raise ParserError(error)
52
53 (macs, error) = runcmd(self.__dladm2)
54 if error:
55 raise ParserError(error)
56
57 return self.__parse_macs(self.__parse_nics(nics), macs)
58
59 def get_terminal_width():
60 try:
61 if sys.version_info >= (2,7):
62 width = int(subprocess.check_output(['tput', 'cols']))
63 else:
64 (out, err) = runcmd('tput cols')
65 if err:
66 raise OSError(err);
67 width = int(out)
68 except OSError as e:
69 print("Invalid Command 'tput cols': exit status ({1})".format(e.errno))
70 except subprocess.CalledProcessError as e:
71 print("Command 'tput cols' returned non-zero exit status: ({1})".format(e.returncode))
72 else:
73 return width
74
75 def make_menu(interfaces):
76 res = None
77 while not res:
78 sys.stderr.write("\x1b[2J\x1b[H")
79 cols = get_terminal_width()
80 intro = 'The following unconfigured interfaces was discovered'
81 fill = (cols / 2) - (len(intro) / 2)
82 print '{0:^{cols}}'.format('Simple network interface configuration tool', cols=cols)
83 print
84 print '{0:<{fill}}{1}'.format('', intro, fill=fill)
85 print '{0:<{fill}}{1:>2} {2:^15} {3:^10} {4:^17}'.format('','#','Interface','Media','MAC',fill=fill)
86 print '{0:<{fill}}{1:-^2} {2:-^15} {3:-^10} {4:-^17}'.format('','','','','',fill=fill)
87
88 n = 0
89 for i in interfaces:
90 print '{0:<{fill}}{1:>2} {2:<15} {3:<10} {4:>17}'.format('',n,i[0],i[1],i[2],fill=fill)
91 n += 1
92 print
93 print '{0:<{fill}}{1:<}'.format('','select interface number to configure:',fill=fill),
94 nic = int(raw_input())
95 if nic >= n or nic < 0:
96 print '{0:<{fill}}{1:<} {2:<}'.format('','Error: Interface: 0 <= # <',n,fill=fill),
97 raw_input(' << Hit any key >>')
98 else:
99 res = interfaces[nic]
100
101 return res
102
103 def get_config():
104 ip = mask = gw = None
105 nettype = raw_input('dhcp or static [dhcp]: ').lower()
106 if nettype == 'static':
107 while not ip:
108 ip = raw_input('Enter IP: ')
109 mask = raw_input('Enter netmask [24]: ')
110 if not mask:
111 mask = 24
112 gw = raw_input('Enter default route [0=no]: ')
113 if not gw:
114 gw = 0
115
116 return (ip,mask,gw)
117
118 def main():
119 p = Parser()
120 try:
121 interfaces = p.parse()
122 if interfaces:
123 nic = make_menu(interfaces)
124 if nic:
125 (ip,mask,gw) = get_config()
126 cmd = 'ipadm delete-if %s' % nic[0]
127 runcmd(cmd)
128 cmd = 'ipadm create-if %s' % nic[0]
129 (out, err) = runcmd(cmd)
130 if err:
131 raise RuntimeError(err)
132 if not ip:
133 # use DHCP
134 cmd = 'ipadm create-addr -T dhcp %s/v4' % nic[0]
135 (out, err) = runcmd(cmd)
136 if err:
137 raise RuntimeError(err)
138 else:
139 # use STATIC
140 cmd = 'ipadm create-addr -T static -a %s/%s %s/v4' % (ip, mask, nic[0])
141 (out, err) = runcmd(cmd)
142 if err:
143 raise RuntimeError(err)
144 if gw:
145 cmd = 'route -p add default %s' % gw
146 (out, err) = runcmd(cmd)
147 if err:
148 raise RuntimeError(err)
149 cmd = 'netstat -rn -finet'
150 (out, err) = runcmd(cmd)
151 if err:
152 raise RuntimeError(err)
153 print 'New route table'
154 print out
155 dns = raw_input('Configure DNS [n]? ').lower()
156 if not dns or dns == 'n':
157 pass
158 else:
159 dns = None
160 print
161 while not dns:
162 dns = raw_input('Enter nameserver: ')
163 cmd = "echo 'nameserver %s' >> /etc/resolv.conf" % dns
164 cmd += '&& cp /etc/nsswitch.conf{,.bak}'
165 cmd += '&& cp /etc/nsswitch.{dns,conf}'
166 (out, err) = runcmd(cmd)
167 if err:
168 raise RuntimeError(err)
169 else:
170 print "Found no unassigned interfaces"
171 except ParserError as e:
172 print 'Parse Errror: %s' % e
173 except RuntimeError as e:
174 print 'Runtime Error: %s' % e
175
176 if __name__ == '__main__':
177 try:
178 main()
179 except KeyboardInterrupt:
180 sys.stderr.write("\x1b[2J\x1b[H")
181
This page took 0.078765 seconds and 6 git commands to generate.