python paramiko模塊簡介


python paramiko模塊簡介python


一:簡介linux

    paramiko是用python語言寫的一個模塊,遵循SSH2協議,支持以加密和認證的方式,進行遠程服務器的鏈接。shell

    因爲使用的是python這樣的可以跨平臺運行的語言,因此全部python支持的平臺,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko均可以支持,所以,若是須要使用SSH從一個平臺鏈接到另一個平臺,進行一系列的操做時,paramiko是最佳工具之一。windows

    舉個常見的例子,現有這樣的需求:須要使用windows客戶端,遠程鏈接到Linux服務器,查看上面的日誌狀態,你們一般使用的方法會是:bash

1:用telnet服務器

2:用PUTTYsession

3:用WinSCPpython2.7

4:用XManager等…ssh

那如今若是需求又增長一條,要從服務器上下載文件,該怎麼辦?那經常使用的辦法可能會是:scrapy

1:Linux上安裝FTP並配置

2:Linux上安裝Sambe並配置…


    你們會發現,常見的解決方法都會須要對遠程服務器必要的配置,若是遠程服務器只有一兩臺還好說,若是有N臺,還須要逐臺進行配置,或者須要使用代碼進行以上操做時,上面的辦法就不太方便了。

    使用paramiko能夠很好的解決以上問題,比起前面的方法,它僅須要在本地上安裝相應的軟件(python以及PyCrypto),對遠程服務器沒有配置要求,對於鏈接多臺服務器,進行復雜的鏈接操做特別有幫助。


二:安裝

  安裝paramiko有兩個先決條件,python和另一個名爲PyCrypto的模塊。

  一般安裝標準的python模塊,只須要在模塊的根目錄下運行:

python setup.py build
python setup.py install

備註:安裝前先檢查是否安裝gcc(yum -y install gcc)


2.1 PyCrypto安裝

wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz
tar -zxvf pycrypto-2.6.tar.gz
cd pycrypto-2.6/
python setup.py build && python setup.py install

測試:

python>> import Crypto

  (編譯時報錯:error: command 'gcc' failed with exit status 1;這是由於缺乏python-dev的軟件包,所yum -y install python-devel)


2.2 paramiko安裝

wget http://www.lag.net/paramiko/download/paramiko-1.7.7.1.tar.gz
tar xvzf paramiko-1.7.7.1.tar.gz
cd paramiko-1.7.7.1/
python setup.py build && python setup.py install
Crypto error: 'module' object has no attribute 'HAVE_DECL_MPZ_POWM_SEC'

測試:

python>> import paramiko
  (Crypto error: 'module' object has no attribute 'HAVE_DECL_MPZ_POWM_SEC'
  找到 /usr/lib/python2.7/site-packages/Crypto/Util/number.py
  把if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
  註釋了
  #if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
  )

三: 使用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)來遠程執行命令以及本地獲取反饋。

paramiko有兩個模塊SSHClient()和SFTPClient()


3.一、利用SSHClient()

 #coding:utf-8
 import paramiko
  
 #建立SSH對象
 ssh = paramiko.SSHClient()
 # 容許鏈接不在know_hosts文件中的主機
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 # 鏈接服務器
 ssh.connect(hostname='192.168.2.103', port=22, username='root', password='123456')
 
 # 執行命令
 stdin, stdout, stderr = ssh.exec_command('ls')
 # 獲取命令結果
 result = stdout.read()
 print (str(result,encoding='utf-8'))
 # 關閉鏈接
 ssh.close()

SSHClient()裏面有一個transport變量,這個是用於獲取鏈接的,所以咱們也能夠單獨的獲取到transport變量,而後執行鏈接操做


  #coding:utf-8
  import paramiko
  
  transport = paramiko.Transport(('192.168.2.103', 22))
  transport.connect(username='root', password='123456')
  
  ssh = paramiko.SSHClient()
  ssh._transport = transport
  
 stdin, stdout, stderr = ssh.exec_command('df')
 print (str(stdout.read(),encoding='utf-8'))
 
 transport.close()


