Netcat implementation in Python

前端 未结 3 1425
半阙折子戏
半阙折子戏 2020-12-01 09:35

I found this and am using it as my base, but it wasn\'t working right out of the box. My goal is also to treat it as a package instead of a command line utility, so my code

相关标签:
3条回答
  • 2020-12-01 09:54

    The following is a working implementation on python3:

    import socket
    
    def netcat(host, port, content):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, int(port)))
        s.sendall(content.encode())
        s.shutdown(socket.SHUT_WR)
        while True:
            data = s.recv(4096)
            if not data:
                break
            print(repr(data))
        s.close()
    

    It can be used to send "content" to a "host" on "port" (which all might be entered as sting).

    Regards

    0 讨论(0)
  • 2020-12-01 10:00

    Does it work if you just use nc?

    I think you should try something a little simpler:

    import socket
    
    def netcat(hostname, port, content):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((hostname, port))
        s.sendall(content)
        s.shutdown(socket.SHUT_WR)
        while 1:
            data = s.recv(1024)
            if data == "":
                break
            print "Received:", repr(data)
        print "Connection closed."
        s.close()
    

    I added the shutdown call because maybe your device is waiting for you to say you're done sending data. (That would be a little weird, but it's possible.)

    0 讨论(0)
  • 2020-12-01 10:07

    if you don't mind scrapping that code altogether, you might like to look at scapy -- it's basically the swiss army knife of packet tools in python. take a look at the interactive tutorial to see if it fits your needs.

    if you'd like something higher-level than packets twisted is the go-to library for networking in python... unfortunately the learning curve is a tad steep.

    0 讨论(0)
提交回复
热议问题