gpt4 book ai didi

python - 如何将Linux命令转换为Python脚本?

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:43 25 4
gpt4 key购买 nike

我想从 Python scrypt 运行这 2 个 Linux 命令(netcat 和 cat)。当我在终端上运行2个Linux命令时,我得到了file.txt的内容运行Python脚本时没有任何输出。

这是我的 Python 代码。我认为 subprocess.Popen 不允许我访问服务器。

cmd1 = 'nc ' + '12.123.123.123' + ' 20'

cmd2 = 'cat file.txt'

process1 = subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

process2 = subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = process2.communicate()

print str(out)

最佳答案

由于命令 cmd1 需要 CTRL-C 来终止它,因此 process1 根本不返回。因此,我们需要向子进程发送 CTRL-C。您应该尝试以下两种方法之一:

import subprocess
import os
import signal
import time

cmd1 = 'nc 127.0.0.1 20'

process1 = subprocess.Popen(cmd1.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) # No Shell......................
time.sleep(2)
process1.kill()
out, err = process1.communicate()
print out, err

或者类似下面的内容:

import subprocess
import os
import signal
import time

cmd1 = 'exec nc 127.0.0.1 20' #NOTICE the exec here

process1 = subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # No Shell......................
time.sleep(2)
print process1.pid
os.kill(process1.pid, signal.SIGKILL)
out, err = process1.communicate()
print out, err

关于python - 如何将Linux命令转换为Python脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com