Advertisement
Guest User

packetSniffer.py

a guest
Jan 18th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.52 KB | None | 0 0
  1. import socket, sys
  2. from scapy.all import *
  3. from struct import *
  4. import subprocess as sub
  5. import time
  6. import re
  7. import sqlite3 as sql
  8. import os
  9.  
  10. #Defines refresh rate of the IP addresses to be monitored
  11. refresh_rate = 10
  12. interface_name = 'br-lan'
  13.  
  14. #establishes connection to a database creating it if it doesn't exist
  15. conn = sql.connect('/tmp/tempHistory.db')
  16. cur = conn.cursor()
  17. tableName = 'connectionHistory'
  18. global macList
  19.  
  20.  
  21. def getTime():
  22.     #Function that gets the system time in seconds
  23.     return int(round(time.time()))
  24. def setTime():
  25.     global clock
  26.     clock = getTime()
  27.  
  28. def getMACs ():
  29.     #Function that gets the IP addresses from the configuration file
  30.  
  31.     #First accesses config file for monitored IPsf
  32.     ipConfigFile = open('/etc/config/cbi_file', 'r')
  33.  
  34.     #Scans through file looking for DeviceIP objects and trims the string accordinglu to get the IP address
  35.     List = []
  36.     for line in ipConfigFile:
  37.         if "option mac" in line:
  38.             value = line[13:(len(line)-2)]
  39.             List.append(value)
  40.     #print List
  41.     return List
  42.  
  43. def checkTables ():
  44.     #Function to check if table exists to hold data
  45.     cur.execute("CREATE TABLE IF NOT EXISTS connectionHistory (monitorMAC text, toIP text, connection text, port integer, length integer, PRIMARY KEY (monitorMAC, toIP, connection, port))")
  46.     #print 'Created master table'
  47.     cur.execute("CREATE TABLE IF NOT EXISTS dnsLookups (toIP text PRIMARY KEY, hostname text)")
  48.  
  49. def enterDNS (ipAddr):
  50.  
  51.     #if ip address does not already exist in table do following
  52.     nslookupProc = sub.Popen(('nslookup', ipAddr), stdout=sub.PIPE)
  53.     results = nslookupProc.communicate()[0]
  54.     #regular expression to pull hostname
  55.     dnsRecord = re.findall( r'([^\s]+\.[a-z]+)', results)
  56.     if dnsRecord != []:
  57.         entry = dnsRecord[0]
  58.         #print entry
  59.         cur.execute("INSERT OR IGNORE INTO dnsLookups VALUES (?,?)", (ipAddr, entry))
  60.     else:
  61.         cur.execute("INSERT OR IGNORE INTO dnsLookups VALUES (?,?)", (ipAddr, ""))
  62.  
  63. def tablePush (items):
  64.  
  65.     #Tries to update values in table
  66.     cur.execute("UPDATE connectionHistory SET length = length + ? WHERE monitorMAC = ? AND toIP = ? AND port = ? AND connection = ?", (items[3], items[0], items[1], items[2], items[4]))
  67.     cur.execute("INSERT OR IGNORE INTO connectionHistory VALUES (?,?,?,?,?)", (items[0], items[1], items[4], items[2], items[3]))
  68.     #print 'added value'
  69.     enterDNS(items[1])
  70.  
  71. #first generate macs from config file using method
  72.  
  73. macList = getMACs()
  74.  
  75. #generate our IPs to monitor and call checkTables to ensure our SQL table exists
  76. checkTables()
  77.  
  78. #begin running the tcpdump subprocess piping output to stdout
  79.  
  80. #capture start time of the process and save to clock variable
  81. setTime()
  82.  
  83.  
  84. def printer(packet):
  85.     src = packet[0][0].src
  86.     dst = packet[0][0].dst
  87.     global clock
  88.     global macList
  89.  
  90.     if src in macList:
  91.         listVals = [packet[0][0].src, packet[0][1].dst, packet[0][1].dport, packet[0][1].len, 'out']
  92.         tablePush(listVals)
  93.     elif dst in macList:
  94.         listVals = [packet[0][0].dst ,packet[0][1].src, packet[0][1].sport, packet[0][1].len, 'in']
  95.         tablePush(listVals)
  96.    
  97.     if getTime() - refresh_rate > clock:
  98.            #update monitored IPs and update clock
  99.             macList = getMACs()
  100.             clock = getTime()
  101.             #print 'updatedIPs'
  102.             #commit changes to database
  103.             conn.commit()
  104.  
  105. #create an INET, STREAMing socket
  106. sniff(filter="tcp or udp", prn=printer, store=0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement