const { Client } = require('ssh2'); const fs = require('fs'); const path = require('path'); const config = { host: 'hs.yifenbao.cn', port: 22, username: 'root', password: 'Torch1112' }; const conn = new Client(); conn.on('ready', () => { console.log('SSH连接成功'); // 先删除容器内旧文件 conn.exec('docker exec huishou rm -rf /usr/share/nginx/html/h5/*', (err, stream) => { if (err) { console.error('删除容器内文件失败:', err.message); conn.end(); return; } stream.on('close', () => { console.log('容器内旧文件已删除'); // 创建容器内目录 conn.exec('docker exec huishou mkdir -p /usr/share/nginx/html/h5/assets', (err, stream) => { if (err) { console.error('创建容器内目录失败:', err.message); conn.end(); return; } stream.on('close', () => { console.log('容器内目录已创建'); // 上传index.html const indexHtml = fs.readFileSync('./dist/build/h5/index.html', 'utf8'); const base64Index = Buffer.from(indexHtml).toString('base64'); console.log('上传index.html...'); conn.exec(`docker exec huishou bash -c "echo '${base64Index}' | base64 -d > /usr/share/nginx/html/h5/index.html"`, (err, stream) => { if (err) { console.error('上传index.html失败:', err.message); conn.end(); return; } stream.on('close', () => { console.log('index.html上传成功'); // 上传assets目录下的文件 const assetFiles = fs.readdirSync('./dist/build/h5/assets'); let uploaded = 0; assetFiles.forEach(file => { const filePath = `./dist/build/h5/assets/${file}`; const fileContent = fs.readFileSync(filePath); const base64Content = fileContent.toString('base64'); console.log(`上传 ${file}...`); conn.exec(`docker exec huishou bash -c "echo '${base64Content}' | base64 -d > /usr/share/nginx/html/h5/assets/${file}"`, (err, stream) => { if (err) { console.error(`上传 ${file} 失败:`, err.message); } else { stream.on('close', () => { console.log(`${file} 上传成功`); }); } uploaded++; if (uploaded === assetFiles.length) { console.log('\n所有文件上传完成'); // 验证文件 conn.exec('docker exec huishou ls -la /usr/share/nginx/html/h5/assets/', (err, stream) => { let output = ''; stream.stdout.on('data', data => output += data); stream.on('close', () => { console.log('\n容器内assets目录内容:'); console.log(output); // 验证首页JS是否包含"新商户" conn.exec('docker exec huishou grep -o "新商户" /usr/share/nginx/html/h5/assets/pages-index-index*.js | head -5', (err, stream) => { let grepOutput = ''; stream.stdout.on('data', data => grepOutput += data); stream.on('close', () => { console.log('\n验证结果:'); console.log(grepOutput ? '✓ 文件包含"新商户"' : '✗ 文件不包含"新商户"'); conn.end(); }); }); }); }); } }); }); }); }); }); }); }); }); }); conn.on('error', (err) => { console.error('SSH连接错误:', err.message); }); conn.connect(config);