import os import paramiko def upload_files(sftp, local_path, remote_path): # 遍历本地目录 for root, dirs, files in os.walk(local_path): # 排除 __pycache__ 目录 if '__pycache__' in dirs: dirs.remove('__pycache__') # 打印当前目录和文件 print(f"当前目录: {root}") print(f"已上传的文件: {files}") for file in files: local_file = os.path.join(root, file) # 计算相对路径 relative_path = os.path.relpath(local_file, local_path) # 计算远程文件路径 remote_file = os.path.join(remote_path, relative_path).replace("\\", "/") # 保留目录结构 # 创建远程目录 remote_dir = os.path.dirname(remote_file) try: # 创建所有必要的远程目录 sftp.mkdir(remote_dir) print(f"创建远程目录: {remote_dir}") except IOError: # 目录已存在,忽略错误 print(f"Remote directory already exists: {remote_dir}") # 上传文件 try: sftp.put(local_file, remote_file) print(f"已上传: {local_file} to {remote_file}") except Exception as e: print(f"Failed to upload {local_file} to {remote_file}: {e}") def execute_remote_command(ssh, command): stdin, stdout, stderr = ssh.exec_command(command) print(stdout.read().decode()) print(stderr.read().decode()) def main(): # SFTP 连接信息 #hostname = '10.10.14.250' hostname = 'www.wmarkj.com' #port = 22 port = 27250 username = 'root' #password = 'dsideal' password='DsideaL4r5t6y7u' remote_path = '/usr/local/SyncData' venv_path = '/usr/local/SyncData/venv' # 虚拟环境路径 # 创建 SSH 客户端 transport = paramiko.Transport((hostname, port)) try: transport.connect(username=username, password=password) except Exception as e: print(f"Failed to connect to SFTP server: {e}") return # 创建 SFTP 客户端 sftp = paramiko.SFTPClient.from_transport(transport) try: # 获取当前目录 local_path = os.getcwd() print(f"本地路径: {local_path}") # 上传文件 upload_files(sftp, local_path, remote_path) print("文件上传完成") # 创建 SSH 客户端 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname, port, username, password) # 创建虚拟环境 create_venv_command = f'python3 -m venv {venv_path}' execute_remote_command(ssh, create_venv_command) # 激活虚拟环境并安装依赖 cmd = f'{venv_path}/bin/pip install -r {remote_path}/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple' execute_remote_command(ssh, cmd) # 构建镜像 #cmd = 'cd /usr/local/SyncData && docker build --no-cache --build-arg PYTHON_VERSION=3.10 --build-arg APP_ENV=prod -t data-sync-service:1.0 .' #execute_remote_command(ssh, cmd) #print("构建镜像完成") # 启动镜像 #cmd = 'docker run -d --rm data-sync-service:1.0' #execute_remote_command(ssh, cmd) #print("部署完成") finally: # 关闭 SFTP 和 SSH 连接 sftp.close() transport.close() ssh.close() if __name__ == "__main__": main()