const { Client } = require('ssh2'); const config = { host: 'hs.yifenbao.cn', port: 22, username: 'root', password: 'Torch1112' }; const conn = new Client(); const nginxConfig = `server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.html; location /h5/ { try_files $uri $uri/ /h5/index.html; } location /admin/ { try_files $uri $uri/ /admin/index.html; } location /api/ { proxy_pass http://huishou-backend:4000/api/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /icons/ { proxy_pass http://huishou-backend:4000/icons/; } }`; conn.on('ready', () => { console.log('SSH连接成功'); conn.sftp((err, sftp) => { if (err) { console.error('SFTP连接失败:', err.message); conn.end(); return; } console.log('SFTP连接成功'); const remoteFile = '/www/huishou/admin/nginx.conf'; const writeStream = sftp.createWriteStream(remoteFile, { mode: 0o644 }); writeStream.on('close', () => { console.log('nginx.conf更新成功'); sftp.end(); conn.exec('docker restart huishou', (err, stream) => { if (err) { console.error('重启容器错误:', err.message); conn.end(); return; } stream.on('close', (code) => { console.log('容器重启命令执行完毕, 退出码:', code); setTimeout(() => { conn.exec('docker ps | grep huishou', (err, stream) => { if (err) { console.error('检查容器错误:', err.message); conn.end(); return; } let output = ''; stream.stdout.on('data', (data) => { output += data.toString(); }); stream.on('close', () => { console.log('容器状态:'); console.log(output); conn.end(); }); }); }, 10000); }); }); }); writeStream.on('error', (err) => { console.error('写入文件失败:', err.message); sftp.end(); conn.end(); }); writeStream.write(nginxConfig); writeStream.end(); }); }); conn.on('error', (err) => { console.error('SSH连接错误:', err.message); }); conn.on('end', () => { console.log('SSH连接已关闭'); }); conn.connect(config);