How to run port lookup command in python subprocess
Question: 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. I found subprocess and I
want to know that how can I do this with subprocess ?

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


Answer: `subprocess.call` does not by default use a shell to run its commands.
Therefore, things like `while` are unknown commands. Instead, you could pass
`shell=True` to `call` ([**security risk** with dynamic data and user
input](https://docs.python.org/2/library/subprocess.html#frequently-used-
arguments)*) or call the shell directly (the same advice applies):

    
    
    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, e.g. `csh` vs.
`bash`, and usage on other shells may lead to undefined or unwanted
behaviour):

    
    
    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.

You may want to have a look at the [`subprocess`
docs](https://docs.python.org/dev/library/subprocess.html), especially for
other ways of invoking processes. See e.g. `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.

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)

* _This link is to the Python 2 docs instead of the Python 3 docs used otherwise because it better outlines the security problems_

