· 7 years ago · Sep 14, 2018, 12:14 AM
1#!/usr/bin/python
2# Written by employee_name@company.com on 2012-05-02
3# Written to target Python 2.4
4
5import StringIO
6import sqlite
7import sys
8from optparse import OptionParser
9from utils import shell
10
11parser=OptionParser()
12parser.add_option("-f","--file",dest="filename",help="source file for list of hosts", metavar="FILE")
13parser.add_option("-d","--database","--db",dest="database",help="destination database for audit results", metavar="DATABASE")
14parser.add_option("-q","--quiet",action="store_false", dest="verbose", default=True,help="suppress stdout messages")
15
16(options, args) = parser.parse_args()
17
18con = None
19
20try:
21 if options.database:
22 con = sqlite.connect(options.database) ; cur = con.cursor()
23 cur.execute('SELECT SQLITE_VERSION()') ; data = cur.fetchone()
24 print "SQLite Version: %s" % (data)
25
26except sqlite.Error, e:
27 print "Error %s:" % e.args[0] ; sys.exit(1)
28
29hosts = dict( (x,{}) for x in shell('cat FILE'.replace('FILE',options.filename)).run() )
30
31mem = StringIO.StringIO()
32print >>mem, '#!/bin/sh'
33print >>mem, '(getent passwd | awk -F: \'{print $6}\' | grep -v \'^/$\' ;'
34print >>mem, 'find /home -maxdepth 1 -mindepth 1 -type d) | while read dir; do'
35print >>mem, ' fullstring="$dir"'
36print >>mem, ' fullstring=`cat $dir/.ssh/authorized_keys 2>/dev/null | awk \'{print $2}\' | (while read pubkey ; do '
37print >>mem, ' fullstring="$fullstring:::$pubkey"'
38print >>mem, ' done'
39print >>mem, ' echo $fullstring)`'
40print >>mem, ' echo $fullstring'
41print >>mem, 'done'
42command = mem.getvalue()
43remote = 'ssh -o ConnectTimeout=1 -q XXX "sh -"'
44
45cur.execute("""
46 DROP TABLE IF EXISTS Audit;
47 CREATE TABLE Audit(Id INTEGER PRIMARY KEY AUTOINCREMENT, Host TEXT, Directory TEXT, Pubkey TEXT);
48 """)
49con.commit()
50
51pubkey_list=[]
52
53for host in hosts.keys():
54 if options.verbose: print "Acquiring data from %s" % (host)
55 hosts[host] = dict( (delimited[0],delimited[1:]) for delimited in [ x.split(':::') for x in shell(command,remote.replace('XXX',host)).passthrough() ] )
56 if options.verbose and hosts[host] == {}: print "ERROR: host %s not accessible" % (host)
57 for dir in hosts[host].keys():
58 for pubkey in hosts[host][dir]:
59 triplet = "%s, %s, %s" % (host,dir,pubkey)
60 cur.execute("INSERT INTO Audit (Host,Directory,Pubkey) VALUES (TUPLE)".replace('TUPLE',triplet))
61
62 con.commit()