reading output from pexpect sendline

Programming in python: reading output from pexpect sendline on newest questions tagged python – Stack Overflow

I have pexpect working, but I am having problems printing the output back from it. In my test script below, it creates the ssh connection, and then sends a sudo su -, then my password, and then sends a line that would require sudo access to do (I have also added p.interact() a few times to make sure it is at root). The problem I am having, is with returning the output of the commands I run. In the end I am wanting to run some top commands, and some du -h, and other(much more complex) space commands. But currently when it tries to print p.before, I get:

Traceback (most recent call last):
File "./", line 37, in <module>
print p.before()
TypeError: 'str' object is not callable

Here is the script I am working from(edited to remove my pass and such)

#!/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 = 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

ssh_newkey = 'Are you sure you want to continue connecting'
p=pexpect.spawn('ssh user@localhost')
if i==0:
    print "I say yes"
if i==1:
    print "I give password",
elif i==2:
    print "I either got key or connection timeout"
elif i==3: #timeout
global global_pexpect_instance
global_pexpect_instance = p
p.sendline("sudo su -")
p.sendline("mkdir /home/user/test")
print p.before

I am working off of this link:

Any help is much appreciated.

EDIT: As Armin Rigo pointed out below. I was calling to p.before as a function like p.before(). Stupid mistake on my part, as this explains why I was getting this error today, and not yesterday when I was trying this. After making that change to my script, and modifying the command being sent, print p.before, and no output is returned. Any other ways to return output from a sendline() command?

See Answers

Programming in python: programming-in-python

Leave a Reply