I have pexpect, but I have problems printing output from it. In my test script below, it creates an ssh connection and then sends sudo su -, then my password, and then sends a line that needs sudo access (I also added p.interact () several times to make sure it is at the root ) The problem I am facing is returning the output of the commands that I run. In the end, I want to run some upper commands, and some du -h and other (much more complex) space commands. But currently, when he tries to print p.before, I get:
Traceback (most recent call last): File "./ssh.py", line 37, in <module> print p.before() TypeError: 'str' object is not callable
Here is the script I'm working with (edited to remove my pass, etc.)
#!/usr/bin/env python import pexpect import struct, fcntl, os, sys, signal def sigwinch_passthrough (sig, data): # Check for buggy platforms (see pexpect.setwinsize()). if 'TIOCGWINSZ' in dir(termios): TIOCGWINSZ = termios.TIOCGWINSZ else: TIOCGWINSZ = 1074295912 # assume s = struct.pack ("HHHH", 0, 0, 0, 0) a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s)) global global_pexpect_instance global_pexpect_instance.setwinsize(a[0],a[1]) ssh_newkey = 'Are you sure you want to continue connecting' p=pexpect.spawn('ssh user@localhost ') i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1) if i==0: print "I say yes" p.sendline('yes') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) if i==1: print "I give password", p.sendline("mypassword") elif i==2: print "I either got key or connection timeout" pass elif i==3: #timeout pass global global_pexpect_instance global_pexpect_instance = p p.sendline("sudo su -") p.sendline("mypasswd") p.sendline("mkdir /home/user/test") print p.before
I am working on this link: http://linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/
Any help is greatly appreciated.
EDIT: As noted by Armin Rigo. I called p.before as a function, e.g. p.before (). A stupid mistake on my part, as this explains why I got this error today, and not yesterday when I tried to do this. After making this change to my script and changing the command to send, type p.before and no output will be returned. Any other ways to return the output from the sendline () command?