Juniper log analysis – get host names from ip addresses.

import os
import re
from pprint import pprint
import socket
import M2Crypto
import ssl

ipsourcetable={}
iptargettable={}
ipsourcetargetcounttable={}
myfilename="192.168_logs_2017_05/192.168.96.43_log.txt"
myfilename="examine.log"
print myfilename
myipnames={'': ''}
for line in open(myfilename).readlines():
        parts=line.split(",")
        mytarget=parts[3]
        mytargetname=myipnames.get(mytarget,'notfound')
        mytargetcert='"",""'
        if mytargetname == 'notfound':
                print 'looking up ' + mytarget
                try:
                        mytargetname=socket.gethostbyaddr(mytarget)[0]
                        pprint(mytargetname)
                except socket.error, msg:
                        mytargetname=""
                # either found it or not - dont look again
                myipnames[mytarget]=mytargetname + "," + mytargetcert
                try:
                        cert = ssl.get_server_certificate((mytarget, 443))
                        x509 = M2Crypto.X509.load_cert_string(cert.encode('ascii','ignore'))
                        print x509.get_issuer()
                        print x509.get_subject()
                        mytargetcert='"'+ str(x509.get_issuer()) +'","'+ str(x509.get_subject()) + '"'
                        myipnames[mytarget]=mytargetname + "," + mytargetcert
                        mytargetname = myipnames[mytarget]
                except:
                        print 'couldnt get it'
                        #raise
                print 'added ' +'mytarget' + mytargetname
        else:
                print 'found ' + mytarget + ' ' + mytargetname
        #
        # make a line with comma seperators and quoted text
        mynewline=parts[0]+","+  parts[1]+ ","+ parts[2]+","+ mytargetname + ',' + parts[3]+","+  parts[5]+","+  parts[6]
        #pprint(mynewline)
        with open('withnames/'+parts[2]+'_with_name_log.txt', 'a') as the_file:
                the_file.write(mynewline)

myfile=open('myipaddresses.txt','w')
for f in myipnames.items():
        myfile.write( f[0] + ',' + f[1] + '\n' )
myfile.close()

About Jeff Turner

Technical director of Nano Tera Network Solutions.
This entry was posted in Uncategorized. Bookmark the permalink.