4

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

3
  • What protocol? HTTP? FTP? .. Whats on the other side of port? I mean server. Commented Dec 3, 2010 at 5:23
  • @pyfunc - no protocol, i am using on my localhost itself. Commented Dec 3, 2010 at 6:26
  • @pastjean : yes i will lokk into the same. thanks Commented Dec 3, 2010 at 6:26

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

Comments

4

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) 

1 Comment

you could make your example copy-pasteable by adding print >>fobj, "hello printed %s times." % i or print("hello printed {} times.".format(i), file=fobj), separating tcp,udp code and specifying concrete values for host, port, providing an example server (nc -l).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.