Python: Open a Listening Port Behind a Router (upnp?)

后端 未结 5 884
长发绾君心
长发绾君心 2020-12-25 14:16

I\'ve developed an application that is essentially just a little ftp server with the ability to specify which directory you wish to share on startup. I\'m using ftplib for t

5条回答
  •  旧巷少年郎
    2020-12-25 14:49

    Looks like there are a few options, one being miniupnp. There are also python bindings for GNUPnP here. For windows minupnp will work, or you could go pure python with miranda-upnp.

    There is a nice example of the python GNUPnP bindings being used to open ports on a router here. In that example the lease time is set to 0, which is unlimited. See here for the definition of add_port.

    A simple example might be:

    #! /usr/bin/python
    import gupnp.igd
    import glib
    from sys import stderr
    
    my_ip = YOUR_IP
    
    igd = gupnp.igd.Simple()
    igd.external_ip = None
    
    main = glib.MainLoop()
    
    def mep(igd, proto, eip, erip, port, localip, lport, msg):
        if port == 80:
            igd.external_ip = eip
            main.quit()
    
    def emp(igd, err, proto, ep, lip, lp, msg):
        print >> stderr, "ERR"
        print >> stderr, err, proto, ep, lip, lp, msg
        main.quit()
    
    igd.connect("mapped-external-port", mep)
    igd.connect("error-mapping-port", emp)
    
    #igd.add_port("PROTO", EXTERNAL_PORT, INTERNAL_IP, INTERNAL_PORT, LEASE_DURATION_IN_SECONDS, "NAME")
    igd.add_port("TCP", 80, my_ip, 8080, 86400, "web")
    
    main.run()
    

提交回复
热议问题