I'm trying to test a small server application using python. The application is working a bit like a remote shell - it takes an input and outputs some data based on the input.
My initial try looks like this:
#!/usr/bin/python3
import subprocess
nc = subprocess.Popen(['/usr/bin/ncat','127.0.0.1','9999'], stdin =
subprocess.PIPE, stdout = subprocess.PIPE)
nc.stdin.write(b'test')
This doesn't work and tells me:
write: Broken pipe
However when i test this out in a python3 interactive intepreter everything seems to be working just fine:
$ /usr/bin/python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> nc = subprocess.Popen(['ncat','127.0.0.1','9999'], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> nc.stdin.write(b'test')
4
When I run the ncat in the shell it also waits for the input as expected.
So what is going on? How is the interactive interpreter different from running a script and why does it affect the subprocesses?
Some notes:
- I don't want to use sockets myself. The server I'm testing is run via xinetd, which means that the executable can also be tested by running it directly. With the current solution I could change
['/usr/bin/ncat','127.0.0.1','9999']
to['./server_executable']
and test everything without the networking inbetween. With sockets I'd lose this functionality. - I know about pexpect and I even consider using it. Even if I end up not using the subprocesses I'd like to know what the heck is happening here.
- When I provide the server executable to Popen everything works fine. This could hint that there is some problem with ncat and how it is run (don't know if it's relevant but I use ncat version 7.40).