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