windows下用python 3 写udp端口探测时,使用SOCK_RAW没有root权限怎么办?


非常简单的代码如下:


 import socket

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    host = 'www.baidu.com'
    ip = socket.gethostbyname(host)
    port = 80
    print(ip)
    address = (ip,port)

    message = 'abc'
    s.sendto(message.encode(),address)

    icmp = socket.getprotobyname("icmp")
    print(icmp)
    try:
        sock_icmp = socket.socket(socket.AF_INET,socket.SOCK_RAW,icmp)
    except:
        print(socket.error)

    recPacket,addr = sock_icmp.recvfrom(64)
    print(recPacket)


 运行时会报错:

clipboard.png

试过用管理员身份运行cmd,然后执行这个脚本,但是结果一样。
百度了很久,一直没找到解决办法。
希望会的童鞋指点一下,不胜感激。

或者你觉得我的udp端口探测这样写错了,也欢迎指出交流。

获得root python3.x udp socket

tc的皮皮虾 9 years, 4 months ago

楼主啊,你这不是没权限,而是未定义啊。能否把OSError详细信息贴下

liege answered 9 years, 4 months ago

  1. 你截图中的错误怎么和我的不一样?
    clipboard.png

  2. 你第二个 socket 建立之后,都没给人家发消息,你就 recvfrom ?
    python UDP 的使用例子你可以参考一下这个:
    http://blog.csdn.net/Sunboy_2050/article/details/5969442


 #!/usr/bin/env python
# -*- coding:utf8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import socket

class UdpClient(object):
    def tcpclient(self):
        clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        sendDataLen = clientSock.sendto("this is send data from client", ('localhost', 9527))
        recvData = clientSock.recvfrom(1024)
        print "sendDataLen: ", sendDataLen
        print "recvData: ", recvData

        clientSock.close()

if __name__ == "__main__":
    udpClient = UdpClient()
    udpClient.tcpclient()

如果是做 ping 的话,你可以参考一下这个:
https://pypi.python.org/pypi/python-ping/
源代码: https://pypi.python.org/packages/source/p/python-ping/python-ping-2011.10.17.376a019.tar.gz#md5=862755beea1af586900ccd30dacda032


帮你找了一遍比较不错的文章(可参考 UDP scan 这一部分):
http://resources.infosecinstitute.com/port-scanning-using-scapy/
里面有讲解为什么要接收 ICMP 的数据包.

  1. The client sends a UDP packet with the port number to connect to. If the server responds to the client with a UDP packet, then that particular port is open on the server.
    clipboard.png

  2. The client sends a UDP packet and the port number it wants to connect to, but the server responds with an ICMP port unreachable error type 3 and code 3, meaning that the port is closed on the server.
    clipboard.png

  3. If the server responds to the client with an ICMP error type 3 and code 1, 2, 9, 10, or 13, then that port on the server is filtered.
    clipboard.png

  4. If the server sends no response to the client’s UDP request packet for that port, it can be concluded that the port on the server is either open or filtered. No final state of the port can be decided.
    clipboard.png

基本上来讲 UDP 扫描很不准确, 因为UDP是无连接的,所以如果你发的内容对方不认同也不响应你,你也就没有办法知道这个端口是否开放.

另端口扫描的过程中肯定是会有异常的, 而你并不捕获/分析这个异常, 所以不要看到异常就认为是错误的.
比如对方没有开放这个端口或者对你提交的数据不响应,那么你 接收肯定是要出错的,但你的代码并不处理异常,所以直接抛出来了.

爱上未来的你 answered 9 years, 4 months ago

Your Answer