Linux. netcat + bash

500 views Asked by At

I have a bash script:

#!/bin/bash
while :
    do
        nc -l -p 30003 | python3 script.py 
    done

I want that listening works all time.

nc localhost 30003 # works, fine type something Ctrl+C

Try again nc localhost 30003 # not working

So, after socket closed first time, it never open again..

How can I fix it?

  • Also I have many defined function inside python script, so I donw want to run it from the beginning. Is it possible?

Thanks.

1

There are 1 answers

0
FormerNcp On BEST ANSWER

The problem is that nc -l -p 30003 is not run again before python3 script.py finishes. After Ctrl+C nc localhost 30003 has no listening nc to connect to. If you replace python3 script.py with cat the nc server will restart. So the simple solution would be to have script.py exit.

I assume that you have a state that you want to save. One possibility is to have a file with the state (variables etc.) saved as JSON. Another is to have nc write the output to a file, and have script.py read from that file.

If you have the time, and want to learn some networking, I recommend to look at the python socket API. You can make script.py act as a server and read the data directly from the connection endpoint, rather than going through nc.

Hope this helps.