[Tutor] subprocess.Popen help

eryksun eryksun at gmail.com
Wed Jan 29 08:15:05 CET 2014


On Tue, Jan 28, 2014 at 2:52 PM, leam hall <leamhall at gmail.com> wrote:
> Python tutorial for 2.6 (using 2.4 -- don't ask), first code blurb under 17.1.1
>
> http://docs.python.org/2.6/library/subprocess.html?highlight=subprocess#subprocess.Popen
>
> How would you make an ssh to another box put data back in "p"? The
> goal is to run a shell command on a remote box and work with the
> output on the local host.

To run a single command via ssh, you may not need to script a fake tty
(as w/ pexpect). That's presuming you use the sshpass program or have
ssh-agent set up, along with keys created and copied by ssh-keygen and
ssh-copy-id.

    from subprocess import Popen, PIPE

    args = ['ssh', 'localhost', 'uname', '-o']
    kwds = dict(stdout=PIPE, stderr=PIPE)
    p = Popen(args, **kwds)

    ####

    >>> p.wait()
    0
    >>> p.stdout.read()
    'GNU/Linux\n'

To script an interactive shell more generally, you probably do want a
fake tty, such as pexpect with the pxssh module. Older versions will
work in Python 2.4. A more robust choice is Fabric, which uses the
Paramiko SSH2 library. But Fabric requires Python 2.5+.

http://pexpect.readthedocs.org
http://fabric.readthedocs.org


More information about the Tutor mailing list