Files
huishou/deploy-with-key-fixed.js
T
2026-07-27 14:07:26 +08:00

153 lines
4.0 KiB
JavaScript

const { Client } = require('ssh2');
const fs = require('fs');
const privateKey = fs.readFileSync('D:\\Trae\\huishou用户密钥id_ed25519', 'utf8');
const config = {
host: 'hs.yifenbao.cn',
port: 22,
username: 'root',
privateKey: privateKey,
debug: (msg) => { console.log('SSH Debug:', msg); }
};
const conn = new Client();
conn.on('ready', () => {
console.log('SSH连接成功(密钥登录)');
conn.exec('cd /www/huishou && docker-compose down && docker-compose build --no-cache && docker-compose up -d 2>&1', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let output = '';
stream.stdout.on('data', (data) => {
output += data.toString();
process.stdout.write(data);
});
stream.stderr.on('data', (data) => {
output += data.toString();
process.stdout.write(data);
});
stream.on('close', () => {
console.log('\n部署完成');
setTimeout(() => {
conn.exec('docker ps | grep huishou', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let output2 = '';
stream.stdout.on('data', (data) => {
output2 += data.toString();
});
stream.on('close', () => {
console.log('\n=== 容器状态 ===');
console.log(output2);
conn.exec('curl -s http://localhost:4000/api/statistics 2>&1', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
conn.end();
return;
}
let output3 = '';
stream.stdout.on('data', (data) => {
output3 += data.toString();
});
stream.on('close', () => {
console.log('\n=== 统计API响应 ===');
console.log(output3);
conn.end();
});
});
});
});
}, 20000);
});
});
});
conn.on('error', (err) => {
console.error('SSH连接错误:', err.message);
console.log('尝试使用密码登录...');
const pwConfig = {
host: 'hs.yifenbao.cn',
port: 22,
username: 'root',
password: 'Torch1112'
};
const pwConn = new Client();
pwConn.on('ready', () => {
console.log('SSH连接成功(密码登录)');
pwConn.exec('cd /www/huishou && docker-compose down && docker-compose build --no-cache && docker-compose up -d 2>&1', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
pwConn.end();
return;
}
let output = '';
stream.stdout.on('data', (data) => {
output += data.toString();
process.stdout.write(data);
});
stream.stderr.on('data', (data) => {
output += data.toString();
process.stdout.write(data);
});
stream.on('close', () => {
console.log('\n部署完成');
setTimeout(() => {
pwConn.exec('docker ps | grep huishou', (err, stream) => {
if (err) {
console.error('执行命令错误:', err.message);
pwConn.end();
return;
}
let output2 = '';
stream.stdout.on('data', (data) => {
output2 += data.toString();
});
stream.on('close', () => {
console.log('\n=== 容器状态 ===');
console.log(output2);
pwConn.end();
});
});
}, 20000);
});
});
});
pwConn.on('error', (err) => {
console.error('密码登录也失败:', err.message);
});
pwConn.connect(pwConfig);
});
conn.on('end', () => {
console.log('SSH连接已关闭');
});
conn.connect(config);