• paramiko 3


    import paramiko
    import concurrent.futures
    
    def execute_remote_command(hostname, username, password, command):
        try:
            # 创建SSH客户端
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
            # 使用密码认证连接远程主机
            client.connect(hostname, username=username, password=password)
    
            # 执行指定的Shell命令
            stdin, stdout, stderr = client.exec_command(command, timeout=10)  # 设置超时时间为10秒
    
            # 输出命令执行结果和主机IP地址
            print(f"在主机 {hostname} 上执行命令: {command}")
            print("--------")
            for line in stdout:
                print(line.strip())
    
            print("--------")
    
            return hostname, True
    
        except paramiko.AuthenticationException:
            print(f"无法连接到主机: {hostname},认证失败。")
            return hostname, False
        except paramiko.ssh_exception.SSHException as e:
            if "timed out" in str(e):
                print(f"在主机 {hostname} 上执行命令超时。")
            else:
                print(f"在主机 {hostname} 上执行命令时出现错误: {str(e)}")
            return hostname, False
        finally:
            if client:
                client.close()
    
    # 从文件中读取服务器信息
    def read_servers_from_file(file_path):
        servers = []
        with open(file_path, 'r') as file:
            for line in file:
                fields = line.strip().split(',')
                if len(fields) == 3:
                    server = {
                        "hostname": fields[0],
                        "username": fields[1],
                        "password": fields[2]
                    }
                    servers.append(server)
        return servers
    
    # 要执行的Shell命令
    command = "ls -l"
    
    # 从文件中读取服务器列表
    servers = read_servers_from_file("servers.txt")
    
    # 调整并发线程池的大小为10
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        futures = {executor.submit(
            execute_remote_command,
            server["hostname"],
            server["username"],
            server["password"],
            command): server["hostname"] for server in servers}
    
        # 获取任务结果
        results = {}
        for future in concurrent.futures.as_completed(futures):
            hostname = futures[future]
            try:
                result = future.result()
                results[hostname] = result[1]
            except Exception as e:
                print(f"在主机 {hostname} 上执行命令时出现错误: {str(e)}")
    
    # 打印连接失败和超时的主机
    print("\n连接失败或超时的主机:")
    for hostname, success in results.items():
        if not success:
            print(hostname)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83

    servers.txt的文本文件

    172.16.20.108,root,123456
    172.16.20.90,root,123qwe
    
    • 1
    • 2

    古老方式

    import paramiko
    import concurrent.futures
    
    def execute_remote_command(hostname, username, password, commands, ip_address):
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(hostname, username=username, password=password)
    
            stdin, stdout, stderr = client.exec_command(commands, timeout=10)
            
            print(f"在主机 {ip_address} 上执行命令: {commands}")
            print("--------")
            for line in stdout:
                print(line.strip())
    
            print("--------")
    
        except paramiko.AuthenticationException:
            print(f"无法连接到主机: {hostname},认证失败。")
        except paramiko.SSHException as e:
            print(f"无法连接到主机: {hostname},错误信息: {str(e)}")
        except paramiko.TransportException as e:
            print(f"无法连接到主机: {hostname},错误信息: {str(e)}")
        except Exception as e:
            print(f"在主机 {ip_address} 上执行命令时出现错误: {str(e)}")
        finally:
            if client:
                client.close()
    
    hosts = [
        {
            "hostname": "172.16.20.108",
            "username": "root",
            "password": "123456",
            "ip_address": "172.16.20.108"
        },
        {
            "hostname": "172.16.20.90",
            "username": "root",
            "password": "123qwe",
            "ip_address": "172.16.20.90"
        },
        {
            "hostname": "172.16.20.166",
            "username": "root",
            "password": "123qwe",
            "ip_address": "172.16.20.166"
        }
    ]
    
    command = "ls -l"
    
    # 使用SSH密钥认证代替密码认证
    # client.load_system_host_keys()
    # client.connect(hostname, username=username, key_filename='path/to/private/key')
    
    pool_size = min(10, len(hosts))  # 调整并发线程池的大小
    commands = "\n".join([f"{command}"] * len(hosts))  # 批量执行相同命令
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=pool_size) as executor:
        futures = []
        for host in hosts:
            future = executor.submit(
                execute_remote_command,
                host["hostname"],
                host["username"],
                host["password"],
                commands,
                host["ip_address"]
            )
            futures.append(future)
    
        concurrent.futures.wait(futures)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
  • 相关阅读:
    斯坦福NLP课程来了
    霍尔效应风扇驱动IC
    论文阅读笔记 | 三维目标检测——AVOD算法
    Linux常见命令总结
    个人主页汇总 | 私信没空看,建议b站
    OkHttp原理解析
    云计算时代的等保测评挑战和应对策略
    No150.精选前端面试题,享受每天的挑战和学习
    lintcode 584 · 丢鸡蛋II 【中等 vip 动态规划】
    Java线程池-简识
  • 原文地址:https://blog.csdn.net/weixin_42562106/article/details/133440373