1

I'm trying to run external commands (note the plural) from a Python script. I've been reading about the subprocess module and use it. 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.

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.

Any idea how to do that?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Nicolas
  • 95
  • 1
  • 6

1 Answers1

0

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.

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. E.g. 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. If at all possible, doing these things from within Python would probably make your script more robust as well as simpler and more coherent.

tripleee
  • 175,061
  • 34
  • 275
  • 318