94 lines
2.5 KiB
JavaScript
94 lines
2.5 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();
|
|
|
|
const localDir = path.join(__dirname, 'dist', 'build', 'h5');
|
|
const remoteDir = '/www/huishou/dist/build/h5';
|
|
|
|
conn.on('ready', () => {
|
|
console.log('SSH连接成功');
|
|
|
|
// 先删除服务器上的旧文件
|
|
conn.exec(`rm -rf ${remoteDir}/*`, (err, stream) => {
|
|
if (err) {
|
|
console.error('删除旧文件失败:', err.message);
|
|
conn.end();
|
|
return;
|
|
}
|
|
|
|
stream.on('close', () => {
|
|
console.log('旧文件已删除');
|
|
|
|
conn.sftp((err, sftp) => {
|
|
if (err) {
|
|
console.error('SFTP连接失败:', err.message);
|
|
conn.end();
|
|
return;
|
|
}
|
|
|
|
const uploadFile = (localPath, remotePath) => {
|
|
return new Promise((resolve, reject) => {
|
|
sftp.fastPut(localPath, remotePath, (err) => {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve();
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
const uploadDir = async (dir, remoteBase) => {
|
|
const files = fs.readdirSync(dir, { withFileTypes: true });
|
|
for (const file of files) {
|
|
const localPath = path.join(dir, file.name);
|
|
const remotePath = `${remoteBase}/${file.name}`;
|
|
|
|
if (file.isDirectory()) {
|
|
await new Promise((resolve) => {
|
|
conn.exec(`mkdir -p ${remotePath}`, (err, stream) => {
|
|
stream.on('close', resolve);
|
|
});
|
|
});
|
|
await uploadDir(localPath, remotePath);
|
|
} else {
|
|
console.log(`上传: ${file.name}`);
|
|
await uploadFile(localPath, remotePath);
|
|
}
|
|
}
|
|
};
|
|
|
|
uploadDir(localDir, remoteDir)
|
|
.then(() => {
|
|
console.log('\n所有文件上传完成');
|
|
|
|
conn.exec('docker restart huishou', (err, stream) => {
|
|
stream.on('close', () => {
|
|
console.log('容器已重启');
|
|
conn.end();
|
|
});
|
|
});
|
|
})
|
|
.catch((err) => {
|
|
console.error('上传失败:', err);
|
|
conn.end();
|
|
});
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
conn.on('error', (err) => {
|
|
console.error('SSH连接错误:', err.message);
|
|
});
|
|
|
|
conn.connect(config); |