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)

servers.txt的文本文件中

172.16.20.108,root,123456
172.16.20.90,root,123qwe

你可能感兴趣的:(Python3,system,python)