Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 875
sam Avatar asked Dec 03 '22 03:12

sam


2 Answers

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

like image 158
pastjean Avatar answered Dec 11 '22 10:12

pastjean


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)
like image 31
tzot Avatar answered Dec 11 '22 09:12

tzot