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

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

Show the connected interface

  • Property svn:executable set to *
File size: 4.9 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 netsnmp
12import os
13import paramiko
14import socket
15import sys
16import time
17
18SSHPASS = None
19netsnmp.verbose = 0
20
21class CmdError(Exception):
22 pass
23
24def check_host(hostname):
25 cmd = "cat /etc/board.info"
26
27 ssh = paramiko.SSHClient()
28 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
29 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
30 stdin, stdout, stderr = ssh.exec_command(cmd)
31 stdout = stdout.readlines()
32 stderr = stderr.readlines()
33 ssh.close()
34 if stderr:
35 raise CmdError(stderr)
36
37 return dict(map(lambda x: x.strip().split('='),stdout))
38
39def get_bridge_type(host):
40 """ Both NS and NS Mx uses a slighly different OID"""
41 var_list = netsnmp.VarList(
42 *map(lambda x: netsnmp.Varbind(x),
43 ['.1.2.840.10036.3.1.2.1.3.6', '.1.2.840.10036.3.1.2.1.3.7']))
44
45 sess = netsnmp.Session(Version=1, DestHost=host, Community='public', Timeout=2 * 100000, Retries=1)
46 retval = sess.get(var_list)
47 if sess.ErrorInd < 0:
48 raise CmdError('SNMP Failed -- [%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
49 return filter(None, retval)[0]
50
51
52
53def update_hosts(filters=[]):
54 for host in gformat.get_hostlist():
55 if filters and not any([f.lower() in host.lower() for f in filters]):
56 continue
57
58 print "# Processing host", host
59 datadump = gformat.get_yaml(host)
60 for iface_key in datadump['autogen_iface_keys']:
61 ifacedump = datadump[iface_key]
62 if ifacedump.has_key('ns_ip') and ifacedump['ns_ip']:
63 addr = ifacedump['ns_ip'].split('/')[0]
64 print "## Bridge IP: %(ns_ip)s at %(interface)s" % ifacedump
65 try:
66 socket.create_connection((addr,80),2)
67 bridge_type = get_bridge_type(addr)
68 datadump[iface_key]['bridge_type'] = bridge_type
69 except (socket.timeout, socket.error) as e:
70 print "### %s (%s)" % (e, addr)
71 except paramiko.AuthenticationException:
72 print "### Conection failed (invalid username/password)"
73 except CmdError, e:
74 print "### Command error: %s" % e
75 gformat.store_yaml(datadump)
76
77
78def make_output(stdout, stderr):
79 def p(prefix, lines):
80 return ''.join(["#%s: %s" % (prefix, line) for line in lines])
81 output = p('STDOUT', stdout)
82 output += p('STDERR', stderr)
83 return output
84
85def ubnt_snmp(hostname):
86 lines = """\
87snmp.community=public
88snmp.contact=beheer@lijst.wirelessleiden.nl
89snmp.location=WL
90snmp.status=enabled\
91"""
92 cmd = 'mca-config get /tmp/get.cfg && grep -v snmp /tmp/get.cfg > /tmp/new.cfg && echo "%s" >> /tmp/new.cfg \
93 && mca-config activate /tmp/new.cfg 1>/dev/null 2>/dev/null && echo "ALL DONE"' % lines
94 ssh = paramiko.SSHClient()
95 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
96 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
97 stdin, stdout, stderr = ssh.exec_command(cmd)
98 stdout = stdout.readlines()
99 stderr = stderr.readlines()
100 print make_output(stdout, stderr)
101 ssh.close()
102
103def ubnt_keys(hostname):
104 keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
105 ssh = paramiko.SSHClient()
106 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
107 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
108 cmd = 'test -d .ssh || mkdir .ssh;\
109 cat > .ssh/authorized_keys && \
110 chmod 0700 .ssh && \
111 chmod 0755 . && cfgmtd -p /etc -w'
112 stdin, stdout, stderr = ssh.exec_command(cmd)
113 stdin.write(keys)
114 stdin.flush()
115 stdin.channel.shutdown_write()
116 stdout = stdout.readlines()
117 stderr = stderr.readlines()
118 print make_output(stdout, stderr)
119 ssh.close()
120
121if __name__ == '__main__':
122 # create the top-level parser
123 parser = argparse.ArgumentParser(prog='Various WL management tools')
124 parser.add_argument('--ask-pass', dest="ask_pass", action='store_true', help='Ask password if SSHPASS is not found')
125 subparsers = parser.add_subparsers(help='sub-command help')
126
127 parser_snmp = subparsers.add_parser('snmp', help='enable SNMP on UBNT')
128 parser_snmp.add_argument('host',type=str)
129 parser_snmp.set_defaults(func='snmp')
130
131 parser_keys = subparsers.add_parser('keys', help='add ssh keys on UBNT')
132 parser_keys.add_argument('host', type=str)
133 parser_keys.set_defaults(func='keys')
134
135 parser_update = subparsers.add_parser('update', help='process all UBNT')
136 parser_update.add_argument('filters', default=None, nargs='*', type=str)
137 parser_update.set_defaults(func='update')
138
139 args = parser.parse_args()
140
141 try:
142 SSHPASS = os.environ['SSHPASS']
143 except KeyError:
144 print "#WARN: SSHPASS environ variable not found"
145 if args.ask_pass:
146 SSHPASS = getpass.getpass("WL root password: ")
147
148
149 if args.func == 'keys':
150 ubnt_keys(args.host)
151 elif args.func == 'snmp':
152 ubnt_snmp(args.host)
153 elif args.func == 'update':
154 update_hosts(args.filters)
Note: See TracBrowser for help on using the repository browser.