歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python的paramiko模塊ssh操作

Python的paramiko模塊ssh操作

日期:2017/3/1 9:06:05   编辑:Linux編程

SSHClient

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

基於用戶名密碼連接:

import paramiko

# 創建SSH對象

ssh = paramiko.SSHClient()

# 允許連接不在know_hosts文件中的主機

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 連接服務器

ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123')

# 執行命令

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')

# 創建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()

SFTPClient

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

基於用戶名密碼上傳下載

import paramiko

transport = paramiko.Transport(('hostname',22))

transport.connect(username='wupeiqi',password='123')

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')

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()

零基礎如何入門Python http://www.linuxidc.com/Linux/2016-10/136485.htm

Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

Ubuntu 14.04下Python數據處理環境搭建 http://www.linuxidc.com/Linux/2017-01/139568.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

在CentOS 6.5上安裝Python2.7 http://www.linuxidc.com/Linux/2016-10/136206.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Copyright © Linux教程網 All Rights Reserved