exec / app.js
aigems's picture
ok
2317df1
raw
history blame
1.75 kB
const express = require('express');
const { Client } = require('ssh2');
const app = express();
const port = 7860;
app.use(express.json());
app.use(express.static('public'));
// 添加根路径处理
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/ssh', async (req, res) => {
const conn = new Client();
try {
await new Promise((resolve, reject) => {
conn.on('ready', resolve)
.on('error', reject)
.connect({
host: 'localhost',
port: 2202,
username: 'user',
password: 'password',
readyTimeout: 5000,
debug: console.log
});
});
console.log('SSH Connection established');
const { stdout, stderr } = await new Promise((resolve, reject) => {
conn.exec(req.body.command, (err, stream) => {
if (err) reject(err);
let stdout = '', stderr = '';
stream.on('close', (code, signal) => {
resolve({ stdout, stderr, code, signal });
}).on('data', (data) => {
stdout += data;
}).stderr.on('data', (data) => {
stderr += data;
});
});
});
conn.end();
res.json({ output: stdout, error: stderr });
} catch (error) {
console.error('SSH error:', error);
res.status(500).json({ error: error.message });
}
});
app.listen(port, () => {
console.log(`Web SSH app listening at http://localhost:${port}`);
});