paramiko模块

1.定义

paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

2.使用实例

使用paramiko模块远程连接分为两种:1.只用SSHClient 2.自己创建一个transport

基于用户名和密码连接方式1:

python版本:Python 3.5.1

import paramiko
#创建ssh对象
ssh = paramiko.SSHClient()
#允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接服务器
ssh.connect(hostname='45.199.182.238',port=23424,username='zww',password='123')
#执行命令并获取命令输出结果
stdin,stdout,stderr=ssh.exec_command('df -h')
res=stdout.read()
print(res.decode())
#关闭连接
ssh.close()

 基于用户名和密码连接方式2:

import paramiko
transport = paramiko.Transport(('45.199.182.238',23424))
transport.connect(username='zww',password='123')
ssh=paramiko.SSHClient()
ssh._transport=transport
stdin,stdout,stderr=ssh.exec_command('df -h')
print(stdout.read().decode())
transport.close()

 基于公钥秘钥连接方式1:

#使用ssh-keygen命令创建秘钥对,公钥添加到目标主机对应用户的authorized_keys文件(远程添加公钥:ssh-copy-id '-p23424 zww@45.199.182.238')
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='45.199.182.238',port=23424,username='zww',pkey=private_key)
stdin,stdout,stderr=ssh.exec_command('df -h')
print(stdout.read().decode())
ssh.close()

  基于公钥秘钥连接方式2:

import paramiko
private_key= paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
transport=paramiko.Transport(('45.199.182.238',23424))
transport.connect(username='zww',pkey=private_key)
ssh=paramiko.SSHClient()
ssh._transport=transport
stdin,stdout,stderr=ssh.exec_command('df -h')
print(stdout.read().decode())
transport.close()

 基于用户名和密码连接远程服务器并进行上传下载方式1:

import paramiko
transport=paramiko.Transport(('45.199.182.238',23424))
transport.connect(username='zww',password='123')
sftp=paramiko.SFTPClient.from_transport(transport)
sftp.put('/root/a.log','/tmp/a.log')   #上传
sftp.get('/home/zww/abc.txt','/tmp/a.txt')  #下载

  基于公钥秘钥连接远程服务器并进行上传下载方式:

import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
transport = paramiko.Transport(('45.199.182.238', 23424))
transport.connect(username='zww', pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/po.sh', '/tmp/abc.py')
# 将remove_path 下载到本地 local_path
sftp.get('/tmp/a.log', '/root/a.log')
transport.close()

 实现远程连接服务器获取执行命令结果和文件上传下载:

import paramiko
class SSHConnection(object):
    def __init__(self,host='45.199.182.238',port=23424,username='zww',password='123'):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.__k=None
    def run(self):
        self.connect() #连接远程服务器
        self.upload('/root/test.txt','/home/zww/a.txt')#上传本地文件到远端服务器
        self.cmd('df -h')
        self.close() #关闭连接
    def connect(self):
        transport=paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.password)
        self.__transport=transport
    def close(self):
        self.__transport.close()
    def upload(self,local_path,ssh_path):
        sftp=paramiko.SFTPClient.from_transport(self.__transport)
        sftp.put(local_path,ssh_path)
    def cmd(self,command):
        ssh=paramiko.SSHClient()
        ssh._transport=self.__transport
        stdin,stdout,stderr=ssh.exec_command(command)
        print(stdout.read().decode())

obj=SSHConnection()
obj.run()

 另外一种方法实现远程连接主机:

import paramiko, sys, os, socket, select, getpass
from paramiko.py3compat import u
tran = paramiko.Transport(('45.199.182.238', 23424,))
tran.start_client()
tran.auth_password('zww', '123')
# 打开一个通道
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()
while True:
    readable, writeable, error = select.select([chan, sys.stdin, ],[],[],1)
    if chan in readable:
        try:
            x = u(chan.recv(1024))
            if len(x) == 0:
                print('
*** EOF
')
                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()
原文地址:https://www.cnblogs.com/wenwei-blog/p/8590941.html