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

时间:2016-10-28 16:00:49

标签: python linux netcat

出于安全原因,我们的Linux prod环境中没有netcat。 我试图将短文写入/读入端口进行记录。 写入记录器节点上读取的工作节点上的端口。 netcat会做这个工作 有没有办法在Linux上使用Python做同样的事情?

3 个答案:

答案 0 :(得分:3)

我为你制作了一个脚本,保存它,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()

答案 1 :(得分:3)

感谢您的回复。 我最终编写了自己的脚本。

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

答案 2 :(得分:2)

我在工作中使用它来处理需要从网络节点获取消息的某些情况。希望它会对你有所帮助。你需要根据自己的需要进行调整。我不会为你做所有的工作,但我会给你正确的方向。

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