简体   繁体   中英

Python get packet data TCP

Hello I have python sniffer

def receiveData(s):
    data = ''
    try:
        data = s.recvfrom(65565)
        #k = data.rstrip()
    except timeout:
        data = ''
    except:
        print "An Error Occurred."
        sys.exc_info()
    return data[0]

 data = receiveData(s)

s is socket. Im getting data but it contains symbols please help me somebody how i can convert it into plain text

Im newbie in Python and if its very silly question sorry : )

this is data example E\\x00\\x00)\\x1a*@\\x00\\x80\\x06L\\xfd\\xc0\\xa8\\x01\\x84\\xad\\xc2#\\xb9M\\xb8\\x00P\\xed\\xb3\\x19\\xd9\\xedY\\xc1\\xfbP\\x10\\x01\\x04\\x16=\\x00\\x00\\x00'

You can't really convert it to "plain text". Characters such as the NUL (ASCII 0, shown as \\x00 ) can't be displayed so python shows them in their hex representation.

What most sniffing/hexdump tools do is to replace unprintable characters with eg a dot. You could do it like this:

import string
printable = set(string.printable)
print ''.join(x if x in printable else '.' for x in data)

Example:

>>> data = 'E\x00\x00)\x1a*@\x00\x80\x06L\xfd\xc0\xa8\x01\x84\xad\xc2#\xb9M\xb8\x00P\xed\xb3\x19\xd9\xedY\xc1\xfbP\x10\x01\x04\x16=\x00\x00\x00'
>>> print ''.join(x if x in printable else '.' for x in data)
E..).*@...L.......#.M..P.....Y..P....=...

The conversion to "plain text" depends on what your data mean.

  • Do you have compressed text? Then uncompress it.

  • Do you have encoded numbers? Then decode it and display the numbers.

Without knowing the semantic of the data, no one can tell you.

Of course, you can just display the raw data with print data.encode("hex") , but I am not sure if that is what you want.

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