我不是一個程序員,但想用Python來實現一些管理目的的自動化。 我嘗試創建的「Hello world」之後的第一個應用程序是交互式ssh客戶端。 我讀過一些文檔和文章,並認爲它是使用paramiko模塊的最簡單方法,但不幸的是我面臨一個問題: 我的應用程序會要求您輸入一些必要的信息,例如服務器IP,用戶名,密碼。在此之後,它建立與定義的服務器的連接,併爲您提供屏幕上的cli。爲了模擬輸入命令的過程,我使用while循環。 不幸的是,我的應用程序只適用於您輸入的第一個命令。雖然試圖輸入第二個命令出現錯誤:Python交互式ssh客戶端使用paramiko
Traceback (most recent call last):
File "C:\Python27\Tests\ssh_client.py", line 53, in <module>
client.execute_command(command)
File "C:\Python27\Tests\ssh_client.py", line 26, in execute_command
stdin,stdout,stderr = self.connection.exec_command(command)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 343, in exec_command
chan.exec_command(command)
AttributeError: 'NoneType' object has no attribute 'exec_command'
守則PROGRAMM的(Windows 7)中:
import paramiko
SERVER = raw_input('Please enter an ip address of remote host: ')
USER = raw_input('Please enter your username: ')
PASSWORD = raw_input('Please enter your password: ')
class MYSSHClient():
def __init__(self, server=SERVER, username=USER, password=PASSWORD):
self.server = server
self.username = username
self.password = password
self.connection = None
self.result = ''
self.is_error = False
def do_connect(self):
self.connection = paramiko.SSHClient()
self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.connection.connect(self.server, username=self.username, password=self.password)
def execute_command(self, command):
if command:
print command
stdin,stdout,stderr = self.connection.exec_command(command)
stdin.close()
error = str(stderr.read())
if error:
self.is_error = True
self.result = error
print 'error'
else:
self.is_error = False
self.result = str(stdout.read())
print 'no error'
print self.result
else:
print "no command was entered"
def do_close(self):
self.connection.close()
if __name__ == '__main__':
client = MYSSHClient()
client.do_connect()
while 1:
command = raw_input('cli: ')
if command == 'q': break
client.execute_command(command)
client.do_close()
我試圖刪除while循環,只是呼籲通過在一個正確的命令一個代碼,但有相同的問題(輸入第二個命令時看到相同的錯誤)。 它看起來像我不完全理解paramiko模塊如何工作。我試圖在網上找到信息,但不幸的是沒有找到任何解決方案。
如果有人能告訴我我做錯了什麼,或者給我一個關於類似問題的鏈接,我可以找到解決方案,我將非常感激。
在此先感謝您的幫助。
據我所知pexpect只適用於基於UNIX的操作系統。無論如何,我試圖安裝它,當進行導入pxssh看到一個錯誤沒有找到一個關鍵的模塊。可能這個操作系統並不支持它 。 Pexpect適用於類UNIX操作系統。 – HFFreeway