简体   繁体   English

Linux。 netcat + bash

[英]Linux. netcat + bash

I have a bash script: 我有一个bash脚本:

#!/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 NC本地主机30003级#的作品,精致有型的东西按Ctrl + C

Try again nc localhost 30003 # not working 再试一次nc localhost 30003 #不起作用

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. 另外,我在python脚本中有很多已定义的函数,所以我不想从一开始就运行它。 Is it possible? 可能吗?

Thanks. 谢谢。

The problem is that nc -l -p 30003 is not run again before python3 script.py finishes. 问题是在python3 script.py完成之前nc -l -p 30003没有再次运行。 After Ctrl+C nc localhost 30003 has no listening nc to connect to. Ctrl + C nc之后,localhost 30003没有监听的nc可连接。 If you replace python3 script.py with cat the nc server will restart. 如果用cat替换python3 script.py,nc服务器将重新启动。 So the simple solution would be to have script.py exit. 因此,简单的解决方案是退出script.py。

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. 一种可能是将状态(变量等)保存为JSON的文件。 Another is to have nc write the output to a file, and have script.py read from that file. 另一个方法是让nc将输出写入文件,并从该文件读取script.py。

If you have the time, and want to learn some networking, I recommend to look at the python socket API. 如果您有时间,并且想学习一些网络知识,建议您查看python套接字API。 You can make script.py act as a server and read the data directly from the connection endpoint, rather than going through nc. 您可以使script.py充当服务器并直接从连接端点读取数据,而不是通过nc读取数据。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM