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

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

Lets start storing the board type in gformat, to give a better look of the hardware in production (and check interface naming for example).

  • Property svn:executable set to *
File size: 6.7 KB
RevLine 
[10074]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#
[10093]8import argparse
[10074]9import gformat
[10098]10import getpass
[10093]11import os
[10081]12import paramiko
13import socket
[10074]14import sys
[10093]15import time
[10074]16
[10098]17SSHPASS = None
[10433]18import pysnmp
19from pysnmp.entity.rfc3413.oneliner import cmdgen
[10081]20
[10433]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
[10074]50class CmdError(Exception):
51 pass
52
[10434]53class ConnectError(Exception):
54 pass
[10433]55
56
[10434]57
[10433]58def host_ssh_cmd(hostname, cmd):
[10434]59 try:
60 ssh = paramiko.SSHClient()
61 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
62 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
63 stdin, stdout, stderr = ssh.exec_command(cmd)
64 stdout = stdout.readlines()
65 stderr = stderr.readlines()
66 ssh.close()
67 if stderr:
68 raise CmdError((stderr, stdout))
69 return stdout
70 except socket.error, e:
71 raise ConnectError(e)
[10074]72
[10433]73def parse_ini(lines):
74 return dict(map(lambda x: x.strip().split('='),lines))
75
76def ubnt_probe(hostname):
77 items = parse_ini(host_ssh_cmd(hostname, 'cat /etc/board.info'))
78 print items
79
80
[10075]81def get_bridge_type(host):
[10081]82 """ Both NS and NS Mx uses a slighly different OID"""
83 var_list = netsnmp.VarList(
84 *map(lambda x: netsnmp.Varbind(x),
85 ['.1.2.840.10036.3.1.2.1.3.6', '.1.2.840.10036.3.1.2.1.3.7']))
[10075]86
[10099]87 sess = netsnmp.Session(Version=1, DestHost=host, Community='public', Timeout=2 * 100000, Retries=1)
[10075]88 retval = sess.get(var_list)
89 if sess.ErrorInd < 0:
[10098]90 raise CmdError('SNMP Failed -- [%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
[10081]91 return filter(None, retval)[0]
[10074]92
[10075]93
[10082]94
[10433]95def node_check(host):
96 print "# Processing host", host
97 datadump = gformat.get_yaml(host)
98 output = host_ssh_cmd(datadump['autogen_fqdn'], 'cat /var/run/dmesg.boot')
[10093]99
[10433]100 # Get board Type
101 for line in [x.strip() for x in output]:
102 if line.startswith('CPU:'):
103 print line
104 elif line.startswith('Geode LX:'):
105 datadump['board'] = 'ALIX2'
106 print line
107 elif line.startswith('real memory'):
108 print line
109 elif line.startswith('Elan-mmcr'):
110 datadump['board'] = 'net45xx'
111 #for iface_key in datadump['autogen_iface_keys']:
112 # ifacedump = datadump[iface_key]
113 # if ifacedump.has_key('ns_ip') and ifacedump['ns_ip']:
114 # addr = ifacedump['ns_ip'].split('/')[0]
115 # print "## Bridge IP: %(ns_ip)s at %(interface)s" % ifacedump
116 # try:
117 # socket.create_connection((addr,80),2)
118 # bridge_type = get_bridge_type(addr)
119 # datadump[iface_key]['bridge_type'] = bridge_type
120 # except (socket.timeout, socket.error) as e:
121 # print "### %s (%s)" % (e, addr)
122 # except paramiko.AuthenticationException:
123 # print "### Conection failed (invalid username/password)"
124 # except CmdError, e:
125 # print "### Command error: %s" % e
126 gformat.store_yaml(datadump)
[10074]127
[10433]128
[10093]129def make_output(stdout, stderr):
130 def p(prefix, lines):
131 return ''.join(["#%s: %s" % (prefix, line) for line in lines])
132 output = p('STDOUT', stdout)
133 output += p('STDERR', stderr)
134 return output
[10083]135
[10093]136def ubnt_snmp(hostname):
137 lines = """\
138snmp.community=public
139snmp.contact=beheer@lijst.wirelessleiden.nl
140snmp.location=WL
141snmp.status=enabled\
142"""
[10095]143 cmd = 'mca-config get /tmp/get.cfg && grep -v snmp /tmp/get.cfg > /tmp/new.cfg && echo "%s" >> /tmp/new.cfg \
[10097]144 && mca-config activate /tmp/new.cfg 1>/dev/null 2>/dev/null && echo "ALL DONE"' % lines
[10093]145 ssh = paramiko.SSHClient()
146 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
147 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
148 stdin, stdout, stderr = ssh.exec_command(cmd)
149 stdout = stdout.readlines()
150 stderr = stderr.readlines()
151 print make_output(stdout, stderr)
152 ssh.close()
[10084]153
[10093]154def ubnt_keys(hostname):
[10094]155 keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
[10093]156 ssh = paramiko.SSHClient()
157 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
158 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
159 cmd = 'test -d .ssh || mkdir .ssh;\
[10094]160 cat > .ssh/authorized_keys && \
[10093]161 chmod 0700 .ssh && \
[10094]162 chmod 0755 . && cfgmtd -p /etc -w'
[10093]163 stdin, stdout, stderr = ssh.exec_command(cmd)
[10094]164 stdin.write(keys)
165 stdin.flush()
166 stdin.channel.shutdown_write()
[10093]167 stdout = stdout.readlines()
168 stderr = stderr.readlines()
169 print make_output(stdout, stderr)
170 ssh.close()
[10085]171
[10093]172if __name__ == '__main__':
173 # create the top-level parser
174 parser = argparse.ArgumentParser(prog='Various WL management tools')
[10098]175 parser.add_argument('--ask-pass', dest="ask_pass", action='store_true', help='Ask password if SSHPASS is not found')
[10434]176 parser.add_argument('--filter', dest="use_filter", action='store_true', help='Thread the host definition as an filter')
[10093]177 subparsers = parser.add_subparsers(help='sub-command help')
178
[10433]179 parser_snmp = subparsers.add_parser('bridge', help='UBNT Bridge Management')
180 parser_snmp.add_argument('action', type=str, choices=['keys', 'snmp', 'probe'])
[10093]181 parser_snmp.add_argument('host',type=str)
[10433]182 parser_snmp.set_defaults(func='bridge')
[10093]183
[10433]184 parser_node = subparsers.add_parser('node', help='Proxy/Node/Hybrid Management')
185 parser_node.add_argument('action', type=str, choices=['check',])
186 parser_node.add_argument('host', type=str)
187 parser_node.set_defaults(func='node')
[10086]188
[10093]189 args = parser.parse_args()
[10087]190
[10098]191 try:
192 SSHPASS = os.environ['SSHPASS']
193 except KeyError:
194 print "#WARN: SSHPASS environ variable not found"
195 if args.ask_pass:
196 SSHPASS = getpass.getpass("WL root password: ")
197
198
[10434]199 if args.use_filter:
200 hosts = []
201 for host in gformat.get_hostlist():
202 if args.host in host:
203 hosts.append(host)
204 else:
205 hosts = [args.host]
[10433]206
[10434]207
208 for host in hosts:
209 try:
210 if args.func == 'bridge':
211 if args.action == 'keys':
212 ubnt_keys(host)
213 elif args.action == 'snmp':
214 ubnt_snmp(host)
215 elif args.action == 'probe':
216 ubnt_probe(host)
217 elif args.func == 'node':
218 if args.action == 'check':
219 node_check(host)
220 except ConnectError:
221 print "#ERR: Connection failed to host %s" % host
Note: See TracBrowser for help on using the repository browser.