python paramiko實現ssh遠端存取的方法

來源:互聯網
上載者:User
安裝paramiko後,看下面例子:

代碼如下:


import paramiko

#設定ssh串連的遠程主機地址和連接埠
t=paramiko.Transport((ip,port))
#設定登入名稱和密碼
t.connect(username=username,password=password)
#串連成功後開啟一個channel
chan=t.open_session()
#設定會話逾時時間
chan.settimeout(session_timeout)
#開啟遠端terminal
chan.get_pty()
#啟用terminal
chan.invoke_shell()
然後就可以通過chan.send('command')和chan.recv(recv_buffer)來遠程執行命令以及本地擷取反饋。
例如:
chan.send('pwd')
print chan.recv(65535)

重點是,有些命令執行的時間長,不適當的receive回來可能得不到想要的結果,可以使用time.sleep()進行等待,或使用一些條件迴圈。
例如:

代碼如下:


str=chan.recv(recv_buffer)
while not str.endswith('#'):
str=chan.recv(recv_buffer)

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.