類下面被設計成操縱一個cisco狀裝置接口,用於執行命令和更新配置元件的目的。我現在可以實例化這個類,調用ssh_to_aos_expsh
函數並獲取有效的輸出(例如,當命令是'show running-config'時獲取配置)。然而,當我做出了ssh_to_aos_config
函數的調用(它調用ssh_to_aos_expsh
功能),我得到一個Pexpect的超時錯誤。問題的Pexpect的和「鏈狀」的函數調用
我比較(在_ssh_connect
,ssh_to_aos_expsh
和ssh_to_aos_config
的「孩子」)通過_ssh_connect
回到ssh_to_aos_expsh
通過ssh_to_aos_expsh
返回ssh_toaos_config
對象的Pexpect的對象,這似乎是在同一個內存位置,所以我我不明白爲什麼我不能繼續用有意思的方式來操縱對象。
我不是最複雜的python編碼器,所以我有可能在嘗試在函數之間傳遞pexpect對象時犯了一些無意的錯誤,如果是這樣,我會很感激有人指出我的錯誤。
#!/usr/bin/env python
import os
import traceback
import pexpect
class SSHTool():
def __init__(self):
self.aos_user = 'some_user'
self.aos_passwd = 'some_passwd'
self.aos_init_prompt = 'accelerator>'
self.aos_enable_prompt = 'accelerator#'
self.aos_lnxsh_prompt = 'ACC#'
self.linux_passwd = 'linux_passwd'
self.root_prompt = ''
def _timeout_error(self, child):
print 'SSH could not login. Timeout error.'
print child.before, child.after
return None
def _password_error(self, child):
print 'SSH could not login. Password error.'
print child.before, child.after
return None
def _ssh_connect(self, user, address, passwd):
self.root_prompt = "[email protected]%s's password: " % address
ssh_newkey = "Are you sure you want to continue connecting"
child = pexpect.spawn('ssh -l %s %s' % (user, address))
i = child.expect([pexpect.TIMEOUT, \
ssh_newkey, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
elif i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
i = child.expect([pexpect.TIMEOUT, \
'Password: ', \
self.root_prompt])
if i == 0: # Timeout
return self._timeout_error(child)
else:
child.sendline(passwd)
return child
elif i == 2 or i == 3:
child.sendline(passwd)
return child
else:
return self._password_error(child)
def ssh_to_aos_expsh(self, ip_address, command = ''):
child = self._ssh_connect(self.aos_user, \
ip_address, \
self.aos_passwd)
i = child.expect([pexpect.TIMEOUT, \
self.aos_init_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('enable')
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
if command:
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
else:
return child
def ssh_to_aos_config(self, ip_address, command):
child = self.ssh_to_aos_expsh(ip_address)
i = child.expect([pexpect.TIMEOUT, \
self.aos_enable_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline('config')
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
child.sendline(command)
i = child.expect([pexpect.TIMEOUT, \
self.aos_config_prompt])
if i == 0:
return self._timeout_error(child)
else:
return child.before
實際上,調用_ssh_connect時會設置self.root_prompt。由於每個連接到的設備的根提示都不同,我需要動態構建它。 我在_ssh_connect中修正了縮進問題,它只是我粘貼文本的工件。 – 2009-11-14 11:21:19