python学习笔记(paramiko)

本文介绍了Paramiko库在Python中的使用,详细讲解了如何进行远程密码连接、批量连接、读取hosts文件、公钥私钥连接以及文件的上传下载。还提供了对Paramiko的封装,实现SSH远程连接的综合功能。
摘要由CSDN通过智能技术生成

paramiko是什么?

基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件

远程密码连接

import paramiko
# ssh root@172.25.254.250
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 2. 解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 3. 连接服务器
client.connect(
    hostname='172.25.254.1',
    username='root',
    password='westos'
)
# 4. 执行操作
stdin, stdout, stderr = client.exec_command('hostname')
# 5. 获取命令的执行结果;
print(stdout.read().decode('utf-8'))
# 6. 关闭连接
client.close()

批量远程密码连接

from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, user, password):
    import paramiko
    # ssh root@172.25.254.250
    # 创建一个ssh对象;
    client = paramiko.SSHClient()
    # 2. 解决问题:如果之前没有;连接过的ip, 会出现
    # Are you sure you want to continue connecting (yes/no)? yes
    # 自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 3. 连接服务器
        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
    else:
        # 4. 执行操作
        stdin, stdout, stderr = client.exec_command('hostname')
        # 5. 获取命令的执行结果;
        res = stdout.read().decode('utf-8')
        # 6. 关闭连接
        client.close()

        return  res


if __name__ == '__main__':
    with open('doc/hosts.txt') as f:
        for line in f:
            # 172.25.254.1:root:westos
            hostname, username, password = line.split(":")
            res = connect('hostname', hostname, username, password )
            print(hostname.center(50, '*'))
            print("主机名:", res)

写入解析hosts文件中

with open('/etc/hosts', 'a+') as f:
    f.write('\n')
    for i in range(100):
        f.write('172.25.254.%s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值