一、作用
paramiko模塊,基於SSH用於連接遠程服務器並執行相關操作。
二、使用
SSHClient
用於連接遠程服務器並執行基本命令
基於用戶名密碼連接:
# 建立一個sshclient對象 ssh = paramiko.SSHClient() # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 調用connect方法連接服務器 ssh.connect(hostname = '192.168.2.129' , port = 22 , username = 'super' , password = 'super' ) # 執行命令 stdin, stdout, stderr = ssh.exec_command( 'df -hl' ) # 結果放到stdout中,如果有錯誤將放到stderr中 print (stdout.read().decode()) # 關閉連接 ssh.close() |
坑:開始一致正常鏈接,重新生成ssh-key 後,無法連接了,,也設置了ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()),最後百度找到解決辦法:,在connect 的時候加入參數 allow_agent, look_for_keys 就可以了。
最終找到的解決方法很簡單
備註:
1)sftp本質實現的是單個文件的傳輸,如果源文件路徑寫的是文件夾,運行時時會直接報錯,多個文件的傳輸只能通過循環遍歷實現
2)remotepath (str) – the destination path on the SFTP server. Note that the filename should be included. Only specifying a directory may result in an error.(目的文件的路徑必須包含文件名,否者會報錯)
def copy_file_to_remote(ssh, local_file, remote_file): # 建立連接 sftp = paramiko.SSHClient.open_sftp(ssh) #等價於 ssh.open_sftp(ssh) 暫不知二者在原理上有什麼區別 # Copy a remote file (remotepath) from the SFTP server to the local host #dst_file must be include filename sftp.put(local_file, remote_file) # Copy a local file (localpath) to the SFTP server as remotepath sftp.close() def copy_file_from_remote(ssh, remote_file, local_file): # 建立連接 sftp = paramiko.SSHClient.open_sftp(ssh) # Copy a remote file (remotepath) from the SFTP server to the local host #dst_file must be include filename sftp.get(remote_file, local_file) # Copy a local file (localpath) to the SFTP server as remotepath sftp.close() |
備註:以下方式也可以實現sftp
transport = paramiko.Transport(( '192.168.179.130' , 22 )) transport.connect(username = 'root' ,password = 'greg311' ) sftp = paramiko.SFTPClient.from_transport(transport) #該方法與 sftp = paramiko.SSHClient.open_sftp(ssh),.分析源碼可知,SSHClient.open_sftp(ssh)最終也是通過SFTPClient.from_transport(t)建立傳輸通道
|