本篇承接上一篇 saltstack实现批量路由增加 ,在上一篇中提到了使用saltstack自带的network state实现了redhat路由的自动配置,不过在suse系统下却无解,晚上没事写了个模块,实现了针对suse系统实现路由增加。代码如下:

 1#coding: utf-8
 2# code from www.361way.com
 3import commands
 4__outputter__ = {
 5  'suse': 'txt',
 6}
 7_SUSE_ROUTE_FILE = '/etc/sysconfig/network/routes'
 8def init():
 9    ywgw = __grains__['dcnyw']['ywgw']
10    yweth = __grains__['dcnyw']['yweth']
11    dcngw = __grains__['dcnyw']['dcngw']
12    dcneth = __grains__['dcnyw']['dcneth']
13    return ywgw,yweth,dcngw,dcneth
14def routing():
15    out = ""
16    ywgw,yweth,dcngw,dcneth = init()
17    if ywgw and yweth and dcngw and dcneth:
18        r1 = "route add default " + ywgw
19        r2 = "route add -net 10.0.0.0 netmask 255.0.0.0 gw " + dcngw
20        r3 = "route add -net 200.200.0.0 netmask 255.255.0.0 gw " + dcngw
21        r4 = "route add -net 10.211.6.0 netmask 255.255.255.0 gw " + ywgw
22        r5 = "route add -net 10.125.0.0 netmask 255.255.0.0 gw " + ywgw
23        out = commands.getoutput(r1 + '\n' + r2 +'\n' + r3 +'\n' + r4 +'\n' + r5)
24    return out
25def suse():
26    if __grains__['os'] == 'SUSE':
27        routing()
28        ywgw,yweth,dcngw,dcneth = init()
29        routestr = """default %s --
3010.0.0.0 %s 255.0.0.0 %s
3110.125.0.0 %s 255.255.0.0 %s
3210.211.6.0 %s 255.255.255.0 %s
33200.200.0.0 %s 255.255.0.0 %s
34""" %(ywgw,dcngw,dcneth,ywgw,yweth,ywgw,yweth,dcngw,dcneth)
35        f = open(_SUSE_ROUTE_FILE, 'w')
36        f.writelines(routestr)
37        f.close()
38        cmd = 'netstat -A inet -rn |tail -n +3'
39        return __salt__['cmd.run'](cmd)
40    else:
41        eturn 'OS not SuSE or can not get eth and gateway info!'

上面的代码需要注意,调用系统grains时,不能写在def函数体外,最开始我想将该定义写在函数体外,发现调用不成功,在minion端的/var/log/salt/minion日志中提示grains定义不存在。具体执行效果见下图:

sqroute
sqroute

上面示例中只实了suse 路由这一个功能,如果不想使用系统自带的network.route state功能,也可以把redhat下的路由增加功能在该模块中写下。