Python中SSH協議的實現 - Paramiko
安裝
# pip install paramiko
SSH客戶端使用
In [1]: import paramiko
#獲取SSHClient對象.
In [2]: ssh = paramiko.SSHClient()
#設置host key策略.
#ssh.load_system_host_keys('/root/.ssh/known_hosts')
In [3]: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連接到SSH server, connect方法有若幹參數, 可據需要設置, 如超時(timeout).
In [4]: ssh.connect('192.168.1.4')
#在SSH server上執行命令, 返回其I/O流, 類似於Python中的文件句柄, 標準輸出(stdout)和標準錯誤(stderr)較常用.
In [5]: stdin, stdout, stderr = ssh.exec_command('ls -l /tmp/')
#獲取標準輸出
In [11]: for line in stdout:
...: print '-> ' + line.strip('\n')
...:
-> total 16
-> -rw-r--r-- 1 root root 2 Jan 24 18:27 a.txt
-> -rw-r--r-- 1 root root 2 Jan 24 18:27 b.txt
-> -rw-r--r-- 1 root root 2 Jan 24 18:27 c.txt
-> -rw-r--r-- 1 root root 2 Jan 24 18:27 d.txt
SFTP客戶端使用
#在連接到SSH server基礎上, 獲取SFTPClient對象.
sftp = ssh.open_sftp()
#上傳文件
In [13]: sftp.put('/tmp/zz.txt', '/tmp/')
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-13-0e19a403e0d2> in <module>()
----> 1 sftp.put('/tmp/zz.txt', '/tmp/')
/usr/local/python27/lib/python2.7/site-packages/paramiko/sftp_client.pyc in put(self, localpath, remotepath, callback, confirm)
...
IOError: Failure
In [14]:
為什麽報錯呢, 命令行上測試正常的...
# sftp 192.168.1.4
Connected to 192.168.1.4.
sftp> put '/tmp/zz.txt' '/tmp'
Uploading /tmp/zz.txt to /tmp/zz.txt
/tmp/zz.txt 100% 3 0.0KB/s 00:00
sftp>
查看sftp_client.py中put方法時, 發現remotepath參數, 需寫明目標文件的名稱.
:param str remotepath: the destination path on the SFTP server. Note
that the filename should be included. Only specifying a directory
may result in an error.
這樣就可以了.
In [21]: sftp.put('/tmp/zz.txt', '/tmp/zz.txt')
Out[21]: <SFTPAttributes: [ size=3 uid=901 gid=901 mode=0100664 atime=1516792881 mtime=1516792881 ]>
#關閉連接
In [24]: sftp.close()
In [25]: ssh.close()
若感興趣可關註訂閱號”數據庫最佳實踐”(DBBestPractice).
Python中SSH協議的實現 - Paramiko