[10074] | 1 | #!/usr/bin/env python
|
---|
| 2 | # vim:ts=2:et:sw=2:ai
|
---|
| 3 | #
|
---|
| 4 | # Check configs with remote addresses
|
---|
| 5 | #
|
---|
| 6 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
| 7 | #
|
---|
[10093] | 8 | import argparse
|
---|
[10074] | 9 | import gformat
|
---|
[10098] | 10 | import getpass
|
---|
[10093] | 11 | import os
|
---|
[10081] | 12 | import paramiko
|
---|
| 13 | import socket
|
---|
[10074] | 14 | import sys
|
---|
[10093] | 15 | import time
|
---|
[10074] | 16 |
|
---|
[10098] | 17 | SSHPASS = None
|
---|
[10433] | 18 | import pysnmp
|
---|
| 19 | from pysnmp.entity.rfc3413.oneliner import cmdgen
|
---|
[10892] | 20 | import netsnmp
|
---|
[10081] | 21 |
|
---|
[10433] | 22 | def snmp_test():
|
---|
| 23 | errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
|
---|
| 24 | # SNMP v1
|
---|
| 25 | # cmdgen.CommunityData('test-agent', 'public', 0),
|
---|
| 26 | # SNMP v2
|
---|
| 27 | cmdgen.CommunityData('test-agent', 'public'),
|
---|
| 28 | # SNMP v3
|
---|
| 29 | # cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'),
|
---|
| 30 | cmdgen.UdpTransportTarget(('localhost', 161)),
|
---|
| 31 | # Plain OID
|
---|
| 32 | (1,3,6,1,2,1,1,1,0),
|
---|
| 33 | # ((mib-name, mib-symbol), instance-id)
|
---|
| 34 | (('SNMPv2-MIB', 'sysObjectID'), 0)
|
---|
| 35 | )
|
---|
| 36 |
|
---|
| 37 | if errorIndication:
|
---|
| 38 | print errorIndication
|
---|
| 39 | else:
|
---|
| 40 | if errorStatus:
|
---|
| 41 | print '%s at %s\n' % (
|
---|
| 42 | errorStatus.prettyPrint(),
|
---|
| 43 | errorIndex and varBinds[int(errorIndex)-1] or '?'
|
---|
| 44 | )
|
---|
| 45 | else:
|
---|
| 46 | for name, val in varBinds:
|
---|
| 47 | print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
|
---|
| 48 |
|
---|
| 49 |
|
---|
| 50 |
|
---|
[10074] | 51 | class CmdError(Exception):
|
---|
| 52 | pass
|
---|
| 53 |
|
---|
[10434] | 54 | class ConnectError(Exception):
|
---|
| 55 | pass
|
---|
[10433] | 56 |
|
---|
| 57 |
|
---|
[10434] | 58 |
|
---|
[10433] | 59 | def host_ssh_cmd(hostname, cmd):
|
---|
[10434] | 60 | try:
|
---|
| 61 | ssh = paramiko.SSHClient()
|
---|
| 62 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
---|
| 63 | ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
|
---|
| 64 | stdin, stdout, stderr = ssh.exec_command(cmd)
|
---|
| 65 | stdout = stdout.readlines()
|
---|
| 66 | stderr = stderr.readlines()
|
---|
| 67 | ssh.close()
|
---|
| 68 | if stderr:
|
---|
| 69 | raise CmdError((stderr, stdout))
|
---|
| 70 | return stdout
|
---|
| 71 | except socket.error, e:
|
---|
| 72 | raise ConnectError(e)
|
---|
[10074] | 73 |
|
---|
[10433] | 74 | def parse_ini(lines):
|
---|
| 75 | return dict(map(lambda x: x.strip().split('='),lines))
|
---|
| 76 |
|
---|
| 77 | def ubnt_probe(hostname):
|
---|
| 78 | items = parse_ini(host_ssh_cmd(hostname, 'cat /etc/board.info'))
|
---|
| 79 | print items
|
---|
| 80 |
|
---|
| 81 |
|
---|
[10075] | 82 | def get_bridge_type(host):
|
---|
[10081] | 83 | """ Both NS and NS Mx uses a slighly different OID"""
|
---|
| 84 | var_list = netsnmp.VarList(
|
---|
| 85 | *map(lambda x: netsnmp.Varbind(x),
|
---|
| 86 | ['.1.2.840.10036.3.1.2.1.3.6', '.1.2.840.10036.3.1.2.1.3.7']))
|
---|
[10075] | 87 |
|
---|
[10099] | 88 | sess = netsnmp.Session(Version=1, DestHost=host, Community='public', Timeout=2 * 100000, Retries=1)
|
---|
[10075] | 89 | retval = sess.get(var_list)
|
---|
| 90 | if sess.ErrorInd < 0:
|
---|
[10098] | 91 | raise CmdError('SNMP Failed -- [%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
|
---|
[10081] | 92 | return filter(None, retval)[0]
|
---|
[10074] | 93 |
|
---|
[10075] | 94 |
|
---|
[10082] | 95 |
|
---|
[10433] | 96 | def node_check(host):
|
---|
| 97 | print "# Processing host", host
|
---|
| 98 | datadump = gformat.get_yaml(host)
|
---|
| 99 | output = host_ssh_cmd(datadump['autogen_fqdn'], 'cat /var/run/dmesg.boot')
|
---|
[10093] | 100 |
|
---|
[10433] | 101 | # Get board Type
|
---|
| 102 | for line in [x.strip() for x in output]:
|
---|
| 103 | if line.startswith('CPU:'):
|
---|
| 104 | print line
|
---|
| 105 | elif line.startswith('Geode LX:'):
|
---|
| 106 | datadump['board'] = 'ALIX2'
|
---|
| 107 | print line
|
---|
| 108 | elif line.startswith('real memory'):
|
---|
| 109 | print line
|
---|
| 110 | elif line.startswith('Elan-mmcr'):
|
---|
| 111 | datadump['board'] = 'net45xx'
|
---|
[10892] | 112 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 113 | ifacedump = datadump[iface_key]
|
---|
| 114 | if ifacedump.has_key('ns_ip') and ifacedump['ns_ip']:
|
---|
| 115 | addr = ifacedump['ns_ip'].split('/')[0]
|
---|
| 116 | print "## Bridge IP: %(ns_ip)s at %(autogen_ifname)s" % ifacedump
|
---|
| 117 | try:
|
---|
| 118 | socket.create_connection((addr,80),2)
|
---|
| 119 | bridge_type = get_bridge_type(addr)
|
---|
| 120 | datadump[iface_key]['bridge_type'] = bridge_type
|
---|
| 121 | except (socket.timeout, socket.error) as e:
|
---|
| 122 | print "### %s (%s)" % (e, addr)
|
---|
| 123 | except paramiko.AuthenticationException:
|
---|
| 124 | print "### Conection failed (invalid username/password)"
|
---|
| 125 | except CmdError, e:
|
---|
| 126 | print "### Command error: %s" % e
|
---|
[10433] | 127 | gformat.store_yaml(datadump)
|
---|
[10074] | 128 |
|
---|
[10433] | 129 |
|
---|
[10093] | 130 | def make_output(stdout, stderr):
|
---|
| 131 | def p(prefix, lines):
|
---|
| 132 | return ''.join(["#%s: %s" % (prefix, line) for line in lines])
|
---|
| 133 | output = p('STDOUT', stdout)
|
---|
| 134 | output += p('STDERR', stderr)
|
---|
| 135 | return output
|
---|
[10083] | 136 |
|
---|
[10093] | 137 | def ubnt_snmp(hostname):
|
---|
| 138 | lines = """\
|
---|
| 139 | snmp.community=public
|
---|
| 140 | snmp.contact=beheer@lijst.wirelessleiden.nl
|
---|
| 141 | snmp.location=WL
|
---|
| 142 | snmp.status=enabled\
|
---|
| 143 | """
|
---|
[10095] | 144 | cmd = 'mca-config get /tmp/get.cfg && grep -v snmp /tmp/get.cfg > /tmp/new.cfg && echo "%s" >> /tmp/new.cfg \
|
---|
[10097] | 145 | && mca-config activate /tmp/new.cfg 1>/dev/null 2>/dev/null && echo "ALL DONE"' % lines
|
---|
[10093] | 146 | ssh = paramiko.SSHClient()
|
---|
| 147 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
---|
| 148 | ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
|
---|
| 149 | stdin, stdout, stderr = ssh.exec_command(cmd)
|
---|
| 150 | stdout = stdout.readlines()
|
---|
| 151 | stderr = stderr.readlines()
|
---|
| 152 | print make_output(stdout, stderr)
|
---|
| 153 | ssh.close()
|
---|
[10084] | 154 |
|
---|
[10093] | 155 | def ubnt_keys(hostname):
|
---|
[10094] | 156 | keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
|
---|
[10093] | 157 | ssh = paramiko.SSHClient()
|
---|
| 158 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
---|
| 159 | ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
|
---|
| 160 | cmd = 'test -d .ssh || mkdir .ssh;\
|
---|
[10094] | 161 | cat > .ssh/authorized_keys && \
|
---|
[10093] | 162 | chmod 0700 .ssh && \
|
---|
[10094] | 163 | chmod 0755 . && cfgmtd -p /etc -w'
|
---|
[10093] | 164 | stdin, stdout, stderr = ssh.exec_command(cmd)
|
---|
[10094] | 165 | stdin.write(keys)
|
---|
| 166 | stdin.flush()
|
---|
| 167 | stdin.channel.shutdown_write()
|
---|
[10093] | 168 | stdout = stdout.readlines()
|
---|
| 169 | stderr = stderr.readlines()
|
---|
| 170 | print make_output(stdout, stderr)
|
---|
| 171 | ssh.close()
|
---|
[10085] | 172 |
|
---|
[10093] | 173 | if __name__ == '__main__':
|
---|
| 174 | # create the top-level parser
|
---|
| 175 | parser = argparse.ArgumentParser(prog='Various WL management tools')
|
---|
[10098] | 176 | parser.add_argument('--ask-pass', dest="ask_pass", action='store_true', help='Ask password if SSHPASS is not found')
|
---|
[10434] | 177 | parser.add_argument('--filter', dest="use_filter", action='store_true', help='Thread the host definition as an filter')
|
---|
[10093] | 178 | subparsers = parser.add_subparsers(help='sub-command help')
|
---|
| 179 |
|
---|
[10433] | 180 | parser_snmp = subparsers.add_parser('bridge', help='UBNT Bridge Management')
|
---|
| 181 | parser_snmp.add_argument('action', type=str, choices=['keys', 'snmp', 'probe'])
|
---|
[10093] | 182 | parser_snmp.add_argument('host',type=str)
|
---|
[10433] | 183 | parser_snmp.set_defaults(func='bridge')
|
---|
[10093] | 184 |
|
---|
[10433] | 185 | parser_node = subparsers.add_parser('node', help='Proxy/Node/Hybrid Management')
|
---|
| 186 | parser_node.add_argument('action', type=str, choices=['check',])
|
---|
| 187 | parser_node.add_argument('host', type=str)
|
---|
| 188 | parser_node.set_defaults(func='node')
|
---|
[10086] | 189 |
|
---|
[10093] | 190 | args = parser.parse_args()
|
---|
[10087] | 191 |
|
---|
[10098] | 192 | try:
|
---|
| 193 | SSHPASS = os.environ['SSHPASS']
|
---|
| 194 | except KeyError:
|
---|
| 195 | print "#WARN: SSHPASS environ variable not found"
|
---|
| 196 | if args.ask_pass:
|
---|
| 197 | SSHPASS = getpass.getpass("WL root password: ")
|
---|
| 198 |
|
---|
| 199 |
|
---|
[10434] | 200 | if args.use_filter:
|
---|
| 201 | hosts = []
|
---|
| 202 | for host in gformat.get_hostlist():
|
---|
| 203 | if args.host in host:
|
---|
| 204 | hosts.append(host)
|
---|
| 205 | else:
|
---|
| 206 | hosts = [args.host]
|
---|
[10433] | 207 |
|
---|
[10434] | 208 |
|
---|
| 209 | for host in hosts:
|
---|
| 210 | try:
|
---|
| 211 | if args.func == 'bridge':
|
---|
| 212 | if args.action == 'keys':
|
---|
| 213 | ubnt_keys(host)
|
---|
| 214 | elif args.action == 'snmp':
|
---|
| 215 | ubnt_snmp(host)
|
---|
| 216 | elif args.action == 'probe':
|
---|
| 217 | ubnt_probe(host)
|
---|
| 218 | elif args.func == 'node':
|
---|
| 219 | if args.action == 'check':
|
---|
| 220 | node_check(host)
|
---|
| 221 | except ConnectError:
|
---|
| 222 | print "#ERR: Connection failed to host %s" % host
|
---|