循序漸進Python3(十)-- 4 -- paramiko


paramiko模塊,基於SSH用於連接遠程服務器並執行相關操作。

使用

(1)SSHClient

用於連接遠程服務器並執行基本命令

基於用戶名密碼連接:

#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = '無名小妖'
import paramiko

# 創建SSH對象
ssh = paramiko.SSHClient()
# 允許連接不在know_hosts文件中的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接服務器
ssh.connect(hostname='192.168.168.231', port=22, username='oracle', password='oracle')

# 執行命令
stdin, stdout, stderr = ssh.exec_command('ls')
# 獲取命令結果
result = stdout.read()
print(result.decode())
# 關閉連接
ssh.close()
-----------------
使用transport :
#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = '無名小妖'
import paramiko

transport = paramiko.Transport(('192.168.168.231', 22))
transport.connect(username='oracle', password='oracle')

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
print(stdout.read().decode())

transport.close()
--------------------------

(2)SFTPClient

用於連接遠程服務器並執行上傳下載

基於用戶名密碼上傳下載:

  
  
  
          
import paramiko
  
transport = paramiko.Transport(( ' 192.168.168.231 ' , 22 ))
transport.connect(username = 'root' ,password = '123456' )
  
sftp = paramiko.SFTPClient.from_transport(transport)
# 將location.py 上傳至服務器 /tmp/test.py
sftp.put( '/tmp/location.py' , '/tmp/test.py' )
# 將remove_path 下載到本地 local_path
sftp.get( 'remove_path' , 'local_path' )
  
transport.close()

---------------------------------------------------------------------

基於公鑰密鑰連接:

import paramiko
  
private_key = paramiko.RSAKey.from_private_key_file( '/home/auto/.ssh/id_rsa' )
  
# 創建SSH對象
ssh = paramiko.SSHClient()
# 允許連接不在know_hosts文件中的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接服務器
ssh.connect(hostname = 'c1.salt.com' , port = 22 , username = 'wupeiqi' , key = private_key)
  
# 執行命令
stdin, stdout, stderr = ssh.exec_command( 'df' )
# 獲取命令結果
result = stdout.read()
  
# 關閉連接
ssh.close()
-------------------------------------------------------------------------

基於公鑰密鑰上傳下載:

import paramiko
  
private_key = paramiko.RSAKey.from_private_key_file( '/home/auto/.ssh/id_rsa' )
  
transport = paramiko.Transport(( 'hostname' , 22 ))
transport.connect(username = 'wupeiqi' , pkey = private_key )
  
sftp = paramiko.SFTPClient.from_transport(transport)
# 將location.py 上傳至服務器 /tmp/test.py
sftp.put( '/tmp/location.py' , '/tmp/test.py' )
# 將remove_path 下載到本地 local_path
sftp.get( 'remove_path' , 'local_path' )
  
transport.close()
-------------------------------------------------------------------------------------
實用小例子:(使用transport既執行命令又上傳下載文件)
#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = '無名小妖'
import paramiko


class SSHConnection(object):

def __init__(self, host='192.168.168.231', port=22, username='oracle', pwd='oracle'):
self.host = host
self.port = port
self.username = username
self.pwd = pwd
self.__k = None

def run(self):
self.connect()
pass
self.close()

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 cmd(self, command):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 執行命令
stdin, stdout, stderr = ssh.exec_command(command)
# 獲取命令結果
result = stdout.read()
return result

def upload(self,local_path, target_path):
# 連接,上傳
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# location.py 上傳至服務器 /tmp/test.py
sftp.put(local_path, target_path)

ssh = SSHConnection()
ssh.connect()
r1 = ssh.cmd('df')
print(r1.decode())
ssh.upload('class12.py', "test.py")
ssh.close()
-------------------------------------------------------------------

實現遠程登錄並進行操作

#!/usr/bin/env python # Version = 3.5.2 # __auth__ = '無名小妖' import paramiko import sys import os import socket import select import getpass from paramiko.py3compat import u tran = paramiko.Transport(('192.168.191.3', 22,)) tran.start_client() tran.auth_password('root', '7ujm8ik,') # 打開一個通道 chan = tran.open_session() # 獲取一個終端 chan.get_pty() # 激活器 chan.invoke_shell() while True: # 監視用戶輸入和服務器返回數據 # sys.stdin 處理用戶輸入 # chan 是之前創建的通道,用於接收服務器返回信息 readable, writeable, error = select.select([chan, sys.stdin, ], [], [], 1) if chan in readable: try: x = u(chan.recv(1024)) if len(x) == 0: print('\r\n*** EOF\r\n') break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in readable: inp = sys.stdin.readline() chan.sendall(inp) chan.close() tran.close()


參考文檔 :
http://www.cnblogs.com/wupeiqi/articles/5699254.html 






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM