import { Client } from 'ssh2'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const serverConfig = { host: '222.20.126.217', port: 22, username: 'admini', password: 'zlzxb@1888', remotePath: '/home/admini/ossrpp/base/nginx/dist/SAP/' }; async function uploadDirectory(sftp, localDir, remoteDir) { const items = fs.readdirSync(localDir); // 确保远程目录存在 try { await new Promise((res) => sftp.mkdir(remoteDir, { mode: '0755' }, () => res())); } catch (e) {} for (const item of items) { const localPath = path.join(localDir, item); const remotePath = path.join(remoteDir, item).replace(/\\/g, '/'); // 转换为Linux路径 if (fs.statSync(localPath).isDirectory()) { await uploadDirectory(sftp, localPath, remotePath); } else { await new Promise((resolve, reject) => { console.log(`🚀 上传中: ${item}`); sftp.fastPut(localPath, remotePath, (err) => { if (err) reject(err); else resolve(); }); }); } } } async function startDeploy() { const conn = new Client(); console.log('✨ 开始部署流程...'); conn.on('ready', () => { console.log('✅ SSH 连接成功!'); conn.sftp(async (err, sftp) => { if (err) throw err; try { const localDist = path.join(__dirname, 'SAP'); await uploadDirectory(sftp, localDist, serverConfig.remotePath); console.log('🎉 所有文件上传成功!'); conn.end(); } catch (uploadErr) { console.error('❌ 上传失败:', uploadErr); conn.end(); } }); }).on('error', (err) => { console.error('❌ 连接出错 (检查IP或密码):', err.message); }).on('close', () => { console.log('🔌 连接已关闭'); process.exit(0); }).connect({ host: serverConfig.host, port: serverConfig.port, username: serverConfig.username, password: serverConfig.password, readyTimeout: 10000 // 10秒超时 }); } startDeploy();