paramiko模块

 

paramiko模块封装了ssh,sftp等连接方法,常用于程序构建ssh等连接

 

1. paramiko 连接ssh服务的简单使用

  1.1 连接方式1

# -*- coding:utf-8 -*-
# Author:Wong Du

import paramiko


# 创建SSHClient对象
ssh = paramiko.SSHClient()

# 允许连接不在know_hosts的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# ssh连接服务器
ssh.connect(hostname="10.0.0.105", port=22, username='Caiyun', password='123456')
print("\033[32;1m连接成功了...\033[0m")

# 获取命令的三个返回值标准输入、标准输出、标准错误输出
stdin, stdout, stderr = ssh.exec_command('cats /etc/passwd')
'''
# low one
# print(stdout.read().decode())
# print(stderr.read().decode())
# print(stdout.read().decode()) if stdout.read() else print(stderr.read().decode())
'''
'''
# low two
rightout = stdout.read().decode()
errorout = stderr.read().decode()
print(rightout) if rightout else print(errorout)
'''

# High bige
rightOut, errorOut = stdout.read(), stderr.read()
result = rightOut if rightOut else errorOut
print(result.decode())


ssh.close()

  1.2 连接方式2

# -*- coding:utf-8 -*-
# Author:Wong Du

import paramiko

# 封装ssh连接和认证
transport = paramiko.Transport(('10.0.0.105', 22))
transport.connect(username='Caiyun', password='123456')

# 创建sshClient对象
ssh = paramiko.SSHClient()
# 建立ssh连接
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('cat /etc/passwd')

rightOut, errorOut = stdout.read(), stderr.read()
result = rightOut if rightOut else errorOut # 三元运算
print(result.decode())

 

2. paramiko SFTP服务的简单使用

# -*- coding:utf-8 -*-
# Author:Wong Du


import paramiko

# 封装ssh连接和认证身份
transport = paramiko.Transport( ('10.0.0.105', 22))
transport.connect(username='Caiyun', password='123456')

# 建立连接
sftp = paramiko.SFTPClient.from_transport(transport)

try:
    sftp.put('__init__.py', '/home/Caiyun/TEST/dfdsf')
except Exception as e:
    print('\033[31;1mError\033[0m', e)

transport.close()

 

3. 用key文件认证建立连接

import paramiko

ssh = paramiko.SSHClient()

private_key = paramiko.RSAKey.from_private_key_file('id_rsa')

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())


ssh.connect(hostname='10.0.0.105', port=22, username='Caiyun', pkey=private_key)

stdin, stdout, stderr = ssh.exec_command('df')
rightOut, errorOut = stdout.read(), stderr.read()
result = rightOut if rightOut else errorOut
print(result.decode())

 

posted @ 2018-08-15 17:05  糕事情  阅读(244)  评论(0编辑  收藏  举报