SH1NU11b1

pythonnetworktraffic

Jul 20th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.74 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2. import urllib2
  3. import re
  4. import time
  5. from selenium import webdriver
  6. from selenium.webdriver.common.keys import Keys
  7. from selenium.webdriver.support.ui import WebDriverWait
  8. from selenium.webdriver.common.by import By
  9. from selenium.webdriver.support import expected_conditions as EC
  10. from time import gmtime, strftime
  11. from datetime import datetime
  12.  
  13.  
  14. # Function that retrieves the table with all traffic data from the admin interface (refreshes periodically automatically) and then checks each entry against the threshold.
  15. def checkNetworkIndividual():
  16.     tableContent = driver.find_element_by_id("bwm-details-grid")
  17.     soup = BeautifulSoup(tableContent.get_attribute('innerHTML'))
  18.     count = 0
  19.  
  20.     for data in soup.find_all("tr"):
  21.         if("traffictable_footer" in str(data)):
  22.             break
  23.         prettyData = data.prettify()
  24.         total = prettyData.splitlines()
  25.        
  26.         for entry in total:
  27.             if("MB" in entry ):
  28.                 count = count + 1
  29.                 #print(count)
  30.                 number = float(entry.strip('MB '))
  31.                 if(number > 0.50):
  32.                     checkViolation(total[3], total[6])
  33.     return
  34.                
  35. # If someone is downloading too much, give them a strike, if they get 5 strikes, set of the alarm.
  36. # Strikes are reset after a timeout.               
  37. def checkViolation(name, ip):
  38.     global last_ip
  39.     global violations
  40.     global alarm_active
  41.     global timestamp
  42.     difference = datetime.now() - timestamp
  43.     timestamp = datetime.now()
  44.    
  45.     if(ip == last_ip and difference.total_seconds() < 20.0):
  46.         violations = violations + 1
  47.     else:
  48.         last_ip = ip
  49.         violations = 1
  50.    
  51.     if(violations > 4 and alarm_active == False):
  52.         alarm_active = True
  53.         alert(name, ip)
  54.         time.sleep(14)
  55.         violations = 0
  56.         alarm_active = False
  57.  
  58.     return
  59.        
  60. # Update the screen with the name and IP of the violator (terrible)
  61. # The html page is hosted with apache in this case, so it can be accesed from a different machine
  62. # And call a shell script that handles the lights and sound.
  63. # Lights are controlled with a RF receiver using http://wiringpi.com/ and this example code https://www.dropbox.com/s/uc1d4igaeviys4a/lights.zip?dl=1
  64. # Tutorial I used in Ducth: https://weejewel.tweakblogs.net/blog/8665/lampen-schakelen-met-een-raspberry-pi.html
  65. def alert(name, ip):
  66.         f = open('/var/www/html/index.html','w')
  67.  
  68.         message = """<html>
  69.        <meta http-equiv="refresh" content="25; URL=http://192.168.1.123">
  70.         <head>
  71.         <link rel="stylesheet" type="text/css" href="mystyle.css">
  72.         </head>
  73.         <body style="background: red; margin-top: 150px;">
  74.         <style>
  75.         h1 {
  76.         font-size: 150px;
  77.         text-align: center;
  78.         }
  79.         h2 {
  80.         font-size: 120px;
  81.         text-align: center;
  82.         }
  83.         h1, h2 {
  84.       animation: blink-animation 1s steps(5, start) infinite;
  85.       -webkit-animation: blink-animation 1s steps(5, start) infinite;
  86.         }
  87.         @keyframes blink-animation {
  88.       to {
  89.         color: white;
  90.       }
  91.         }
  92.         @-webkit-keyframes blink-animation {
  93.       to {
  94.         color: white;
  95.       }
  96.     }
  97.     </style>
  98.         <h1>""" + name + """</h1>
  99.         <h2>""" + ip + """</h2>
  100.         </body>
  101.         </html>"""
  102.        f.write(message)
  103.        f.close()
  104.        import subprocess
  105.        subprocess.Popen("./alarm.sh", shell=True)
  106.        time.sleep(10)
  107.        defaultHTML()
  108.  
  109.        return
  110.  
  111. # Reset the screen to the default black state.
  112. def defaultHTML():
  113.    f = open('/var/www/html/index.html','w')
  114.  
  115.    message = """<html>
  116.     <meta http-equiv="refresh" content="5; URL=http://192.168.1.123">
  117.     <head></head>
  118.     <body style="background: black;">
  119.     <h1>Stand by</h1>
  120.     </body>
  121.     </html>"""
  122.    f.write(message)
  123.    f.close()
  124.    return
  125.  
  126. # Location of the router admin interface
  127. host = '192.168.1.1'
  128. trafic_url = 'http://' + host + '/Main_TrafficMonitor_devrealtime.asp'
  129.  
  130. # Use selenium to log into the admin control panel of the router
  131. driver = webdriver.Firefox()
  132. driver.get(trafic_url)
  133. username = driver.find_element_by_name("login_username")
  134. password = driver.find_element_by_name("login_passwd")
  135.  
  136. username.send_keys("Username")
  137. password.send_keys("SomePassword")
  138.  
  139. driver.find_element_by_class_name("button").click()
  140. wait = WebDriverWait(driver, 20)
  141. element = wait.until(EC.presence_of_element_located((By.ID, 'bwm-details-grid')))
  142.  
  143.  
  144. defaultHTML()
  145. violations = 0
  146. alarm_active = False
  147. last_ip = ""
  148. timestamp = datetime.now()
  149.  
  150. # Call the traffic check function each second for al eternity
  151. while (True):
  152.        checkNetworkIndividual()
  153.        time.sleep(1)
Add Comment
Please, Sign In to add comment