120 lines
3.2 KiB
JavaScript
120 lines
3.2 KiB
JavaScript
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连接成功');
|
|
|
|
const localH5Dir = path.join(__dirname, 'dist', 'build', 'h5');
|
|
|
|
// 读取本地文件列表
|
|
const fileList = [];
|
|
const collectFiles = (dir) => {
|
|
const items = fs.readdirSync(dir, { withFileTypes: true });
|
|
for (const item of items) {
|
|
const fullPath = path.join(dir, item.name);
|
|
if (item.isDirectory()) {
|
|
collectFiles(fullPath);
|
|
} else {
|
|
fileList.push({
|
|
local: fullPath,
|
|
rel: path.relative(localH5Dir, fullPath).replace(/\\/g, '/')
|
|
});
|
|
}
|
|
}
|
|
};
|
|
collectFiles(localH5Dir);
|
|
|
|
console.log(`找到 ${fileList.length} 个文件`);
|
|
|
|
// 创建远程目录结构
|
|
const createDirs = () => {
|
|
const dirs = new Set();
|
|
fileList.forEach(f => {
|
|
const dir = f.rel.substring(0, f.rel.lastIndexOf('/'));
|
|
if (dir) dirs.add(dir);
|
|
});
|
|
|
|
return new Promise((resolve) => {
|
|
let pending = dirs.size + 1;
|
|
dirs.forEach(dir => {
|
|
conn.exec(`mkdir -p /www/huishou/dist/build/h5/${dir}`, (err, stream) => {
|
|
stream.on('close', () => {
|
|
pending--;
|
|
if (pending === 0) resolve();
|
|
});
|
|
});
|
|
});
|
|
pending--;
|
|
if (pending === 0) resolve();
|
|
});
|
|
};
|
|
|
|
createDirs().then(() => {
|
|
console.log('目录结构已创建');
|
|
|
|
conn.sftp((err, sftp) => {
|
|
if (err) {
|
|
console.error('SFTP连接失败:', err.message);
|
|
conn.end();
|
|
return;
|
|
}
|
|
|
|
let uploaded = 0;
|
|
let errors = [];
|
|
|
|
fileList.forEach(file => {
|
|
const remotePath = `/www/huishou/dist/build/h5/${file.rel}`;
|
|
|
|
sftp.fastPut(file.local, remotePath, (err) => {
|
|
if (err) {
|
|
errors.push({ file: file.rel, error: err.message });
|
|
} else {
|
|
console.log(`✓ ${file.rel}`);
|
|
}
|
|
|
|
uploaded++;
|
|
if (uploaded === fileList.length) {
|
|
console.log(`\n上传完成: ${fileList.length - errors.length}/${fileList.length}`);
|
|
if (errors.length > 0) {
|
|
console.log('错误列表:');
|
|
errors.forEach(e => console.log(` ✗ ${e.file}: ${e.error}`));
|
|
}
|
|
|
|
// 验证上传
|
|
conn.exec('ls -la /www/huishou/dist/build/h5/assets/ | head -10', (err, stream) => {
|
|
let output = '';
|
|
stream.stdout.on('data', data => output += data);
|
|
stream.on('close', () => {
|
|
console.log('\n服务器assets目录内容:');
|
|
console.log(output);
|
|
|
|
conn.exec('docker restart huishou', (err, stream) => {
|
|
stream.on('close', () => {
|
|
console.log('\n容器已重启');
|
|
conn.end();
|
|
});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
});
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
conn.on('error', (err) => {
|
|
console.error('SSH连接错误:', err.message);
|
|
});
|
|
|
|
conn.connect(config); |