我正在跟一个教程来创建一个python数据包嗅探器,并且我在使用socket.py时遇到了一个错误。我对python完全陌生,还无法在线找到任何东西。这是我的代码段:
import socket
import struct
import textwrap
def main():
conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(3))
while True:
raw_data, addr = conn.recvfrom(65536) # biggest buffer size
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))
# Unpack ethernet frame
def ethernet_frame(data): # pass packets into this function
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:] #htons is endian bit compatibility
# 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) # 2 decimal places
return ':'.join(bytes_str).upper() # mac addr
main()
这是错误:
Traceback (most recent call last):
File "Untitled.py", line 26, in <module>
main()
File "Untitled.py", line 7, in main
conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(3))
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 134, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
该代码最初使用AF_PACKET而不是AF_INET,但是我读到AF_PACKET用于Windows,而AF_INET用于Linux。我实际上是在Mac上,因此不确定是否正确。我正在使用python 3.5。任何帮助或建议都将不胜感激,谢谢。
最佳答案
为了使用这种类型的 socket 。您需要使用sudo/admin权限启动脚本。
转到目录并打开终端。然后使用sudo权限运行代码:
sudo python3 file_name.py
关于python - Socket.py权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37686488/