3.二、用transport實現上傳下載以及命令的執行:

 #coding:utf-8
  import paramiko
  import uuid
  
  class SSHConnection(object):
  
      def __init__(self, host='192.168.2.103', port=22, username='root',pwd='123456'):
         self.host = host
         self.port = port
         self.username = username
         self.pwd = pwd
         self.__k = None
 
     def connect(self):
         transport = paramiko.Transport((self.host,self.port))
         transport.connect(username=self.username,password=self.pwd)
         self.__transport = transport
 
     def close(self):
         self.__transport.close()
 
     def upload(self,local_path,target_path):
         # 鏈接,上傳
         # file_name = self.create_file()
         sftp = paramiko.SFTPClient.from_transport(self.__transport)
         # 將location.py 上傳至服務器 /tmp/test.py
         sftp.put(local_path, target_path)
 
     def download(self,remote_path,local_path):
         sftp = paramiko.SFTPClient.from_transport(self.__transport)
         sftp.get(remote_path,local_path)
 
     def cmd(self, command):
         ssh = paramiko.SSHClient()
         ssh._transport = self.__transport
         # 執行命令
         stdin, stdout, stderr = ssh.exec_command(command)
         # 獲取命令結果
         result = stdout.read()
         print (str(result,encoding='utf-8'))
         return result
         
     ssh = SSHConnection()
          ssh.connect()
          ssh.cmd("ls")
          ssh.upload('s1.py','/tmp/ks77.py')
          ssh.download('/tmp/test.py','kkkk',)
          ssh.cmd("df")
          ssh.close()



四,與linux鏈接


下面是兩種使用paramiko鏈接到linux服務器的代碼


方式一:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("某IP地址",22,"用戶名", "口令")

方式二:

t = paramiko.Transport((「主機」,」端口」))
t.connect(username = 「用戶名」, password = 「口令」)

SFTPClient()也是使用transport來實現的,所以若是有需求須要執行命令和上傳文件糅合在一塊兒的話,那麼就須要使用transport的方式來實現。


若是鏈接遠程主機須要提供密鑰,上面第二行代碼可改爲:

t.connect(username = 「用戶名」, password = 「口令」, hostkey=」密鑰」)


4.1 windows對linux運行任意命令,並將結果輸出


若是linux服務器開放了22端口,在windows端,咱們可使用paramiko遠程鏈接到該服務器,並執行任意命令,而後經過 print或其它方式獲得該結果,


代碼以下

 #coding:Utf8
  
 import paramiko
  
 ssh = paramiko.SSHClient()
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 ssh.connect("某IP地址",22,"用戶名", "口令")
 stdin, stdout, stderr = ssh.exec_command("你的命令")
 print stdout.readlines()
  ssh.close()

其中的」你的命令」能夠任意linux支持的命令


4.2 從widnows端下載linux服務器上的文件

 coding:utf8
  
 import paramiko
   
 t = paramiko.Transport((「主機」,」端口」))
 t.connect(username = 「用戶名」, password = 「口令」)
 sftp = paramiko.SFTPClient.from_transport(t)
 remotepath=’/var/log/system.log’
 localpath=’/tmp/system.log’
  sftp.get(remotepath, localpath)
  t.close()


4.3 從widnows端上傳文件到linux服務器

 import paramiko
 
 t = paramiko.Transport((「主機」,」端口」))
 t.connect(username = 「用戶名」, password = 「口令」)
 sftp = paramiko.SFTPClient.from_transport(t)
 remotepath=’/var/log/system.log’
 localpath=’/tmp/system.log’
 sftp.put(localpath,remotepath)
 t.close()


4.4 在Linux上安裝paramiko模塊


安裝scrapy這個應用中遇到的問題

c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory
sudo apt-get install python-dev
c/_cffi_backend.c:13:17: fatal error: ffi.h: No such file or directory
1 sudo apt-get install libffi-dev
* make sure the development packages of libxml2 and libxslt are installed *
1 sudo apt-get install libxslt1-dev

1.下載安裝wget http://peak.telecommunity.com/dist/ez_setup.py
2.python ez_setup.py
3.easy_install paramiko
相關文章
相關標籤/搜索