'How to read terminal output of nc utility?

I need to run a command like

nc 123.123.123.123 1111

in Bash. The service I'm connecting to will send occasional messages and expect a response in the terminal. After hitting enter, it will send another prompt and expect another response.

I want to automate this in Python, but I don't know how to read the output of the nc command. I need to continually re-read from the terminal after submitting the previous reply.

Is there an easy way to point Python at a specific terminal and say "get the contents of this"?



Solution 1:[1]

You can open nc from python in subprocess and pipe stdin, stdout and stderr.
I've put together example, which will read from nc server and consume messages. Just for demonstration I've added some primitive protocol handling. When b"OK\n" is received, our client respond with b"Got it!\n". When b"EXIT\n" is received, client close.

Please make sure to run Your nc server with -k parameter, to keep server alive after client closes connection.

nc -lk 123.123.123.123 1111

Here is full example:

import subprocess

# Open new subprocess and run nc in a shell, pipe stdin, stdout and stderr
proc = subprocess.Popen(["nc 123.123.123.123 1111"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
while True:
    response = proc.stdout.readline()
    if response == b"OK\n":
        # Write back to the process
        proc.stdin.write(b"Got it!\n")
        proc.stdin.flush()
    elif response == b"EXIT\n":
        print("Client is closing")
        break
    else:
        print(response)

# Terminate process
proc.terminate()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Domarm