A little help with pexpect

H

Hussein B

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

Piet van Oostrum

Hussein B said:
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:

Open a channel for a command
''

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

Piet van Oostrum

Piet van Oostrum said:
PvO> You can also consider using paramiko instead of pexpect. [snip]

In a real program it is better to use sendall here, as send may decide
to send only part of its argument (the result will tell how many bytes
have been sent).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top