使用python中有一個paramiko模塊來實現python SSH客戶端,與SSH服務器交互時,需要注意有交互式和非交互式的區別。
只執行單條命令,之后就斷開鏈接,可以使用非交互方式。執行多條命令,或者基於前面的輸出結果來判斷后續要執行的命令,需要使用交互式方式。
我在寫自動化測試用例時,就嘗試使用非交互方式去連接一個只支持交互方式的SSH服務器,就怎么也讀不到返回結果。換成交互式后就可以了。
需要注意的是,命令后面記得加“\n”。
下面內容轉自: https://blog.csdn.net/u012322855/article/details/77839929/
python中有一個paramiko,功能強大,用來做SSH比較方便
先上代碼
import paramiko class SSHConnection(object): def __init__(self, host, port, username, password): self._host = host self._port = port self._username = username self._password = password self._transport = None self._sftp = None self._client = None self._connect() # 建立連接 def _connect(self): transport = paramiko.Transport((self._host, self._port)) transport.connect(username=self._username, password=self._password) self._transport = transport #下載 def download(self, remotepath, localpath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.get(remotepath, localpath) #上傳 def put(self, localpath, remotepath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.put(localpath, remotepath) #執行命令 def exec_command(self, command): if self._client is None: self._client = paramiko.SSHClient() self._client._transport = self._transport stdin, stdout, stderr = self._client.exec_command(command) data = stdout.read() if len(data) > 0: print data.strip() #打印正確結果 return data err = stderr.read() if len(err) > 0: print err.strip() #輸出錯誤結果 return err def close(self): if self._transport: self._transport.close() if self._client: self._client.close()
接下來就簡單測試一下exec_command這個命令,比較常用
if __name__ == "__main__": conn = SSHConnection('ip', port, 'username', 'password') conn.exec_command('ls -ll') conn.exec_command('cd /home/test;pwd') #cd需要特別處理 conn.exec_command('pwd') conn.exec_command('tree /home/test')
exec_command這個函數如果想cd,可以使用pwd這樣可以到當前目錄而不是初始目錄,但是有些情況下,比如chroot,是做不到的,這個時候就需要新的方法
上代碼
ssh = paramiko.SSHClient() #創建sshclient ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #目的是接受不在本地Known_host文件下的主機。 ssh.connect("ip",port,'username','password') command='chroot /xxx\n' #conn.write(command) chan=ssh.invoke_shell()#新函數 chan.send(command+'\n') #\n是執行命令的意思,沒有\n不會執行 time.sleep(10)#等待執行,這種方式比較慢 #這個時候就可以在chroot目錄下執行命令了 res=chan.recv(1024)#非必須,接受返回消息 chan.close()
注意invoke_shell這個函數即可
另外使用這個函數命令后面記得加“\n”