source: genesis/tools/check-batch-cmd@ 11701

Last change on this file since 11701 was 11053, checked in by rick, 13 years ago

Cleanups & Data verzamelen.

Nu we hier zijn, ook eens kijken naar de wl_release (svn version) of het image
was gedeployt is, dit zou wel eens makkelijk kunnen zijn om updates en versie
beheer van de nodes beter te administreren en detecteren.

  • Property svn:executable set to *
File size: 7.2 KB
Line 
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#
8import argparse
9import gformat
10import getpass
11import os
12import paramiko
13import subprocess
14import socket
15import sys
16import time
17
18SSHPASS = None
19import pysnmp
20from pysnmp.entity.rfc3413.oneliner import cmdgen
21import netsnmp
22
23def 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
52class CmdError(Exception):
53 pass
54
55class ConnectError(Exception):
56 pass
57
58
59
60def host_ssh_cmd(hostname, cmd):
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
72 except (socket.error, paramiko.AuthenticationException) as e:
73 raise ConnectError(e)
74
75def parse_ini(lines):
76 return dict(map(lambda x: x.strip().split('='),lines))
77
78def ubnt_probe(hostname):
79 items = parse_ini(host_ssh_cmd(hostname, 'cat /etc/board.info'))
80 print items
81
82
83def get_bridge_type(host):
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']))
88
89 sess = netsnmp.Session(Version=1, DestHost=host, Community='public', Timeout=2 * 100000, Retries=1)
90 retval = sess.get(var_list)
91 if sess.ErrorInd < 0:
92 raise CmdError('SNMP Failed -- [%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
93 return filter(None, retval)[0]
94
95
96
97def node_check(host):
98 """ Using multiple connect methods to do some basic health checking as well"""
99
100 print "# Processing host", host
101 datadump = gformat.get_yaml(host)
102 output = host_ssh_cmd(datadump['autogen_fqdn'], 'cat /var/run/dmesg.boot')
103
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'
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
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
137 gformat.store_yaml(datadump)
138
139
140def 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
146
147def ubnt_snmp(hostname):
148 lines = """\
149snmp.community=public
150snmp.contact=beheer@lijst.wirelessleiden.nl
151snmp.location=WL
152snmp.status=enabled\
153"""
154 cmd = 'mca-config get /tmp/get.cfg && grep -v snmp /tmp/get.cfg > /tmp/new.cfg && echo "%s" >> /tmp/new.cfg \
155 && mca-config activate /tmp/new.cfg 1>/dev/null 2>/dev/null && echo "ALL DONE"' % lines
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()
164
165def ubnt_keys(hostname):
166 keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
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;\
171 cat > .ssh/authorized_keys && \
172 chmod 0700 .ssh && \
173 chmod 0755 . && cfgmtd -p /etc -w'
174 stdin, stdout, stderr = ssh.exec_command(cmd)
175 stdin.write(keys)
176 stdin.flush()
177 stdin.channel.shutdown_write()
178 stdout = stdout.readlines()
179 stderr = stderr.readlines()
180 print make_output(stdout, stderr)
181 ssh.close()
182
183if __name__ == '__main__':
184 # create the top-level parser
185 parser = argparse.ArgumentParser(prog='Various WL management tools')
186 parser.add_argument('--ask-pass', dest="ask_pass", action='store_true', help='Ask password if SSHPASS is not found')
187 parser.add_argument('--filter', dest="use_filter", action='store_true', help='Thread the host definition as an filter')
188 subparsers = parser.add_subparsers(help='sub-command help')
189
190 parser_snmp = subparsers.add_parser('bridge', help='UBNT Bridge Management')
191 parser_snmp.add_argument('action', type=str, choices=['keys', 'snmp', 'probe'])
192 parser_snmp.add_argument('host',type=str)
193 parser_snmp.set_defaults(func='bridge')
194
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')
199
200 args = parser.parse_args()
201
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
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]
217
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
Note: See TracBrowser for help on using the repository browser.