python之基于ssh服务的paramiko模块

1. 使用基于ssh服务的paramiko模块远程连接主机

import paramiko
# ssh username@ip passwd
# 创建一个ssh对象
client = paramiko.SSHClient()
#
# # 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# # 连接的服务器
client.connect(
     hostname='172.25.254.8',
    username='root',
    password='westos'
 )
#
# # 执行操作
# # 标准输入 标准正确输出 标准错误输出
stdin,stdout,stderr = client.exec_command('hostname')
# # 获取命令的执行结果
print(stdout.read().decode('utf-8'))
#
# # 关闭连接
client.close()

在这里插入图片描述

2. paramiko批量远程密码连接

from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
import paramiko
def connect(cmd,hostname,user,password):
    # 创建一个ssh对象
    client = paramiko.SSHClient()
    # 自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        # 连接的服务器
        client.connect(
        hostname=hostname,
        username=user,
        password=password
        )
    except NoValidConnectionsError as e:
        return '主机%s连接失败' %(hostname)
    except AuthenticationException as e:
        return '主机%s密码错误' %(hostname)
    except Exception as e:
        return '未知错误:',e

    # 执行操作
    # 标准输入 标准正确输出 标准错误输出
    stdin,stdout,stderr = client.exec_command(cmd)
    # 获取命令的执行结果
    return stdout.read().decode('utf-8')

    # 关闭连接
    client.close()

with open('hosts') as f:
    for line in f:
        # 172.25.254.254:root:dd
        hostname,username,password = line.strip().split(':')
        res = connect('hostname',hostname,username,password)
        print(hostname.center(50,'*'))
        print('主机名:',res)

在这里插入图片描述

3. 上传和下载文件

(1)上传

import  paramiko
transport = paramiko.Transport(('172.25.254.8', 22))
transport.connect(username='root', password='westos')
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件, 包含文件名
sftp.put('/tmp/xin', '/home/kiosk/Desktop/xin1')  #xin和xin1必须为文件名
transport.close()

在这里插入图片描述
(2)下载

import  paramiko
transport = paramiko.Transport(('172.25.254.8', 22))
transport.connect(username='root', password='westos')
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件, 包含文件名
sftp.get('/home/kiosk/Desktop/xin1', 'xin1')
transport.close()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值