import paramiko

# 设置SSH连接参数
port = 22
username = 'root'
password = 'alpine'

def upload_file(hostname: str, local_path: str, remote_path: str):
    # 创建SSH传输通道
    transport = paramiko.Transport((hostname, port))
    transport.set_keepalive(5)
    # 连接SSH服务端，以用户名和密码进行认证
    transport.connect(username=username, password=password)

    # 创建SFTP客户端
    sftp = paramiko.SFTPClient.from_transport(transport)

    # 上传本地文件到远程主机
    sftp.put(local_path, remote_path)

    print(f"文件 {local_path} 已上传到 {hostname}:{remote_path}")
    
    # 关闭SFTP连接
    sftp.close()

    # 关闭SSH传输通道
    transport.close()

if __name__ == "__main__":
    ips1 = []
    with open("./ips.txt", 'r') as f:
       ips1 = [i.strip() for i in f.readlines()]

    local_path = 'local_file.txt'  # 本地文件路径
    remote_path = '/remote/path/to/file.txt'  # 远程文件路径

    for hostname in ips1:
        try:
            print(hostname)
            upload_file(hostname, local_path, remote_path)
        except Exception as e:
            print(e)
