William126

Python自学笔记-paramiko模块(Mr serven)

文章出处:http://www.cnblogs.com/wupeiqi/articles/5095821.html

SSHClient

用于连接远程服务器并执行基本命令

基于用户名密码连接:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname='10.245.53.85', port=23, username='Administrator', password='Aa1')
stdin, stdout, stderr = ssh.exec_command('dir')

result = stdout.read()

ssh.close()

# SSHClient 封装Transport

import paramiko

transport = paramiko.Transport(('hostname',22))
transport.connect(username="Administrator", password="Aa1")

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

stdin, stdout, stderr = ssh.exec_command('dir')
print(stdout.read())
transport.close()

基于公钥密钥连接:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='localhost',port=22, username='william',password='111111')

stdin, stdout, stderr = ssh.exec_command('df')
result = stdout.read()
ssh.close()
import paramiko

private_key = paramiko.RSAKey.from_private_key_file('hone/id_rsa')
transport = paramiko.Transport(('hostname',22))
transport.connect(username='william',pkey=private_key)

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

stdin, stdout, stderr = ssh.exec_command('df')
transport.close()
import paramiko
from io import StringIO

key_str = """-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAq7gLsqYArAFco02/55IgNg0r7NXOtEM3qXpb/dabJ5Uyky/8
NEHhFiQ7deHIRIuTW5Zb0kD6h6EBbVlUMBmwJrC2oSzySLU1w+ZNfH0PE6W6fans
DlQC4Zb73nHgdREtQYYXTu7p27Bl0Gizz1sW2eSgxFU8eTh+ucfVwOXKAXKU5SeI
+MbuBfUYQ4if2N/BXn47+/ecf3A4KgB37Le5SbLDddwCNxGlBzbpBa0=
-----END RSA PRIVATE KEY-----"""

private_key = paramiko.RSAKey(file_obj=StringIO(key_str))

transport = paramiko.Transport(('10.0.1.40',22))
transport.connect(username='william',pkey=private_key)

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

stdin, stdout, stderr = ssh.exec_command('dir')
result = stdout.read()

transport.close()
print(result)

SFTPClient

用于连接远程服务器并执行上传下载

基于用户名密码上传下载

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import paramiko
transport = paramiko.Transport(('10.103.110.211',22))
transport.connect(username='william',password='111111')
sftp = paramiko.SFTPClient.from_transport(transport)

sftp.get('Goal.jpg','..\homeWork')

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='william',pkey=private_key)

sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('/william/test.py','/willian/test.py')
sftp.get('remove_path','local_path')

 


posted on 2017-07-21 13:37  William126  阅读(327)  评论(0编辑  收藏  举报

导航