pexpect: unable to run command on multi-hopped node using namespace

时间:2015-05-04 19:55:36

标签: python pexpect

I had posted this problem earlier https://stackoverflow.com/questions/29794260/python-fabric-multi-hop-ssh-to-run-cmd-on-remote-host-using and since I was unable to find a fix I adopted pexpect to implement. However I am unable to achieve the intent of running command on the end machine:

TestMachine -- connected---Node1--(namespace ssh)--Node2(run cmd on Node2)

Here is the piece of code which I am running:

#!/usr/bin/env python
import pexpect
import sys
h1='8.8.8.2'
un='root'
### This below worked correctly as expected ###
child = pexpect.spawn("ssh root@node1")
child.expect('password:')
child.sendline('abc123')
child.expect('#')
child.sendline("ls")
child.expect('#')
print child.before
child.sendline('ssh root@node2')
child.expect('password:')
child.sendline('abc123')
child.expect('#')
child.sendline("ifconfig eth2")
child.expect('#')
print child.before
child.sendline('ip netns exec dhcp_ns_1 ssh test@20.20.20.2') #Node2 access
child.expect('password:')
child.sendline('abc123')
child.expect('')
child.sendline("ifconfig eth0")
child.expect('$')
print child.before

The script does not error out, however it does not seem to access Node2 as no output on print is seen. Any help much appreciated

1 个答案:

答案 0 :(得分:0)

child.expect('$')更改为child.expect('\$'),解决了问题