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

Last change on this file since 11727 was 11727, checked in by rick, 12 years ago

Not used anymore, causing import errors.

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