【问题标题】:TCP port using python - how to forward command output to tcp port?使用 python 的 TCP 端口 - 如何将命令输出转发到 tcp 端口?
【发布时间】:2011-05-19 13:36:03
【问题描述】:

我想在 python 中开发一个代码,它将在 localhost 中打开一个端口并将日志发送到该端口。日志只是 python 文件的命令输出。

喜欢:

hello.py

i = 0  
while True:  
    print "hello printed %s times." % i  
    i+=1

这将连续打印语句。 我想要这个续集。输出要发送到打开的端口。

谁能告诉我怎么做?

提前致谢

【问题讨论】:

  • 什么协议? HTTP? FTP? .. 港口的另一边是什么?我的意思是服务器。
  • @pyfunc - 没有协议,我在我的本地主机上使用。
  • @pastjean :是的,我会喜欢的。谢谢

标签: python command-line tcp send


【解决方案1】:

这是我想出的。

与您的脚本一起使用:

hello.py | thisscript.py

希望这是你想要的。

import socket
import sys

TCP_IP = '127.0.0.1'
TCP_PORT = 5005

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
  line = sys.stdin.readline()
  if line:
    s.send(line)
  else:
    break

s.close()

这可以扩展为使用 argv 指定端口

【讨论】:

    【解决方案2】:

    外部

    无需接触您的 python 代码:

    重击

    hello.py >/dev/tcp/$host/$port # if tcp
    hello.py >/dev/udp/$host/$port # if udp
    

    网猫

    hello.py | nc $host $port      # if tcp
    hello.py | nc -u $host $port   # if udp
    

    内部

    使用套接字模块。

    import socket
    
    sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM) # if tcp
    sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # if udp
    
    # if it's TCP, connect and use a file-like object
    sock.connect( (host, port) )
    fobj= sock.makefile("w")
    # use fobj and its write methods, or set sys.stderr or sys.stdout to it
    
    # if it's UDP, make a dummy class
    class FileLike(object):
        def __init__(self, asocket, host, port):
            self.address= host, port
            self.socket= asocket
        def write(self, data):
            self.socket.sendto(data, self.address)
    fobj= FileLike(sock, host, port)
    

    【讨论】:

    • 您可以通过添加 print >>fobj, "hello printed %s times." % iprint("hello printed {} times.".format(i), file=fobj),分隔 tcp、udp 代码并为 hostport 指定具体值来使您的示例可复制粘贴,提供示例服务器 (@ 987654328@).
    猜你喜欢
    • 2015-04-15
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2013-11-07
    相关资源
    最近更新 更多