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

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