简体   繁体   English

如何在python子进程中运行端口查找命令

[英]How to run port lookup command in python subprocess

I am using terminal command 我正在使用终端命令

while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done

in my commandline to lookup port in my remote machine.( it is working fine). 在我的命令行中到我的远程计算机中的查找端口。(它工作正常)。 I want to do this operation inside my python script. 我想在我的python脚本中执行此操作。 I found subprocess and I want to know that how can I do this with subprocess ? 我找到了子流程,我想知道如何使用子流程来做到这一点?

from subprocess import call
call(["while xxxxxxxxxxxxxxxxxxxxxxxxxxx"])

subprocess.call does not by default use a shell to run its commands. subprocess.call默认情况下不使用外壳程序来运行其命令。 Therefore, things like while are unknown commands. 因此,诸如while类的东西是未知命令。 Instead, you could pass shell=True to call ( security risk with dynamic data and user input *) or call the shell directly (the same advice applies): 相反,您可以传递shell=True进行call带有动态数据和用户输入 *的安全风险 )或直接调用Shell(适用相同的建议):

from subprocess import call
call("while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done", shell="True")

or directly with the shell, this is (a) less portable (because it assumes a specific shell) and (b) more secure (because you can specify what shell is to be used as syntax is not unified over different shells, eg csh vs. bash , and usage on other shells may lead to undefined or unwanted behaviour): 或直接与shell一起使用,这(a) 移植性较差 (因为它假定使用特定的shell),并且(b) 更安全 (因为您可以指定要使用的shell,因为语法在不同的shell上没有统一,例如csh vs bash以及在其他shell上的使用可能会导致未定义或不良的行为):

from subprocess import call
call(["bash", "-c", "while ! echo exit | nc 10.0.2.11 9445; do sleep 10; done"])

The exact argument to the shell to execute a command (here -c ) depends on your shell. Shell执行命令的确切参数(此处为-c )取决于您的Shell。

You may want to have a look at the subprocess docs , especially for other ways of invoking processes. 您可能需要看subprocess文档 ,尤其是有关调用流程的其他方式的文档 See eg check_call as a way of checking the return code for success, check_output to get the standard output of the process and Popen for advanced input/output interaction with the process. 例如参见check_call作为检验成功的返回码的方式, check_output获得进程的标准输出和Popen与工艺先进的输入/输出互动。

Alternatively, you could use os.system , which implicitly launches a shell and returns the return code ( subprocess.check_call with shell=True is a more flexible alternative to this) 或者,您可以使用os.system ,它隐式启动一个Shell并返回返回代码( subprocess.check_callshell=True是一个更灵活的选择)

* This link is to the Python 2 docs instead of the Python 3 docs used otherwise because it better outlines the security problems * 此链接指向的是Python 2文档,而不是否则使用的Python 3文档,因为它可以更好地概述安全性问题

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

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