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

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

Echo does not work, cat with closing stdin works fine.

  • Property svn:executable set to *
File size: 4.6 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 netsnmp
11import os
12import paramiko
13import socket
14import sys
15import time
16
17try:
18 SSHPASS = os.environ['SSHPASS']
19except KeyError:
20 SSHPASS = 'SSH_NOT_SET'
21
22netsnmp.verbose = 0
23
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())
32 ssh.connect(hostname, username='root', password=SSHPASS,timeout=3)
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
42def get_bridge_type(host):
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']))
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:
51 raise CmdError('[%(ErrorInd)s] %(ErrorStr)s (%(DestHost)s)' % vars(sess))
52 return filter(None, retval)[0]
53
54
55
56def update_hosts(filters=[]):
57 for host in gformat.get_hostlist():
58 if filters and not any([f.lower() in host.lower() for f in filters]):
59 continue
60
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]
65 if ifacedump.has_key('ns_ip') and ifacedump['ns_ip']:
66 addr = ifacedump['ns_ip'].split('/')[0]
67 print "## Bridge IP: %s" % addr
68 try:
69 socket.create_connection((addr,80),2)
70 bridge_type = get_bridge_type(addr)
71 datadump[iface_key]['bridge_type'] = bridge_type
72 except (socket.timeout, socket.error) as e:
73 print "### %s (%s)" % (e, addr)
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
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
87
88def ubnt_snmp(hostname):
89 lines = """\
90snmp.community=public
91snmp.contact=beheer@lijst.wirelessleiden.nl
92snmp.location=WL
93snmp.status=enabled\
94"""
95 cmd = '(mca-config get /tmp/get.cfg | grep -v snmp /tmp/get.cfg; echo "%s") >/tmp/new.cfg \
96 && mca-config activate /tmp/new.cfg' % lines
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()
105
106def ubnt_keys(hostname):
107 keys = open(os.path.join(gformat.NODE_DIR,'global_keys'),'r').read()
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;\
112 cat > .ssh/authorized_keys && \
113 chmod 0700 .ssh && \
114 chmod 0755 . && cfgmtd -p /etc -w'
115 stdin, stdout, stderr = ssh.exec_command(cmd)
116 stdin.write(keys)
117 stdin.flush()
118 stdin.channel.shutdown_write()
119 stdout = stdout.readlines()
120 stderr = stderr.readlines()
121 print make_output(stdout, stderr)
122 ssh.close()
123
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)
136 parser_keys.set_defaults(func='keys')
137
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()
143
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.