]>
git.datanom.net - netconf.git/blob - netconf.py
3 # This file and its contents are supplied under the terms of the
4 # Common Development and Distribution License ("CDDL"), version 1.0.
5 # You may only use this file in accordance with the terms of version
8 # A full copy of the text of the CDDL should have accompanied this
9 # source. A copy of the CDDL is also available via the Internet at
10 # http://www.illumos.org/license/CDDL.
14 # Copyright 2017 <Michael Rasmussen>
18 # The porpuse of this script is to help with basic and/or initial
19 # network configuration for Illumos based distribution. However,
20 # the script is developed specifically for OmniOS so there is no
21 # garaunty that it will work on other Illumos based distributions
25 import sys
, subprocess
, getopt
28 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
29 output
, error
= process
.communicate();
31 return (output
.rstrip(), error
.rstrip())
33 class ParserError(Exception):
37 """ Parse nic information """
40 self
.__dladm
1 = "dladm show-phys -p -o link,media | sed 's/:/ /g'"
41 self
.__dladm
2 = "dladm show-phys -p -m -o link,address,inuse | sed 's/:/ /g' | sed 's/\\\[[:space:]]/:/g' | sed 's/\\\//g'"
43 def __parse_nics(self
, text
):
45 for line
in text
.splitlines():
47 #if parts[1] in ('Ethernet', 'Infiniband'):
48 if parts
[1] in ('Ethernet'):
49 nics
[parts
[0]] = [parts
[0], parts
[1]]
53 def __parse_macs(self
, obj
, text
):
56 for line
in text
.splitlines():
62 obj
[parts
[0]].append(parts
[1])
65 for k
, v
in obj
.items():
71 (nics
, error
) = runcmd(self
.__dladm
1)
73 raise ParserError(error
)
75 (macs
, error
) = runcmd(self
.__dladm
2)
77 raise ParserError(error
)
79 return self
.__parse
_macs
(self
.__parse
_nics
(nics
), macs
)
81 def get_terminal_width():
83 if sys
.version_info
>= (2,7):
84 width
= int(subprocess
.check_output(['tput', 'cols']))
86 (out
, err
) = runcmd('tput cols')
91 print("Invalid Command 'tput cols': exit status ({1})".format(e
.errno
))
92 except subprocess
.CalledProcessError
as e
:
93 print("Command 'tput cols' returned non-zero exit status: ({1})".format(e
.returncode
))
97 def make_menu(interfaces
):
100 sys
.stderr
.write("\x1b[2J\x1b[H")
101 cols
= get_terminal_width()
102 intro
= 'The following unconfigured interfaces was discovered'
103 fill
= (cols
/ 2) - (len(intro
) / 2)
104 print '{0:^{cols}}'.format('Simple network interface configuration tool', cols
=cols
)
106 print '{0:<{fill}}{1}'.format('', intro
, fill
=fill
)
107 print '{0:<{fill}}{1:>2} {2:^15} {3:^10} {4:^17}'.format('','#','Interface','Media','MAC',fill
=fill
)
108 print '{0:<{fill}}{1:-^2} {2:-^15} {3:-^10} {4:-^17}'.format('','','','','',fill
=fill
)
112 print '{0:<{fill}}{1:>2} {2:<15} {3:<10} {4:>17}'.format('',n
,i
[0],i
[1],i
[2],fill
=fill
)
115 print '{0:<{fill}}{1:<}'.format('','select interface number to configure:',fill
=fill
),
116 nic
= int(raw_input())
117 if nic
>= n
or nic
< 0:
118 print '{0:<{fill}}{1:<} {2:<}'.format('','Error: Interface: 0 <= # <',n
,fill
=fill
),
119 raw_input(' << Hit any key >>')
121 res
= interfaces
[nic
]
126 ip
= mask
= gw
= None
127 nettype
= raw_input('dhcp or static [dhcp]: ').lower()
128 if nettype
== 'static':
130 ip
= raw_input('Enter IP: ')
131 mask
= raw_input('Enter netmask [24]: ')
134 gw
= raw_input('Enter default route [0=no]: ')
141 print 'Usage: %s [options]' % sys
.argv
[0]
143 print '%s' % """Options:
144 -h, --help This usage.
145 -a, --address IP for interface. 0 means use DHCP
146 -g, --gateway Default gateway. Optional.
147 -i, --interface Interface to configure.
148 -m, --netmask Netmask to use for interface. Default /24.
149 -n, --nameserver Nameserver to use. Optional.
150 -r, --record Output create commands to stdout."""
156 opts
, args
= getopt
.gnu_getopt(sys
.argv
[1:],
157 'ha:g:i:m:n:r', ['help', 'address=', 'gateway=',
158 'interface=', 'netmask=', 'nameserver=', 'record'])
159 except getopt
.GetoptError
as err
:
164 address
= gateway
= interface
= netmask
= nameserver
= None
169 if o
in ('-h', '--help'):
172 if o
in ('-a', '--address'):
174 elif o
in ('-g', '--gateway'):
176 elif o
in ('-i', '--interface'):
178 elif o
in ('-m', '--netmask'):
180 elif o
in ('-n', '--nameserver'):
182 elif o
in ('-r', '--record'):
185 assert False, 'Unhandled option'
188 if (bool(address
) ^
bool(interface
)):
189 print 'Error: missing options'
193 if not address
or not interface
or error
:
194 print 'Error: missing options'
203 options
= (interface
, address
, netmask
, gateway
, nameserver
, record
)
212 options
= parse_input()
220 interfaces
= p
.parse()
223 nic
= make_menu(interfaces
)
232 err
= '%s: No such interface' % nic
[0]
233 raise RuntimeError(err
)
236 (ip
,mask
,gw
) = get_config()
241 cmd
= 'ipadm delete-if %s' % nic
[0]
246 cmd
= 'ipadm create-if %s' % nic
[0]
250 (out
, err
) = runcmd(cmd
)
252 raise RuntimeError(err
)
255 cmd
= 'ipadm create-addr -T dhcp %s/v4' % nic
[0]
259 (out
, err
) = runcmd(cmd
)
261 raise RuntimeError(err
)
264 cmd
= 'ipadm create-addr -T static -a %s/%s %s/v4' % (ip
, mask
, nic
[0])
268 (out
, err
) = runcmd(cmd
)
270 raise RuntimeError(err
)
272 cmd
= 'route -p add default %s' % gw
276 (out
, err
) = runcmd(cmd
)
278 raise RuntimeError(err
)
280 cmd
= 'netstat -rn -finet'
281 (out
, err
) = runcmd(cmd
)
283 raise RuntimeError(err
)
284 print 'New route table'
287 dns
= raw_input('Configure DNS [n]? ').lower()
290 if not dns
or dns
== 'n':
297 dns
= raw_input('Enter nameserver: ')
299 cmd
= "echo 'nameserver %s' >> /etc/resolv.conf " % dns
300 cmd
+= '&& cp /etc/nsswitch.conf{,.bak} '
301 cmd
+= '&& cp /etc/nsswitch.{dns,conf}'
305 (out
, err
) = runcmd(cmd
)
307 raise RuntimeError(err
)
311 print "Found no unassigned interfaces"
312 except ParserError
as e
:
313 print 'Parse Errror: %s' % e
314 except RuntimeError as e
:
315 print 'Runtime Error: %s' % e
317 if __name__
== '__main__':
320 except KeyboardInterrupt:
321 sys
.stderr
.write("\x1b[2J\x1b[H")
This page took 0.205464 seconds and 6 git commands to generate.