A little help with pexpect

Piet van Oostrum piet at cs.uu.nl
Sun Jul 19 10:49:09 EDT 2009


>>>>> Hussein B <hubaghdadi at gmail.com> (HB) wrote:

>HB> Hey,
>HB> I'm trying to execute a command over a remore server using pexpect
>HB> +++++++++++++++++
>HB> url = 'ssh internalserver'
>HB> res = pexpect.spawn(url)
>HB> print '1'
>HB> res.expect('.*ssword:')
>HB> print '2'
>HB> res.sendline('mypasswd')
>HB> print '3'
>HB> res.sendline('ls -aslh')
>HB> +++++++++++++++++
>HB> What I want to do is to send a couple of commands and get the
>HB> response.
>HB> How to do this?
>HB> Thanks.

You can read the output with res.readline() in a loop or similar. The
problem is when to stop. You could look in the returned string for the
prompt and hope the prompt doesn't accidentally occur in the output.

You can also do res.expect(prompt) and get res.before() Same problem
with accidentally occurrence of the prompt.

Another way is to use a timeout, e.g. with read_nonblocking or
specifying a timeout at the spawn call.

You can also consider using paramiko instead of pexpect. It gives you
considerably more control. For each command you van open a `channel' and
that acts more or less similar to a socket, i.e. you get a decent EOF at
the end of the command's output. This implies that you have to create a
new channel for each command, but it stays within the same SSH
connection (SSH allows subconnections).

Example:

>>> import paramiko
...Mumbles about deprecated modules...
>>> hostname='server.example.net'
>>> port = 22
>>> t = paramiko.Transport((hostname, port))
>>> username = 'user'
>>> password = '********'
>>> t.connect(username=username, password=password)

Open a channel for a command

>>> chan = t.open_session()
>>> chan.exec_command('ls -l')
>>> chan.recv(999999)
'total 0\ndrwxr-xr-x  2 user group 60 Apr  2  2009 Mail\ndrwx------  2 user group  6 Dec 27  2008 tmp\n'
>>> chan.recv(999999)
''

That was end of file.
Open a new channel for a new command

>>> chan = t.open_session()
>>> chan.exec_command('cat')
>>> chan.send('abcdefghijklmn\n')
15
>>> chan.recv(99)
'abcdefghijklmn\n'
>>> 
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list