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
Without touching your python code:
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With