netcat is not available in our Linux prod environment for security reasons. I'm trying to write/read short text messages into a port for logging. Write to port on worker nodes read on logger node. netcat would do the job Is there a way to do the same on Linux using Python?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
i made you a script, save this, chmod it and make it executable. And run it. This should work for you. Ping me if you have questions.
#!/usr/bin/python
import socket
def writer(sock):
file=open("log.txt","w") #you can specify a path for the file here, or a different file name
while(1):
try:
output=sock.recv(500)
file.write(output)
except:
file.close()
try:
x=socket.socket()
x.bind(("127.0.0.1",1339)) # Enter IP address and port according to your needs ( replace 127.0.0.1 and 1339 )
x.listen(2) # This will accept upto two connections, change the number if you like
sock,b=x.accept()
writer(sock)
except:
print("bye")
exit()
回答2:
Thank you for replies. I ended up writing my own scripts.
- I start netcat_reader.py on logger node.
- I start 2 netcat_writer.py shells on the same or different worker nodes:
python netcat_writer.py writer1& python netcat_writer.py writer2&
- Result is combined log of messages from 2 reporting scripts (netcat_writer.py) accumulated on logging server:
Receiving... timed out 1 timed out 2 timed out 1 timed out 2 timed out 1 timed out 2 timed out 1 Got connection from ('10.20.102.39', 17992) Got connection from ('10.20.102.39', 17994) client:one --0-- client:two --0-- client:one --1-- client:one --2-- client:one --3-- client:one --4-- client:one --5-- client:two --1-- client:one --6-- client:two --2-- client:one --7-- client:two --3-- client:one --8-- client:two --4-- client:one --9-- client:two --5-- client:two --6-- client:two --7-- client:two --8-- client:two --9--
netcat_reader.py (run it in loggerhost123):
import socket
import sys
e=sys.exit
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False)
s.settimeout(2)
#
host = socket.gethostname()
port = 12346
s.bind((host, port))
s.listen(5)
c1=c2=t1=t2=None
print "Receiving..."
while True:
try:
if not c1:
c1, addr1 = s.accept()
print 'Got connection from', addr1
if t1:
print t1.decode('utf-8')
if c1:
t1 = c1.recv(1024)
except socket.error, er:
err = er.args[0]
print err ,1
try:
if not c2:
c2, addr2 = s.accept()
print 'Got connection from', addr2
if t2:
print t2.decode('utf-8')
if c2:
t2 = c2.recv(1024)
except socket.error, er:
err = er.args[0]
print err,2
c1.close()
c2.close()
s.shutdown(socket.SHUT_WR)
s.close()
print "Done Receiving"
e(0)
netcat_writer.py (run it on reporting nodes)
import socket
import sys, time
e=sys.exit
assert len(sys.argv)==2, 'Client name is not set'
client_name= sys.argv[1]
class NetcatWriter:
def __init__(self, port,client_name):
print '__init__'
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = 'loggerhost123'
self.port = port
self.client_name=client_name
self.s.connect((self.host, self.port))
def __enter__(self):
print '__enter__'
return self
def write(self,i):
print 'Sending..',
l = 'client:%s --%d--' % (self.client_name,i)
while (l):
print '.',
self.s.send(l)
l=None
#f.close()
print "Done Sending"
#
def __exit__(self, exc_type, exc_value, traceback):
self.s.shutdown(socket.SHUT_WR)
self.s.close
netcat= NetcatWriter(12346,client_name)
if 1:
for i in range(10):
netcat.write(i)
time.sleep(0.1)
e(0)
回答3:
I use this at work for some situations where i need to get a message from a network node. hopefully it will help you. you will need to adapt this to your needs. i wont do all the work for you but I will give you the right direction.
!#/usr/bin/env python
import socket
def netcat_alternative(ip, port):
req = socket.create_connection((ip, port)).recv(1024)
print(req) #alternatively you can log this value
req.close()
# main goes here
def main():
"""
main logic flow
"""
string_ip = '127.0.0.1'
int_port = 80
netcat_alternative(string_ip, int_port)
if __name__ == "__main__":
main()