- Timestamp:
- Jun 11, 2019, 10:41:16 AM (6 years ago)
- Location:
- tools
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
tools/gformat.py
r14335 r14374 1 #!/usr/ local/bin/python1 #!/usr/bin/env python3 2 2 # 3 3 # vim:ts=2:et:sw=2:ai … … 32 32 sys.path.append(os.path.dirname(__file__)) 33 33 34 SVN = filter(os.path.isfile, ('/usr/local/bin/svn', '/usr/bin/svn'))[0]35 SVNVERSION = filter(os.path.isfile, ('/usr/local/bin/svnversion', '/usr/bin/svnversion'))[0]34 SVN = next(filter(os.path.isfile, ('/usr/local/bin/svn', '/usr/bin/svn'))) 35 SVNVERSION = next(filter(os.path.isfile, ('/usr/local/bin/svnversion', '/usr/bin/svnversion'))) 36 36 37 37 import argparse 38 38 import cgi 39 39 import cgitb 40 import codecs 40 41 import copy 41 42 import glob … … 51 52 import time 52 53 import traceback 53 import url parse54 import urllib 54 55 55 56 from pprint import pprint 56 57 from collections import defaultdict, OrderedDict 58 from operator import itemgetter, attrgetter 57 59 from sys import stderr 58 60 try: 59 61 import yaml 60 except ImportError ,e:61 print e62 print "[ERROR] Please install the python-yaml or devel/py-yaml package"62 except ImportError as e: 63 print(e) 64 print("[ERROR] Please install the python-yaml or devel/py-yaml package") 63 65 exit(1) 64 66 … … 92 94 93 95 94 if os.environ. has_key('CONFIGROOT'):96 if os.environ.get('CONFIGROOT', None): 95 97 NODE_DIR = os.environ['CONFIGROOT'] 96 98 else: … … 131 133 DHCP_SERVER = 20 132 134 def dhcp_type(item): 133 if not item.has_key('dhcp'):135 if not 'dhcp' in item: 134 136 return NO_DHCP 135 137 elif not item['dhcp']: … … 159 161 try: 160 162 """ Get configuration yaml for 'item'""" 161 if datadump_cache.has_key(item):163 if item in datadump_cache: 162 164 return datadump_cache[item].copy() 163 165 … … 178 180 if datadump['nodetype'] == 'Hybrid': 179 181 # Some values are defined implicitly 180 if datadump.has_key('rdr_host') and datadump['rdr_host'] and not datadump.has_key('service_incoming_rdr'):182 if 'rdr_host' in datadump and datadump['rdr_host'] and not 'service_incoming_rdr' in datadump: 181 183 datadump['service_incoming_rdr'] = True 182 184 # Use some boring defaults … … 188 190 'monitoring_group' : 'wleiden', 189 191 } 190 for (key,value) in defaults.ite ritems():191 if not datadump.has_key(key):192 for (key,value) in defaults.items(): 193 if not key in datadump: 192 194 datadump[key] = value 193 195 f.close() … … 195 197 # Sometimes getting version information is useless or harmfull, like in the pre-commit hooks 196 198 if add_version_info: 197 p = subprocess.Popen([SVN, 'info', datadump['autogen_gfile']], stderr=subprocess.STDOUT, stdout=subprocess.PIPE )199 p = subprocess.Popen([SVN, 'info', datadump['autogen_gfile']], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, universal_newlines=True) 198 200 lines = p.communicate()[0].split('\n') 199 201 if p.returncode == 0: … … 213 215 datadump[key]['autogen_vlan_alias'] = False 214 216 215 datadump[key]['autogen_bridge_member'] = datadump[key].has_key('parent')217 datadump[key]['autogen_bridge_member'] = 'parent' in datadump[key] 216 218 datadump[key]['autogen_bridge'] = datadump[key]['autogen_ifbase'].startswith('bridge') 217 219 datadump[key]['autogen_bridge_alias'] = datadump[key]['autogen_ifbase'].startswith('bridge') and '_alias' in key 218 220 219 if datadump[key].has_key('parent'):220 if datadump[key].has_key('ip'):221 if 'parent' in datadump[key]: 222 if 'ip' in datadump[key]: 221 223 raise ValueError("Interface bridge member cannot have IP assigned") 222 if datadump[key].has_key('dhcp')and datadump[key]['dhcp'] != False:224 if 'dhcp' in datadump[key] and datadump[key]['dhcp'] != False: 223 225 raise ValueError("Interface bridge member cannot have DHCP set") 224 226 225 if datadump[key].has_key('ip'):227 if 'ip' in datadump[key]: 226 228 datadump[key]['autogen_gateway'] = datadump[key]['ip'].split('/')[0] 227 229 … … 252 254 datadump['autogen_item'] = item 253 255 254 datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain')else 'wleiden.net.'256 datadump['autogen_domain'] = datadump['domain'] if 'domain' in datadump else 'wleiden.net.' 255 257 datadump['autogen_fqdn'] = datadump['nodename'] + '.' + datadump['autogen_domain'] 256 258 datadump_cache[item] = datadump.copy() … … 445 447 output += "<h2>Connected To:</h2><ul>" 446 448 (poel, errors) = make_relations() 447 for network, hosts in poel.ite ritems():449 for network, hosts in poel.items(): 448 450 if host in [x[0] for x in hosts]: 449 451 if len(hosts) == 1: … … 474 476 def parseaddr(s): 475 477 """ Process IPv4 CIDR notation addr to a (binary) number """ 476 f = s.split('.') 477 return (long(f[0]) << 24L) + \ 478 (long(f[1]) << 16L) + \ 479 (long(f[2]) << 8L) + \ 480 long(f[3]) 478 f = list(map(int, s.split('.'))) 479 return ((f[0] << 24) + (f[1] << 16) + (f[2] << 8) + (f[3])) 481 480 482 481 … … 554 553 ifname = datadump[iface_key]['autogen_ifbase'] 555 554 groupif = datadump[iface_key]['autogen_if_dhcp'] 556 if not datadump[iface_key].has_key('comment'):555 if not 'comment' in datadump[iface_key]: 557 556 datadump[iface_key]['comment'] = None 558 557 559 if not datadump[iface_key].has_key('ip'):558 if not 'ip' in datadump[iface_key]: 560 559 continue 561 560 … … 613 612 614 613 # Output the blocks in groups 615 for ifname,value in sorted(dhcp_out.ite ritems()):614 for ifname,value in sorted(dhcp_out.items()): 616 615 output += ("shared-network \"%s\" {\n" % ifname) + indent(''.join(value), 2).rstrip() + '\n}\n\n' 617 616 return output … … 637 636 638 637 for iface_key in get_interface_keys(datadump): 639 if not datadump[iface_key].has_key('comment'):638 if not 'comment' in datadump[iface_key]: 640 639 datadump[iface_key]['comment'] = None 641 640 output += "## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key] … … 667 666 668 667 def make_interface_list(datadump): 669 if interface_list_cache.has_key(datadump['autogen_item']):668 if datadump['autogen_item'] in interface_list_cache: 670 669 return (interface_list_cache[datadump['autogen_item']]) 671 670 # lo0 configuration: … … 684 683 masterip_used = False 685 684 for iface_key in get_interface_keys(datadump): 686 if datadump[iface_key].has_key('ip')and datadump[iface_key]['ip'].startswith(datadump['masterip']):685 if 'ip' in datadump[iface_key] and datadump[iface_key]['ip'].startswith(datadump['masterip']): 687 686 masterip_used = True 688 687 break … … 710 709 711 710 # Flag dhclient is possible 712 if not dhclient_if.has_key(ifname)or dhclient_if[ifname] == False:711 if not ifname in dhclient_if or dhclient_if[ifname] == False: 713 712 dhclient_if[ifname] = dhcp_type(ifacedump) == DHCP_CLIENT 714 713 715 714 # Ethernet address 716 if ifacedump.has_key('ether'):715 if 'ether' in ifacedump: 717 716 flags_if[ifname]['ether'] = ifacedump['ether'] 718 717 … … 721 720 722 721 # Add interface IP to list 723 if ifacedump.has_key('ip'):722 if 'ip' in ifacedump: 724 723 item = (ifacedump['ip'], ifacedump['comment']) 725 if addrs_list.has_key(ifname):724 if ifname in addrs_list: 726 725 addrs_list[ifname].append(item) 727 726 else: … … 740 739 ifacedump['autogen_wlanmode'] = "ap" 741 740 742 if not ifacedump.has_key('channel'):741 if not 'channel' in ifacedump: 743 742 if ifacedump['type'] == '11a': 744 743 ifacedump['channel'] = 36 … … 747 746 748 747 # Allow special hacks at the back like wds and stuff 749 if not ifacedump.has_key('extra'):748 if not 'extra' in ifacedump: 750 749 ifacedump['autogen_extra'] = 'regdomain ETSI country NL' 751 750 else: 752 751 ifacedump['autogen_extra'] = ifacedump['extra'] 753 754 ifacedump['autogen_ssid_hex'] = '0x' + ''.join(x.encode('hex') for x in ifacedump['ssid'])752 753 ifacedump['autogen_ssid_hex'] = '0x' + codecs.encode(ifacedump['ssid'].encode('ascii'), 'hex').decode('ascii') 755 754 756 755 output += "wlans_%(autogen_ifbase)s='%(autogen_ifname)s'\n" % ifacedump … … 797 796 """ Generate configuration file '/etc/rc.conf.local' """ 798 797 item = datadump['autogen_item'] 799 if rc_conf_local_cache.has_key(item):798 if item in rc_conf_local_cache: 800 799 return rc_conf_local_cache[item] 801 800 802 if not datadump.has_key('ileiden'):801 if not 'ileiden' in datadump: 803 802 datadump['autogen_ileiden_enable'] = False 804 803 else: … … 856 855 # 857 856 list_ileiden_proxies=" 858 {% for serviceid,item in autogen_ileiden_proxies.ite ritems() -%}857 {% for serviceid,item in autogen_ileiden_proxies.items() -%} 859 858 {{ "%-16s"|format(serviceid) }} # {{ item.nodename }} 860 859 {% endfor -%} … … 997 996 # Print IP address which needs to be assigned over here 998 997 output += "\n" 999 for iface,addrs in sorted(addrs_list.ite ritems()):998 for iface,addrs in sorted(addrs_list.items()): 1000 999 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])): 1001 1000 output += "# %s || %s || %s\n" % (iface, addr, comment) … … 1013 1012 # Make sure the external address is always first as this is needed in the 1014 1013 # firewall setup 1015 addrs = sorted( 1016 [x for x in addrs if not '0.0.0.0' in x[0]], 1017 key=lambda x: x[0].split('.')[0], 1018 cmp=lambda x,y: cmp(1 if x == '172' else 0, 1 if y == '172' else 0) 1019 ) 1020 1014 addrs_tmp = [] 1015 for addr in addrs: 1016 if addr[0].startswith('172'): 1017 addrs_tmp.insert(0, addr) 1018 else: 1019 addrs_tmp.append(addr) 1020 addrs = addrs_tmp 1021 1021 1022 1022 idx_offset = 0 1023 1023 # Set MAC is required 1024 if flags_if[iface].has_key('ether'):1024 if 'ether' in flags_if[iface]: 1025 1025 output += prefix + "ifconfig_%s='link %s'\n" % (iface, flags_if[iface]['ether']) 1026 1026 output += prefix + "ifconfig_%s_alias0='inet %s'\n" % (iface, addrs[0][0]) … … 1096 1096 (poel, errors) = make_relations() 1097 1097 table = [] 1098 for iface,addrs in sorted(addrs_list.ite ritems()):1098 for iface,addrs in sorted(addrs_list.items()): 1099 1099 if iface in ['lo0']: 1100 1100 continue … … 1115 1115 ifacedump = datadump[iface_key] 1116 1116 1117 if not ifacedump.has_key('ns_ip'):1117 if not 'ns_ip' in ifacedump: 1118 1118 continue 1119 1119 … … 1230 1230 autogen_ips = [] 1231 1231 (addrs_list, _, _, dhclient_if, _, extra_ouput) = make_interface_list(datadump) 1232 for iface,addrs in sorted(addrs_list.ite ritems()):1232 for iface,addrs in sorted(addrs_list.items()): 1233 1233 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])): 1234 1234 if addr.startswith('172'): … … 1258 1258 forward-addr: 208.67.220.220 # OpenDNS DNS B 1259 1259 {% else -%} 1260 {%- for serviceid,item in autogen_ileiden_proxies.ite ritems() %}1260 {%- for serviceid,item in autogen_ileiden_proxies.items() %} 1261 1261 {%- if loop.index <= 5 %} 1262 1262 forward-addr: {{ "%-16s"|format(serviceid) }} # {{ item.nodename }} … … 1306 1306 (addrs_list, vlan_list, bridge_list, dhclient_if, flags_if, extra_ouput) = make_interface_list(datadump) 1307 1307 table = [] 1308 for iface,addrs in sorted(addrs_list.ite ritems()):1308 for iface,addrs in sorted(addrs_list.items()): 1309 1309 if iface in ['lo0']: 1310 1310 continue … … 1391 1391 output += "%s:\n" % iface_key 1392 1392 for key,required in key_order: 1393 if datadump[iface_key].has_key(key):1393 if key in datadump[iface_key]: 1394 1394 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key])) 1395 1395 output += "\n\n" … … 1406 1406 output = generate_header(datadump, "#") if header else '' 1407 1407 1408 for key in datadump.keys():1408 for key in list(datadump.keys()): 1409 1409 if key.startswith('autogen_'): 1410 1410 del datadump[key] 1411 1411 # Interface autogen cleanups 1412 1412 elif type(datadump[key]) == dict: 1413 for key2 in datadump[key].keys():1413 for key2 in list(datadump[key].keys()): 1414 1414 if key2.startswith('autogen_'): 1415 1415 del datadump[key][key2] … … 1470 1470 else: 1471 1471 assert False, "Config not found!" 1472 except IOError ,e:1472 except IOError as e: 1473 1473 output += "[ERROR] Config file not found" 1474 1474 return output … … 1502 1502 1503 1503 # Update repository if requested 1504 form = url parse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING')else None1505 if form and form.has_key("action") and "update" in form["action"]:1504 form = urllib.parse.urlparse.parse_qs(environ['QUERY_STRING']) if QUERY_STRING in environ else None 1505 if form and 'action' in form and 'update' in form['action']: 1506 1506 refresh_rate = 5 1507 1507 output = "[INFO] Updating subverion, please wait...\n" … … 1510 1510 output += subprocess.Popen([SVN, 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0] 1511 1511 new_version = subprocess.Popen([SVNVERSION, '-c', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0] 1512 if old_version != new_version or ( environ.has_key('QUERY_STRING')and 'force' in environ['QUERY_STRING']):1512 if old_version != new_version or ('QUERY_STRING' in environ and 'force' in environ['QUERY_STRING']): 1513 1513 try: 1514 1514 generate_static(CACHE_DIR, False) … … 1575 1575 fqdn = datadump['nodename'] 1576 1576 1577 if datadump.has_key('rdr_host'):1577 if 'rdr_host' in datadump: 1578 1578 remote_target = datadump['rdr_host'] 1579 elif datadump.has_key('remote_access')and datadump['remote_access']:1579 elif 'remote_access' in datadump and datadump['remote_access']: 1580 1580 remote_target = datadump['remote_access'].split(':')[0] 1581 1581 else: … … 1610 1610 cidr = int(cidr) 1611 1611 addr = addr & ~((1 << (32 - cidr)) - 1) 1612 if pool.has_key(addr):1612 if addr in pool: 1613 1613 pool[addr] += [(iface_name, fqdn, ip)] 1614 1614 else: … … 1624 1624 1625 1625 # Automatic naming convention of interlinks namely 2 + remote.lower() 1626 for (key,value) in pool.ite ritems():1626 for (key,value) in pool.items(): 1627 1627 # Make sure they are sorted from low-ip to high-ip 1628 1628 value = sorted(value, key=lambda x: parseaddr(x[2])) … … 1674 1674 k, items = line.items()[0] 1675 1675 if type(items) == dict: 1676 if items.has_key('reverse'):1676 if 'reverse' in items: 1677 1677 reverse = items['reverse'] 1678 1678 items = items['a'] … … 1724 1724 f.write(dns_header % details) 1725 1725 1726 for host,items in wleiden_zone.ite ritems():1726 for host,items in wleiden_zone.items(): 1727 1727 for ip,reverse in items: 1728 1728 if ip not in ['0.0.0.0']: 1729 1729 f.write("%s.wleiden.net. IN A %s\n" % (host.lower(), ip)) 1730 for source,dest in wleiden_cname.ite ritems():1730 for source,dest in wleiden_cname.items(): 1731 1731 dest = dest if dest.endswith('.') else dest + ".wleiden.net." 1732 1732 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower())) 1733 for source, dest in wleiden_raw.ite ritems():1733 for source, dest in wleiden_raw.items(): 1734 1734 f.write("%s.wleiden.net. %s\n" % (source, dest)) 1735 1735 f.close() … … 1743 1743 #XXX: Not effient, fix to proper data structure and do checks at other 1744 1744 # stages 1745 for host,items in wleiden_zone.ite ritems():1745 for host,items in wleiden_zone.items(): 1746 1746 for ip,reverse in items: 1747 1747 if not reverse: … … 1756 1756 1757 1757 def usage(): 1758 print 1758 print("""Usage: %(prog)s <argument> 1759 1759 Argument: 1760 1760 \tcleanup = Cleanup all YAML files to specified format … … 1783 1783 VIEW differences and VERIFY all are OK: 1784 1784 $ diff -urI 'Generated' -r /tmp/pre /tmp/post 1785 """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) } 1785 """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }) 1786 1786 exit(0) 1787 1787 … … 1814 1814 def fix_conflict(left, right, default='i'): 1815 1815 while True: 1816 print "## %-30s | %-30s" % (left, right)1816 print("## %-30s | %-30s" % (left, right)) 1817 1817 c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default) 1818 1818 if not c: … … 1828 1828 return None 1829 1829 else: 1830 print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c1830 print("#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c) 1831 1831 1832 1832 … … 1834 1834 def print_cgi_response(response_headers, output): 1835 1835 for header in response_headers: 1836 print "%s: %s" % header1837 print 1838 print output1836 print("%s: %s" % header) 1837 print("") 1838 print(output) 1839 1839 1840 1840 … … 1843 1843 """Hard working sub""" 1844 1844 # Allow easy hacking using the CLI 1845 if not os.environ. has_key('REQUEST_URI'):1845 if not os.environ.get('REQUEST_URI', None): 1846 1846 if len(sys.argv) < 2: 1847 1847 usage() … … 1883 1883 node = sys.argv[2] 1884 1884 except IndexError: 1885 print "Invalid argument"1885 print("Invalid argument") 1886 1886 exit(1) 1887 1887 except IOError as e: 1888 print e1888 print(e) 1889 1889 exit(1) 1890 1890 … … 1898 1898 for config in gen_files: 1899 1899 logger.info("## Generating %s %s", node, config) 1900 print generate_config(node, config, datadump)1900 print(generate_config(node, config, datadump)) 1901 1901 elif sys.argv[1] == "test-cgi": 1902 1902 os.environ['REQUEST_URI'] = "/".join(['config'] + sys.argv[2:]) … … 1927 1927 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]): 1928 1928 ifacedump = datadump[iface_key] 1929 if ifacedump.has_key('mode')and ifacedump['mode'] == 'ap-wds':1929 if 'mode' in ifacedump and ifacedump['mode'] == 'ap-wds': 1930 1930 ifacedump['nodename'] = datadump['nodename'] 1931 if not ifacedump.has_key('channel')or not ifacedump['channel']:1931 if not 'channel' in ifacedump or not ifacedump['channel']: 1932 1932 ifacedump['channel'] = 0 1933 1933 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status) … … 1938 1938 datadump = get_yaml(host) 1939 1939 if datadump.get('service_proxy_normal', False) or datadump.get('service_proxy_ileiden', False): 1940 print 1940 print(textwrap.dedent("""\ 1941 1941 ++ wleiden-gw-%(nodename)s 1942 1942 menu = %(nodename)s.gw 1943 1943 title = Wireless Leiden gateway %(nodename)s.gw.wleiden.net. 1944 1944 host = %(nodename)s.gw.wleiden.net. 1945 """ % datadump) 1945 """ % datadump)) 1946 1946 elif sys.argv[1] == "nagios-export": 1947 1947 try: … … 1963 1963 ip2host[datadump['masterip']] = datadump['autogen_fqdn'] 1964 1964 for iface in get_interface_keys(datadump): 1965 if datadump[iface].has_key('autogen_gateway'):1965 if 'autogen_gateway' in datadump[iface]: 1966 1966 ip2host[datadump[iface]['autogen_gateway']] = datadump['autogen_fqdn'] 1967 1967 … … 1979 1979 parents[ip2host[ip]].append(ip2host[stack[-1]]) 1980 1980 except KeyError as e: 1981 print >> stderr, "# Unable to find %s in configuration files" % e.args[0]1981 print("# Unable to find %s in configuration files" % e.args[0]) 1982 1982 stack.append(ip) 1983 1983 elif prev_depth > depth: … … 1987 1987 parents[ip2host[ip]].append(ip2host[stack[-1]]) 1988 1988 except KeyError as e: 1989 print >> stderr, "# Unable to find %s in configuration files" % e.args[0]1989 print("# Unable to find %s in configuration files" % e.args[0]) 1990 1990 1991 1991 … … 2003 2003 } 2004 2004 2005 print 2005 print('''\ 2006 2006 define host { 2007 2007 name wleiden-node ; Default Node Template … … 2075 2075 # TDB: Advanced local passive checks 2076 2076 # /usr/local/libexec/nagios/check_by_ssh 2077 ''' % params 2078 2079 print 2077 ''' % params) 2078 2079 print('''\ 2080 2080 # Service Group, not displayed by default 2081 2081 define hostgroup { … … 2105 2105 check_command check_dns_wl!"www.wirelessleiden.nl" 2106 2106 } 2107 ''' 2107 ''') 2108 2108 2109 2109 if heavy_load: 2110 print 2110 print('''\ 2111 2111 define service { 2112 2112 use wleiden-service … … 2143 2143 check_command check_snmp_disk 2144 2144 } 2145 ''' 2145 ''') 2146 2146 for node in get_hostlist(): 2147 2147 datadump = get_yaml(node) 2148 2148 if not datadump['status'] == 'up': 2149 2149 continue 2150 if not hostgroup_details.has_key(datadump['monitoring_group']):2150 if not datadump['monitoring_group'] in hostgroup_details: 2151 2151 hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group'] 2152 print 2152 print('''\ 2153 2153 define host { 2154 2154 use wleiden-node,host-pnp … … 2157 2157 address %(masterip)s 2158 2158 hostgroups srv_hybrid,%(monitoring_group)s\ 2159 ''' % datadump 2159 ''' % datadump) 2160 2160 if (len(parents[datadump['autogen_fqdn']]) > 0) and parents[datadump['autogen_fqdn']][0] != 'root': 2161 print 2161 print('''\ 2162 2162 parents %(parents)s\ 2163 ''' % { 'parents' : parents[datadump['autogen_fqdn']][0] } 2164 print 2163 ''' % { 'parents' : parents[datadump['autogen_fqdn']][0] }) 2164 print('''\ 2165 2165 } 2166 ''' 2167 2168 2169 for name,alias in hostgroup_details.ite ritems():2170 print 2166 ''') 2167 2168 2169 for name,alias in hostgroup_details.items(): 2170 print('''\ 2171 2171 define hostgroup { 2172 2172 hostgroup_name %s 2173 2173 alias %s 2174 } ''' % (name, alias) 2174 } ''' % (name, alias)) 2175 2175 2176 2176 … … 2180 2180 datadump = get_yaml(node) 2181 2181 hosts[datadump['nodename']] = datadump 2182 print yaml.dump(hosts)2182 print(yaml.dump(hosts)) 2183 2183 2184 2184 elif sys.argv[1] == "dns": … … 2196 2196 2197 2197 (poel, errors) = make_relations() 2198 print "\n".join(["# WARNING: %s" % x for x in errors])2199 2200 for host,datadump in datadumps.ite ritems():2198 print("\n".join(["# WARNING: %s" % x for x in errors])) 2199 2200 for host,datadump in datadumps.items(): 2201 2201 try: 2202 2202 # Convert all yes and no to boolean values … … 2230 2230 datadump[iface_key]['mode'] = 'ap' 2231 2231 # Wireless Leiden SSID have an consistent lowercase/uppercase 2232 if datadump[iface_key].has_key('ssid'):2232 if 'ssid' in datadump[iface_key]: 2233 2233 ssid = datadump[iface_key]['ssid'] 2234 2234 prefix = 'ap-WirelessLeiden-' 2235 2235 if ssid.lower().startswith(prefix.lower()): 2236 2236 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:] 2237 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):2237 if 'ns_ip' in datadump[iface_key] and not 'mode' in datadump[iface_key]: 2238 2238 datadump[iface_key]['mode'] = 'autogen-FIXME' 2239 if not datadump[iface_key].has_key('comment'):2239 if not 'comment' in datadump[iface_key]: 2240 2240 datadump[iface_key]['comment'] = 'autogen-FIXME' 2241 2241 2242 if datadump[iface_key].has_key('ns_mac'):2242 if 'ns_mac' in datadump[iface_key]: 2243 2243 datadump[iface_key]['ns_mac'] = datadump[iface_key]['ns_mac'].lower() 2244 2244 2245 if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):2245 if 'comment' in datadump[iface_key] and datadump[iface_key]['comment'].startswith('autogen-'): 2246 2246 datadump[iface_key] = datadump[iface_key]['desc'] 2247 2247 … … 2261 2261 # See: https://en.wikipedia.org/wiki/List_of_WLAN_channels 2262 2262 channels_at_2400Mhz = (1,6,11) 2263 if datadump[iface_key]['type'] == '11g' and datadump[iface_key].has_key('channel'):2263 if datadump[iface_key]['type'] == '11g' and 'channel' in datadump[iface_key]: 2264 2264 datadump[iface_key]['channel'] = int(datadump[iface_key]['channel']) 2265 2265 if datadump[iface_key]['channel'] not in channels_at_2400Mhz: … … 2267 2267 2268 2268 # Mandatory interface keys 2269 if not datadump[iface_key].has_key('status'):2269 if not 'status' in datadump[iface_key]: 2270 2270 datadump[iface_key]['status'] = 'planned' 2271 2271 … … 2279 2279 2280 2280 # Making sure description works 2281 if datadump[iface_key].has_key('desc'):2281 if 'desc' in datadump[iface_key]: 2282 2282 if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower(): 2283 2283 del datadump[iface_key]['desc'] 2284 2284 else: 2285 print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)2285 print("# ERROR: At %s - %s" % (datadump['nodename'], iface_key)) 2286 2286 response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc']) 2287 2287 if response: … … 2334 2334 output = datadump['autogen_fqdn'] if use_fqdn else system 2335 2335 if sys.argv[2] == "all": 2336 print output2336 print(output) 2337 2337 elif datadump['status'] == sys.argv[2]: 2338 print output2338 print(output) 2339 2339 elif sys.argv[1] == "create": 2340 2340 if sys.argv[2] == "network.kml": 2341 print make_network_kml.make_graph()2341 print(make_network_kml.make_graph()) 2342 2342 elif sys.argv[2] == "host-ips.txt": 2343 2343 for system in get_hostlist(): … … 2346 2346 for ifkey in get_interface_keys(datadump): 2347 2347 ips.append(datadump[ifkey]['ip'].split('/')[0]) 2348 print system, ' '.join(ips)2348 print(system, ' '.join(ips)) 2349 2349 elif sys.argv[2] == "host-pos.txt": 2350 2350 for system in get_hostlist(): 2351 2351 datadump = get_yaml(system) 2352 print system, datadump['rdnap_x'], datadump['rdnap_y']2352 print(system, datadump['rdnap_x'], datadump['rdnap_y']) 2353 2353 elif sys.argv[2] == "nodeplanner.json": 2354 print make_network_kml.make_nodeplanner_json()2354 print(make_network_kml.make_nodeplanner_json()) 2355 2355 elif sys.argv[2] == 'ssh_config': 2356 print 2356 print(''' 2357 2357 Host *.wleiden.net 2358 2358 User root … … 2360 2360 Host 172.16.*.* 2361 2361 User root 2362 ''' 2362 ''') 2363 2363 for system in get_hostlist(): 2364 2364 datadump = get_yaml(system) 2365 print 2365 print('''\ 2366 2366 Host %s 2367 2367 User root … … 2375 2375 Host %s 2376 2376 User root 2377 ''' % (system, system.lower(), datadump['nodename'], datadump['nodename'].lower()) 2377 ''' % (system, system.lower(), datadump['nodename'], datadump['nodename'].lower())) 2378 2378 else: 2379 2379 usage() … … 2388 2388 response_headers, output = process_cgi_request() 2389 2389 except: 2390 print ''2391 print ''2390 print('') 2391 print('') 2392 2392 raise 2393 2393 -
tools/make_network_kml.py
r14313 r14374 81 81 try: 82 82 for host in gformat.get_hostlist(): 83 if debug: print "## Processing host", host83 if debug: print("## Processing host", host) 84 84 datadump = gformat.get_yaml(host) 85 85 nodename = datadump['nodename'] … … 100 100 mask = int(mask) 101 101 addr = addr & ~((1 << (32 - mask)) - 1) 102 if poel.has_key(addr):102 if addr in poel: 103 103 poel[addr] += [nodename] 104 104 if link_status[addr] == 'linkUp': … … 112 112 poel[addr] = [nodename] 113 113 # Assume all ns_ip to be 11a for a moment 114 if datadump[iface_key].has_key('ns_ip'):114 if 'ns_ip' in datadump[iface_key]: 115 115 link_type[addr] = '11a' 116 116 else: … … 130 130 nodename = datadump['nodename'] 131 131 INTERVAL = 60 * 10 132 if store and store['uptime'].has_key(nodename) and store['snmp'].has_key(nodename) and store['traffic'].has_key(nodename):133 if store and store['traffic'][nodename].has_key(iface):132 if store and nodename in store['uptime'] and nodename in store['snmp'] and nodename in store['traffic']: 133 if store and iface in store['traffic'][nodename]: 134 134 (b_in, b_out) = store['traffic'][nodename][iface] 135 135 uptime = store['uptime'][nodename] 136 136 t_kb = float(b_in + b_out) / 1024 137 if debug: print "# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL)137 if debug: print("# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL)) 138 138 retval = ((t_kb) / uptime) * INTERVAL 139 139 link_data[addr] = retval 140 140 141 if debug: print "### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr])142 except (KeyError, ValueError) ,e:143 if debug: print "[FOUT] in '%s' interface '%s'" % (host,iface_key)144 if debug: print e141 if debug: print("### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr])) 142 except (KeyError, ValueError) as e: 143 if debug: print("[FOUT] in '%s' interface '%s'" % (host,iface_key)) 144 if debug: print(e) 145 145 sys.exit(1) 146 146 return (poel, link_type, link_data, link_status, hosts) … … 169 169 poel, link_type, link_data, link_status, hosts = get_graph_data(debug) 170 170 output = '' 171 if debug: print "# Building KML file"171 if debug: print("# Building KML file") 172 172 output += HEADER 173 173 for nodename, datadump in hosts.iteritems(): … … 204 204 f.write(kml_data) 205 205 f.close() 206 print "# COMPLETED find your output in %s\n" % OUTFILE207 206 print("# COMPLETED find your output in %s\n" % OUTFILE) 207 -
tools/syntax-checker.py
r14025 r14374 1 #!/usr/bin/env python 1 #!/usr/bin/env python3 2 2 # vim:ts=2:et:sw=2:ai 3 3 # … … 12 12 __version__ = '$Id$' 13 13 14 allowed_multi_use = map(lambda x: ipaddress.ip_network(x, strict=True), [ 15 u'192.168.0.0/22', 16 u'192.168.0.0/16', 17 u'192.168.0.0/24', 18 u'192.168.1.0/24', 19 u'192.168.178.0/24', 20 ]) 21 22 23 14 allowed_multi_use = list(map(lambda x: ipaddress.ip_network(x, strict=True), [ 15 '192.168.0.0/22', 16 '192.168.0.0/16', 17 '192.168.0.0/24', 18 '192.168.1.0/24', 19 '192.168.178.0/24', 20 ])) 24 21 25 22 … … 28 25 try: 29 26 for host in gformat.get_hostlist(): 30 print "## Processing host %-25s: " % host,27 print("## Processing host %-25s: " % host, end='') 31 28 datadump = gformat.get_yaml(host,add_version_info=False) 32 masterip_addr = ipaddress.IPv4Interface( unicode(datadump['masterip']))29 masterip_addr = ipaddress.IPv4Interface(datadump['masterip']) 33 30 masterip_is_used = False 34 31 … … 46 43 for entry in ['ip', 'ns_ip']: 47 44 if entry in datadump[iface_key]: 48 addr = ipaddress.IPv4Interface( unicode(datadump[iface_key][entry]))45 addr = ipaddress.IPv4Interface(datadump[iface_key][entry]) 49 46 if masterip_addr in addr.network: 50 47 masterip_is_used = True … … 56 53 pool[masterip_addr.network].append((host, 'masterip', '', masterip_addr)) 57 54 58 print "OK"59 except (KeyError, ValueError) ,e:60 print "[ERROR] in '%s' interface '%s' (%s)" % (host, iface_key, e)55 print("OK") 56 except (KeyError, ValueError) as e: 57 print("[ERROR] in '%s' interface '%s' (%s)" % (host, iface_key, e)) 61 58 raise 62 59 except Exception as e: … … 72 69 if not network2 in allowed_multi_use and network2.overlaps(network): 73 70 errors += 1 74 print "[ERROR#%i] network %s overlaps with %s:" % (errors, network, network2)71 print("[ERROR#%i] network %s overlaps with %s:" % (errors, network, network2)) 75 72 for (host, key, entry, addr) in sorted(pool[network] + pool[network2]): 76 print " - %-20s - %-20s - %-5s - %s" % (host, key, entry, addr)73 print(" - %-20s - %-20s - %-5s - %s" % (host, key, entry, addr)) 77 74 78 75 leden = sorted(pool[network]) … … 81 78 if lid[3] == lid2[3]: 82 79 errors += 1 83 print "[ERROR#%i] Multiple usages of IP %s:" % (errors, lid[3])84 print " - %-20s - %-20s - %-5s" % (lid[0], lid[1], lid[2])85 print " - %-20s - %-20s - %-5s" % (lid2[0], lid2[1], lid2[2])80 print("[ERROR#%i] Multiple usages of IP %s:" % (errors, lid[3])) 81 print(" - %-20s - %-20s - %-5s" % (lid[0], lid[1], lid[2])) 82 print(" - %-20s - %-20s - %-5s" % (lid2[0], lid2[1], lid2[2])) 86 83 87 84 if errors > 0: 88 print "# %i Errors found" % errors85 print("# %i Errors found" % errors) 89 86 return 1 90 87 else: 91 print "# No multiple usages of IPs found"88 print("# No multiple usages of IPs found") 92 89 return 0 93 90
Note:
See TracChangeset
for help on using the changeset viewer.