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

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

Awefull hack to get some basic board discovery going.

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