Python 3.4: Unknown format code #39;x#39;(Python 3.4:未知格式代码“x)
问题描述
我对 Python3 中的数据包嗅探器有疑问.
I have issue about packet sniffer in Python3.
python 版本:3.4
version of python: 3.4
我遵循了一些有效的教程,但不是在我的计算机上.此代码必须获取 mac 地址,将其转换为字符串,并且在 main() 方法中应该向我打印目标 mac、源 mac 和协议.
I followed some tutorial that works, but not on my computer. This code has to get mac address, convert it to string and in main() method should print to me destination mac, source mac and protocol.
代码:sniffer_demo.py
code: sniffer_demo.py
import socket
import struct
import textwrap
def main():
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
raw_data, addr = conn.recvfrom(65536)
# one's and zero's put to the method ehternet_frame
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
print('
Ethernet Frame:')
print('Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))
# Unpack ethernet frame
def ethernet_frame(data):
dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:]
# Return properly formatted MAC address: (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(bytes_addr):
bytes_str = map('{:02x}'.format, bytes_addr)
return ':'.join(bytes_str).upper()
main()
错误是:
Traceback (most recent call last):
File "sniffer_demo.py", line 28, in <module>
main()
File "sniffer_demo.py", line 11, in main
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
File "sniffer_demo.py", line 19, in ethernet_frame
return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:]
File "sniffer_demo.py", line 24, in get_mac_addr
bytes_str = map('{:02x}'.format, bytes_addr)
ValueError: Unknown format code 'x' for object of type 'str'
如何解决?
推荐答案
在尝试重现时,您的代码似乎完全按预期工作.我没有看到任何shebang-line.你确定你正在使用 python3
执行吗?
While trying to reproduce, your code seems to work exactly as expected. I do not see any shebang-line. Are you sure you are executing using python3
?
#python3.4 snif2.py
的示例输出:
Ethernet Frame:
Destination: A4:17:31:xx:xx:xx, Source: 00:0C:F6:xx:xx:xx, Protocol: 8
Ethernet Frame:
Destination: 00:0C:F6:xx:xx:xx, Source: A4:17:31:xx:xx:xx, Protocol: 8
^CTraceback (most recent call last):
File "snif2.py", line 27, in <module>
main()
File "snif2.py", line 9, in main
raw_data, addr = conn.recvfrom(65536)
KeyboardInterrupt
这篇关于Python 3.4:未知格式代码“x"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 3.4:未知格式代码“x"


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01