Python中SSH協議的實現 - Paramiko

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.