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

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

paramiko and mca-config are no friends of each-other. It seems to look the TTY causing the UBNT to crash.

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