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

Last change on this file since 10932 was 10892, checked in by rick, 13 years ago

Doe een import van de bridge unit dmv een scan.

  • Property svn:executable set to *
File size: 6.7 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 socket
14import sys
15import time
16
17SSHPASS = None
18import pysnmp
19from pysnmp.entity.rfc3413.oneliner import cmdgen
20import netsnmp
21
22def 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
51class CmdError(Exception):
52 pass
53
54class ConnectError(Exception):
55 pass
56
57
58
59def host_ssh_cmd(hostname, cmd):
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)
73
74def parse_ini(lines):
75 return dict(map(lambda x: x.strip().split('='),lines))
76
77def ubnt_probe(hostname):
78 items = parse_ini(host_ssh_cmd(hostname, 'cat /etc/board.info'))
79 print items
80
81
82def get_bridge_type(host):
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']))
87
88 sess = netsnmp.Session(Version=1, DestHost=host, Community='public', Timeout=2 * 100000, Retries=1)
89 retval = sess.get(var_list)
90 if sess.ErrorInd < 0:
91 raise CmdError('SNMP Failed -- [%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
92 return filter(None, retval)[0]
93
94
95
96def 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')
100
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'
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
127 gformat.store_yaml(datadump)
128
129
130def 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
136
137def ubnt_snmp(hostname):
138 lines = """\
139snmp.community=public
140snmp.contact=beheer@lijst.wirelessleiden.nl
141snmp.location=WL
142snmp.status=enabled\
143"""
144 cmd = 'mca-config get /tmp/get.cfg && grep -v snmp /tmp/get.cfg > /tmp/new.cfg && echo "%s" >> /tmp/new.cfg \
145 && mca-config activate /tmp/new.cfg 1>/dev/null 2>/dev/null && echo "ALL DONE"' % lines
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()
154
155def ubnt_keys(hostname):
156 keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
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;\
161 cat > .ssh/authorized_keys && \
162 chmod 0700 .ssh && \
163 chmod 0755 . && cfgmtd -p /etc -w'
164 stdin, stdout, stderr = ssh.exec_command(cmd)
165 stdin.write(keys)
166 stdin.flush()
167 stdin.channel.shutdown_write()
168 stdout = stdout.readlines()
169 stderr = stderr.readlines()
170 print make_output(stdout, stderr)
171 ssh.close()
172
173if __name__ == '__main__':
174 # create the top-level parser
175 parser = argparse.ArgumentParser(prog='Various WL management tools')
176 parser.add_argument('--ask-pass', dest="ask_pass", action='store_true', help='Ask password if SSHPASS is not found')
177 parser.add_argument('--filter', dest="use_filter", action='store_true', help='Thread the host definition as an filter')
178 subparsers = parser.add_subparsers(help='sub-command help')
179
180 parser_snmp = subparsers.add_parser('bridge', help='UBNT Bridge Management')
181 parser_snmp.add_argument('action', type=str, choices=['keys', 'snmp', 'probe'])
182 parser_snmp.add_argument('host',type=str)
183 parser_snmp.set_defaults(func='bridge')
184
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')
189
190 args = parser.parse_args()
191
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
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]
207
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
Note: See TracBrowser for help on using the repository browser.