python - Socket.py权限错误

标签 python macos sockets python-3.5 permission-denied

我正在跟一个教程来创建一个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/

相关文章:

python - 使用fast-ai时如何修复 'Error(s) in loading state_dict for AWD_LSTM'

c# - 开始一个不需要等待的任务

python - 通过固定大小的python数据套接字发送整数

c# - 使用P/Invoke在套接字上发送签名的char *

python - linux命令行程序可以看到python临时文件吗?

Python顺序遍历到一个平面列表

python - 将 Python 警告/错误跟踪到 numpy 和 scipy 中的行号

objective-c - 当您将窗口拖向 OSX Dock 时,可以使用什么 API 来隐藏它

xcode - cocoa 教程建议

objective-c - 如何以编程方式编辑 osx 上的/etc/hosts 文件