[ADD]Server : first SSH2 client / connection
This commit is contained in:
parent
a9734f32c2
commit
596105fa9a
@ -17,7 +17,8 @@
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"polka": "^0.5.2",
|
||||
"sirv": "^0.4.0"
|
||||
"sirv": "^0.4.0",
|
||||
"ssh2": "^0.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.4.4",
|
||||
|
51
server.js
51
server.js
@ -6,12 +6,59 @@ const http = require('http');
|
||||
const { join } = require('path');
|
||||
const polka = require('polka');
|
||||
const sirv = require('sirv');
|
||||
const { json } = require('body-parser');
|
||||
const sshClient = require('ssh2').Client;
|
||||
|
||||
const { PORT=3000 } = process.env;
|
||||
const files = sirv('dist');
|
||||
const files = sirv('dist', {dev: true});
|
||||
const server = http.createServer();
|
||||
|
||||
polka({ server }).use(files).listen(PORT, err => {
|
||||
let sshConn;
|
||||
|
||||
const sendJSON = (res, httpCode, message) => {
|
||||
res.writeHead(httpCode, { 'Content-Type': 'application/json' });
|
||||
return JSON.stringify(message);
|
||||
};
|
||||
|
||||
const connect = (req, res) => {
|
||||
console.log(req.body);
|
||||
if (!req.body.address.length || !req.body.username.length ||
|
||||
!req.body.port.length || !req.body.key.length) {
|
||||
res.end(sendJSON(res, 500, 'Erreur : un champ requis manque.'));
|
||||
}
|
||||
sshConn = new sshClient();
|
||||
try {
|
||||
sshConn.on('ready', () => {
|
||||
console.log('Client :: ready');
|
||||
res.end(sendJSON(res, 200, 'OK, connected!'));
|
||||
}).connect({
|
||||
host: req.body.address,
|
||||
port: req.body.port,
|
||||
username: req.body.username,
|
||||
privateKey: req.body.key,
|
||||
passphrase: req.body.password
|
||||
});
|
||||
sshConn.on('error', (err) => {
|
||||
console.log(err);
|
||||
res.end(sendJSON(res, 403, err.message));
|
||||
});
|
||||
}
|
||||
catch(err) {
|
||||
console.log(err);
|
||||
res.end(sendJSON(res, 403, err.message));
|
||||
}
|
||||
};
|
||||
|
||||
const disconnect = (req, res) => {
|
||||
sshConn.end();
|
||||
res.end(sendJSON(res, 200, 'OK, disconnected!'));
|
||||
};
|
||||
|
||||
polka({ server })
|
||||
.use(json(), files)
|
||||
.post('/connect', connect)
|
||||
.get('/disconnect', disconnect)
|
||||
.listen(PORT, err => {
|
||||
if (err) throw err;
|
||||
console.log(`> Running on localhost:${PORT}`);
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user