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('mkdir -p /tmp/huishou-h5', (err, stream) => { stream.on('close', () => { console.log('临时目录已创建'); conn.sftp((err, sftp) => { if (err) { console.error('SFTP连接失败:', err.message); conn.end(); return; } const localDir = path.join(__dirname, 'dist', 'build', 'h5'); // 先上传index.html sftp.fastPut(`${localDir}/index.html`, '/tmp/huishou-h5/index.html', (err) => { if (err) { console.error('index.html上传失败:', err.message); conn.end(); return; } console.log('index.html上传成功'); // 创建assets目录 conn.exec('mkdir -p /tmp/huishou-h5/assets', (err, stream) => { stream.on('close', () => { const assetsDir = `${localDir}/assets`; fs.readdir(assetsDir, (err, files) => { if (err) { console.error('读取assets目录失败:', err.message); conn.end(); return; } let uploaded = 0; files.forEach(file => { const localPath = `${assetsDir}/${file}`; const remotePath = `/tmp/huishou-h5/assets/${file}`; sftp.fastPut(localPath, remotePath, (err) => { if (err) { console.error(`${file}上传失败:`, err.message); } else { console.log(`${file}上传成功`); } uploaded++; if (uploaded === files.length) { console.log('\n所有文件上传到临时目录完成'); // 使用docker cp复制到容器 conn.exec('docker cp /tmp/huishou-h5/. huishou:/usr/share/nginx/html/h5/', (err, stream) => { if (err) { console.error('docker cp失败:', err.message); conn.end(); return; } stream.on('close', () => { console.log('文件已复制到容器'); // 验证 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); conn.exec('docker exec huishou grep -o "新商户" /usr/share/nginx/html/h5/assets/pages-index-index*.js | head -3', (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);