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