Python端口转发/多路复用服务器 [英] Python port forwarding/multiplexing server
问题描述
我想让服务器侦听UDP端口162(SNMP陷阱),然后将此流量转发给多个客户端.同样重要的是源端口&地址保持不变(地址欺骗).
I would like to make server that listen on UDP port 162 (SNMP trap) and then forwards this traffic to multiple clients. Also important is that the source port & address stays same (address spoofing).
我猜想,最好的工具是 Twisted 或 Scapy 或香草插座, 只有Twisted的文档中找不到关于源地址欺骗/伪造的任何内容.
I guess that best tool for this would be Twisted or Scapy or maybe vanilla sockets, only I can't find anything in the documentation for Twisted about source address spoofing/forging.
有什么解决办法吗?
增加了赏金,我可以用iptables解决方案吗?
added bounty, mybe any solution with iptables?
推荐答案
我对扭曲或船骨不满意,但是使用香草python插座非常简单.这样做的另一个优点是它将更加便携.这段代码可以在我的有限测试中使用:
I am not comfortable with twisted or scapy, but it's quite straightforward to do this with vanilla python sockets. An extra advantage of that is that it will be even more portable. This code works in my limited tests:
#!/usr/bin/python
from socket import *
bufsize = 1024 # Modify to suit your needs
targetHost = "somehost.yourdomain.com"
listenPort = 1123
def forward(data, port):
print "Forwarding: '%s' from port %s" % (data, port)
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(("localhost", port)) # Bind to the port data came in on
sock.sendto(data, (targetHost, listenPort))
def listen(host, port):
listenSocket = socket(AF_INET, SOCK_DGRAM)
listenSocket.bind((host, port))
while True:
data, addr = listenSocket.recvfrom(bufsize)
forward(data, addr[1]) # data and port
listen("localhost", listenPort)
这篇关于Python端口转发/多路复用服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!