【发布时间】:2017-02-12 06:07:34
【问题描述】:
我正在尝试编写一个脚本,我需要 ssh 多个跳转服务器来访问路由器。
例如LocalMachine----ssh---server1---ssh---server2---telnet/ssh---路由器
不确定最好的方法是什么,我尝试通过 pexpect 实现它。 我的要求是当我从服务器 server2 远程登录到路由器并且它超时/连接被拒绝时我想尝试 ssh 请问有什么建议吗?
import time, pexpect
child = pexpect.spawn('ssh username@server-1') ##########ssh to 1st Jump server
child.expect('password: ')
child.sendline('abc')
child.expect('$')
child.sendline('ssh username@server-2') ##########ssh to 2nd Jump server
print child.before
child.expect('password:')
child.sendline('xyz')
child.expect('$')
print child.before
host=raw_input("Enter Router name: ")
try:
print "Trying Telnet ", host
child.sendline(' telnet ' + host) ### router telnet at this point i want if telnet is timeout/connection refused try ssh
print child.before
except pexpect.TIMEOUT:
print child.before
else:
child.expect(':')
child.sendline("User")
child.expect(":")
child.sendline('passwprd')
child.expect('#')
child.sendline("\n")
child.expect("#")
finally:
print "Trying SSH ", host
child.sendline(' ssh -l User ' + host)
print child.before
child.expect(":")
child.sendline('password')
child.expect('#')
child.sendline("\n")
print child.before
child.interact()
【问题讨论】:
标签: python-2.7 pexpect