標籤:type 參數 atime 輸出 系統維護 方式 ror /tmp print
作業系統維護時, 一般會通過ssh命令串連到遠端伺服器, 進行某些操作. 那Python中如何完成這些呢, 當然也能執行ssh命令, 但還有更優雅的方式, 藉助Paramiko, 其為實現了SSHv2協議的一開源項目, 下面主要使用了它的ssh和sftp用戶端的相關功能.
安裝
# 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