Reputation: 3761
Im trying to write a python script using the pexpect library.
What im trying to do is as follows:
ID = 'User1'
cmdrun = 'A LINUX COMMAND'
sshChild = pexpect.spawn('ssh [email protected]')
sshOut = file('sshLog.txt','w')
sshChild.logfile = sshOut
sshChild.expect('Last login:*')
sshChild.expect('Please enter your login Id')
sshChild.sendline(ID + '\r')
sshChild.sendline('ssh 192.168.21.1\r')
sshChild.expect('Last login:*')
sshChild.expect('Please enter your login Id')
sshChild.sendline(ID + '\r')
sshChild.sendline(cmdrun + '\r')
Everything works as expected up until the last line, where i do the sendline for the cmdrun. This command is a custom tcpdump command, i want the command to run indefinitely until i do a sendctrl('C') to kill it and then escape the ssh tunnel.
However unless i put an interact() after the sendline(cmdrun + '\r') the output from the tcpdump does not get printed.
Is there anyway i can do this without interact as i do not want interactive terminal control. What i want is to be able to wait a period of time, capturing the tcpdump output, then kill the tcpdump along with the ssh tunnel.
Upvotes: 3
Views: 1936
Reputation: 66739
I have never used pexpect for a long running command. But you can try the following:
Pexpect waits for completion of the command and provides you with the output.
sshChild.sendline(cmdrun + '\r')
Since this is long running command, it is never going to give you the output unless you run
child.interact()
Can you try to have this after executing the command with appropriate timeout so that you kill the long running command after certain time and capture the output obtained till then.
sshChild.sendline(cmdrun + '\r')
child.expect(pexpect.EOF, timeout=20)
print child.before, child.after
Upvotes: 1