简体   繁体   English

在Python脚本中运行一系列外部命令

[英]Run a series of external commands in a Python script

I'm trying to run external commands (note the plural) from a Python script. 我正在尝试从Python脚本运行外部命令(请注意复数)。 I've been reading about the subprocess module and use it. 我一直在阅读有关subprocess模块的信息并使用它。 It works for me when I have a single or independent commands to run, whether I'm interested in the stdout or not. 无论我对标准输出是否感兴趣,当我有一个或多个独立的命令要运行时,它都对我有用。

What I want to do is a bit different: I want something persistent. 我想做的事情有些不同:我想要持久的东西。 Basically the first command I run is to log in an application, then I can run some other commands which only work if I'm logged in. For some of these commands, I need the stdout. 基本上,我运行的第一个命令是登录应用程序,然后我可以运行其他一些仅在登录后才能运行的命令。对于其中一些命令,我​​需要stdout。

So when I use subprocess to login, it does it, but then the process is killed and next time I run a command with subprocess , I'm not logged in anymore... I just need to run a series of commands, like I would do it in a terminal. 因此,当我使用subprocess登录时,它确实完成了,但是随后该流程被终止,下一次我使用subprocess运行命令时,我不再登录了……我只需要运行一系列命令,例如会在终端上做到这一点。

Any idea how to do that? 任何想法如何做到这一点?

You can pass in an arbitrarily complex series of commands with shell=True though I would generally advise against doing that , if not least because you are making your Python script platform dependent. 您可以使用shell=True传递任意复杂的命令序列,尽管我通常建议不要这样做 ,即使不是最不重要的是,因为您使Python脚本平台依赖。

result = subprocess.check_output('''
    servers=0
    for server in one two three four; do
        output=$(printf 'echo moo\necho bar\necho baz\n' | ssh "$server")
        case $output in *"hello"*) echo "$output";; esac
        echo "$output" | grep -q 'ALERT' && echo "$server: Intrusion detected"
        servers=$((servers++))
    done
    echo "$servers hosts checked"
    ''', shell=True)

One of the problems with shell script (or I guess Powershell or cmd batch script if you are in that highly unfortunate predicament) is that doing what you are vaguely describing is often hard to do with a bunch of unconnected processes. Shell脚本(如果您处于这种非常不幸的困境中,或者我想是Powershell或cmd批处理脚本)的问题之一是,用一堆未连接的进程通常很难做到您难以理解的描述。 Eg curl has a crude way to maintain a session between separate invocations by keeping a "cookie jar" which allows one curl to pass on login credentials etc to an otherwise independent curl call later on, but there is no good, elegant, general mechanism for this. 例如, curl有一个粗略的方法,可以通过保留一个“ cookie jar”来维持单独调用之间的会话,该cookie罐允许一个curl稍后将登录凭据等传递给其他独立的curl调用,但是没有一种好的,优雅的通用机制可以这个。 If at all possible, doing these things from within Python would probably make your script more robust as well as simpler and more coherent. 如果有可能,在Python中执行这些操作可能会使您的脚本更健壮,更简单且更一致。

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

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