[英]Python interactive ssh client using paramiko
我不是程序員,但想將Python用於某些管理目的的自動化。 我嘗試創建的“ Hello world”之后的第一個應用程序是交互式ssh客戶端。 我已經閱讀了一些文檔和文章,並確定這將是使用paramiko模塊的最簡單方法,但是不幸的是,我遇到了一個問題:我的應用程序要求您輸入一些必要的信息,例如服務器ip,用戶名,密碼。 此后,它將與定義的服務器建立連接,並在屏幕上為您提供cli。 為了模擬輸入命令的過程,我使用了while循環。 不幸的是,我的應用程序只能與您輸入的第一個命令一起很好地工作。 嘗試鍵入第二個命令時,出現錯誤:
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'
程序代碼(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模塊的工作原理。 我試圖在網上查找信息,但不幸的是沒有找到任何解決方案。
如果有人可以告訴我我做錯了什么,或者給我有關類似問題的鏈接,我可以找到解決辦法,我將不勝感激。
在此先感謝您的幫助。
請為pxssh模塊使用,如果適用於Windows,則對您的應用程序非常有用Python:如何使用Paramiko從我的本地PC到remoteA到remoteb到遠程c遠程訪問本示例對您非常有用Python-Pxssh-出現密碼拒絕錯誤嘗試登錄到遠程服務器
我認為您檢查遠程主機中的服務器設置
不是您問題的真正答案,而是更多建議。
我建議您看一下結構,它可以完全滿足您的要求:在本地或遠程主機上自動執行任務。 可能會容易一些,因為您不必實現用於連接和執行命令的邏輯。
面料文檔: http : //docs.fabfile.org/en/1.6/
不幸的是,我沒有找到使用paramiko模塊解決問題的方法,但是我找到了Exscript這樣的模塊。 簡單的代碼如下:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.1')
conn.login(account)
while True:
command = raw_input('cli: ')
if command == 'q': break
conn.execute(command)
print conn.response
conn.send('quit\r')
conn.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.