Linux上是否有使用Python的netcat替代方案?



由于安全原因,netcat在我们的Linux prod环境中不可用。我试图写/读短文本消息到一个端口记录。写入工作节点上的端口,读取日志节点上的端口。Netcat会做这项工作有没有一种方法可以在Linux上使用Python做同样的事情?

我制作了一个脚本,保存它,chmod它并使其可执行。然后运行它。这应该对你有用。如果有什么问题,请给我打电话。

#!/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()

感谢您的回复。最后我自己写剧本。

    我在日志节点上启动netcat_reader.py。
  1. 我在相同或不同的工作节点上启动两个netcat_writer.py shell:
python netcat_writer.py writer1& 
python netcat_writer.py writer2&
  • 结果是两个报告脚本(netcat_writer.py)在日志服务器上积累的消息的组合日志:
  • 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(在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(在报告节点上运行)

    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)
    

    我在一些需要从网络节点获取消息的情况下使用这个。希望能对你有所帮助。您需要根据自己的需要对其进行调整。我不会为你做所有的工作,但我会给你正确的方向。

    !#/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()
    

    最新更新