简体   繁体   中英

TCP port using python - how to forward command output to tcp port?

I want to develop a code in python which will open a port in the localhost and will send the logs to that port. Logs will be nothing but the command output of a python file.

like :

hello.py

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

this will continuously print the statement. I want this cont. output to be sent to opened port.

can anyone tell me how I can do the same?

Thanks in advance

Here is what i came up with.

to use with your script you do :

hello.py | thisscript.py

Hope it is was you wanted.

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()

This could be extended to specify the port with argv

external

Without touching your python code:

bash

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

netcat

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

internal

Use the socket module.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM