利用Python抓取网络流量并识别出网络中是否存在下载可执行文件的行为

  测试网站(需要是非加密的http网站):http://startrinity.com/InternetQuality/ContinuousBandwidthTester.aspx

  

from email.policy import HTTP
from scapy.all import *
from scapy.layers import http
import sys
import optparse
import termcolor

class HTTPDownloadDetect:
    def __init__(self) -> None:
        self.interface = self.get_params()
        self.executable_list = ['.exe', '.zip', '.rar']

    def get_params(self):
        parser = optparse.OptionParser('Usage: <Program> -i interface')
        parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to listen')
        options, args = parser.parse_args()
        if options.interface is None:
            print(parser.usage)
            sys.exit(0)
        return options.interface
    
    def packet_handler(self,pkt):
        if pkt.haslayer(http.HTTPRequest):   
            pkt_request = pkt.getlayer(http.HTTPRequest)     
            
            if pkt_request.Method.decode("utf-8") =='GET':
                src_ip = pkt.getlayer(IP).src
                dst_ip = pkt.getlayer(IP).dst
                host = pkt_request.Host.decode("utf-8") 
                path = pkt_request.Path.decode("utf-8")
                url = host + path
                for ext in self.executable_list:
                    if ext in path:
                        print(url)
                        print("Detected client %s downloading from %s: %s" % (src_ip, dst_ip, termcolor.colored(path, 'blue')))           
                
              

    def run(self):
        try:
            sniff(iface=self.interface, prn=self.packet_handler, store=False)
        except KeyboardInterrupt:
            print("Exit program now!")
            sys.exit(0)

if __name__ == '__main__':
    httpobj = HTTPDownloadDetect()
    httpobj.run()

 

posted @ 2022-05-23 17:44  Jason_huawen  阅读(228)  评论(0编辑  收藏  举报