paramiko远程连接以及批量远程连接

本文介绍如何利用Python库Paramiko实现SSH远程服务器的自动化管理,包括远程执行命令、上传及下载文件等操作,通过示例代码展示了批量连接及执行命令的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.strip().split(":")
            res = connect('hostname', hostname, username, password )
            print(hostname.center(50, '*'))
            print("主机名:", res)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值