Python Paramiko模組的使用實際案例,pythonparamiko

來源:互聯網
上載者:User

Python Paramiko模組的使用實際案例,pythonparamiko

本文研究的主要是Python Paramiko模組的使用的執行個體,具體如下。

Windows下有很多非常好的SSH用戶端,比如Putty。在python的世界裡,你可以使用原始通訊端和一些加密函數建立自己的SSH用戶端或服務端,但如果有現成的模組,為什麼還要自己實現呢。使用Paramiko庫中的PyCrypto能夠讓你便於使用SSH2協議。

Paramiko的安裝方法網上有很多這樣的文章,這裡就不描述了。這裡主要講如何使用它。Paramiko實現SSH2不外乎從兩個角度實現:SSH用戶端與服務端。

首先讓我們理清以下幾個名詞:

  • SSHClient:封裝了Channel、Transport、SFTPClient
  • Channel:是一種類Socket,一種安全的SSH傳輸通道;
  • Transport:是一種加密的會話(但是這樣一個對象的Session並未建立),並且建立了一個加密的tunnels,這個tunnels叫做Channel;
  • Session:是client與Server保持串連的對象,用connect()/start_client()/start_server()開始會話。

具體請參考Paramiko的庫文檔:http://docs.paramiko.org/en/2.0/index.html

下面給出幾個常用的使用案例:

SSH用戶端實現方案一,執行遠程命令

這個方案直接使用SSHClient對象的exec_command()在服務端執行命令,下面是具體代碼:

  #執行個體化SSHClient  client = paramiko.SSHClient()  #自動添加策略,儲存伺服器的主機名稱和密鑰資訊  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  #串連SSH服務端,以使用者名稱和密碼進行認證  client.connect(ip,username=user,password=passwd)  #開啟一個Channel並執行命令  stdin,stdout,stderr = client.exec_command(command)  #列印執行結果  print stdout.readlines()  #關閉SSHClient  client.close()
SSH用戶端實現方案二,執行遠程命令

這個方案是將SSHClient建立串連的對象得到一個Transport對象,以Transport對象的exec_command()在服務端執行命令,下面是具體代碼:

#執行個體化SSHClientclient = paramiko.SSHClient()#自動添加策略,儲存伺服器的主機名稱和密鑰資訊client.set_missing_host_key_policy(paramiko.AutoAddPolicy())#串連SSH服務端,以使用者名稱和密碼進行認證client.connect(ip,username=user,password=passwd)#執行個體化Transport,並建立會話Sessionssh_session = client.get_transport().open_session()if ssh_session.active:  ssh_session.exec_command(command)  print ssh_session.recv(1024)client.close()
SSH服務端的實現

實現SSH服務端必須繼承ServerInterface,並實現裡面相應的方法。具體代碼如下:

import socketimport sysimport threadingimport paramikohost_key = paramiko.RSAKey(filename='private_key.key')class Server(paramiko.ServerInterface):  def __init__(self):  #執行start_server()方法首先會觸發Event,如果返回成功,is_active返回True    self.event = threading.Event()  #當is_active返回True,進入到認證階段  def check_auth_password(self, username, password):    if (username == 'root') and (password == '123456'):      return paramiko.AUTH_SUCCESSFUL    return paramiko.AUTH_FAILED  #當認證成功,client會請求開啟一個Channel  def check_channel_request(self, kind, chanid):    if kind == 'session':      return paramiko.OPEN_SUCCEEDED#命令列接收ip與portserver = sys.argv[1]ssh_port = int(sys.argv[2])#建立sockettry:  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  #TCP socket  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  sock.bind((server, ssh_port))    sock.listen(100)    print '[+] Listening for connection ...'  client, addr = sock.accept()except Exception, e:  print '[-] Listen failed: ' + str(e)  sys.exit(1)print '[+] Got a connection!'try:  #用sock.accept()返回的socket執行個體化Transport  bhSession = paramiko.Transport(client)  #添加一個RSA祕密金鑰加密會話  bhSession.add_server_key(host_key)  server = Server()  try:  #啟動SSH服務端    bhSession.start_server(server=server)  except paramiko.SSHException, x:    print '[-] SSH negotiation failed'  chan = bhSession.accept(20)   print '[+] Authenticated!'  print chan.recv(1024)  chan.send("Welcome to my ssh")  while True:    try:      command = raw_input("Enter command:").strip("\n")       if command != 'exit':        chan.send(command)        print chan.recv(1024) + '\n'      else:        chan.send('exit')        print 'exiting'        bhSession.close()        raise Exception('exit')    except KeyboardInterrupt:      bhSession.close()except Exception, e:  print '[-] Caught exception: ' + str(e)  try:    bhSession.close()  except:    pass  sys.exit(1)
使用SFTP上傳檔案
import paramiko#擷取Transport執行個體tran = paramiko.Transport(("host_ip",22))#串連SSH服務端tran.connect(username = "username", password = "password")#擷取SFTP執行個體sftp = paramiko.SFTPClient.from_transport(tran)#設定上傳的本地/遠程檔案路徑localpath="/root/Desktop/python/NewNC.py"remotepath="/tmp/NewNC.py"#執行上傳動作sftp.put(localpath,remotepath)tran.close()
使用SFTP下載檔案
import paramiko#擷取SSHClient執行個體client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())#串連SSH服務端client.connect("host_ip",username="username",password="password")#擷取Transport執行個體tran = client.get_transport()#擷取SFTP執行個體sftp = paramiko.SFTPClient.from_transport(tran)remotepath='/tmp/NewNC.py'localpath='/root/Desktop/NewNC.py'sftp.get(remotepath, localpath)client.close()
總結

以上就是本文關於Python 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.