exec / app.js
aigems's picture
add
3b4170f
raw
history blame
1.66 kB
const express = require('express');
const { Client } = require('ssh2');
const fs = require('fs').promises;
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.post('/execute', async (req, res) => {
const { command } = req.body;
if (!command) {
return res.status(400).json({ error: 'Command is required' });
}
try {
const conn = new Client();
const privateKey = await fs.readFile('/home/user/.ssh/id_rsa');
conn.on('ready', () => {
conn.exec(command, (err, stream) => {
if (err) {
conn.end();
return res.status(500).json({ error: 'Failed to execute command' });
}
let output = '';
stream.on('close', (code, signal) => {
conn.end();
res.json({ output: output.trim(), code });
}).on('data', (data) => {
output += data;
}).stderr.on('data', (data) => {
output += data;
});
});
}).on('error', (err) => {
res.status(500).json({ error: 'SSH connection failed', details: err.message });
}).connect({
host: 'localhost',
port: 2222,
username: 'user',
privateKey
});
} catch (error) {
res.status(500).json({ error: 'Internal server error', details: error.message });
}
});
app.listen(port, '0.0.0.0', () => {
console.log(`Server running on port ${port}`);
});