I'm running protractor on my windows VM and need to execute some commands on a linux VM. I'm trying to use SSH to do the same. I've tried using 'simple-ssh', 'remote-exec' and 'ssh-exec. The problem with all of them is the same, the protractor test completes without any error but the SSH connection is not established. Strangely it doesn't throw any error as well, I've tried giving wrong IP, but still, no error is thrown. I've tried SSH over python with same machine, it works flawlessly.
here is a piece of code from documentation that I directly tried to use.
var ssh = new SSH({
host: 'xx.xx.xxx.xx',
user: 'xxxxx',
pass: 'xxxxx'
});
ssh.exec('ls -lh', {
out: function(stdout) {
console.log(stdout);
}
}).start();
Figured it out.
I used ssh2 package to establish an interactive SSH session. Then I synchronized it with jasmine using done() in jasmine 2.
Used Maciej Ciach's solution for solving sync problem.
Here's an 'It' block that runs flawlessly
it("trying ssh connection", function (done) {
var conn = new Client();
conn.on('ready', function () {
console.log('Client :: ready');
conn.shell(function (err, stream) {
if (err) throw err;
stream.on('close', function () {
console.log('Stream :: close');
conn.end();
}).on('data', function (data) {
console.log('OUTPUT: ' + data);
});
stream.end('ls \nexit\n');
done();
});
}).connect({
host: 'xx.xx.xxx.xx',
port: 22,
username: 'x',
privateKey: require('fs').readFileSync('file_path')
});
})
Obviously, you need to add your public ssh key to the list of trusted keys on your server first.
You can read about it here.
If you are on windows then execute those commands in Powershell.
Related
I'm currently learning how to setup a node server and I'm making an API that performs some requests on my MariaDB database hosted on my VPS.
The problem is that when I make a POST request which makes a SQL request to the database, the connection times out and the server shuts down.
I have tried to add new users to MariaDB with all privileges, I tried use sequelize too.
But none of those solutions work, it still times out every time I make a query to my database.
I can connect to phpmyadmin and make some request on it, so I think that my database is running fine.
Here is my code:
router.post('/login', async function(req,res) {
let conn;
try {
// establish a connection to MariaDB
conn = await pool.getConnection();
// create a new query
var query = "select * from people";
// execute the query and set the result to a new variable
var rows = await conn.query(query);
// return the results
res.send(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
})
The way I connect to my database in my database.js file
const pool = mariadb.createPool({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABSE_NAME,
});
// Connect and check for errors
module.exports={
getConnection: function(){
return new Promise(function(resolve,reject){
pool.getConnection().then(function(connection){
resolve(connection);
}).catch(function(error){
reject(error);
});
});
}
}
module.exports = pool;
And my error:
Node.js v17.0.1
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server started
/Users/alexlbr/WebstormProjects/AlloEirb/server/node_modules/mariadb/lib/misc/errors.js:61
return new SqlError(msg, sql, fatal, info, sqlState, errno, additionalStack, addHeader);
^
SqlError: retrieve connection from pool timeout after 10001ms
at Object.module.exports.createError (/Users/alexlbr/WebstormProjects/AlloEirb/server/node_modules/mariadb/lib/misc/errors.js:61:10)
at timeoutTask (/Users/alexlbr/WebstormProjects/AlloEirb/server/node_modules/mariadb/lib/pool-base.js:319:16)
at Timeout.rejectAndResetTimeout [as _onTimeout] (/Users/alexlbr/WebstormProjects/AlloEirb/server/node_modules/mariadb/lib/pool-base.js:342:5)
at listOnTimeout (node:internal/timers:559:11)
at processTimers (node:internal/timers:500:7) {
text: 'retrieve connection from pool timeout after 10001ms',```
Three possibilities come to mind:
There is a typo in database name:
database: process.env.DATABSE_NAME
database: process.env.DATABASE_NAME
Your environment variables are not being properly set. Are you using dotenv to load these from an .env file?
https://www.npmjs.com/package/dotenv
If not, how are you setting the process.env values at runtime?
If the environment values are indeed set:
verify that these environment values are correct
verify which interface your MariaDB server is listening on:
It's possible the server is using a bind-address configuration and only listening on 127.0.0.1 (which is the default on Debian/Ubuntu)
You want to make sure the server is listening on: 0.0.0.0 (all interfaces, not only localhost)
I´m pretty new in the whole JS and node.js and npm thing and im trying to use a mqtt broker in a project I have for a class, so I installed the mqtt module from npm and to give me an idea of how it works I ran the example in the npm page but it doesn´t seem to work, it just hangs without ever printing the "hello mqtt" it says it should? im sure im missing something but i really don´t know what.
The code is:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
the page I got it from is https://www.npmjs.com/package/mqtt
i also tried using my own broker but it also doesnt work.
This could be so many things, but the most likely is that you are failing to connect to the broker.
The sample code has no error handling at all so it's not going to tell you when it fails to connect. Try the following code which should tell you what's going on.
var mqtt = require('mqtt')
var options = {
connectTimeout: 10000
};
var client = mqtt.connect('mqtt://test.mosquitto.org',options)
client.on('connect', function () {
console.log("connected");
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('error', function(err){
console.log("error %j", err);
});
client.on('close',function(){
console.log("client disconnected");
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I've wound the connection timeout down to 10 seconds from the default 30 so you can see it fail quicker.
I im using the following code to manage my server (install, reinstall, restart, shutdown etc...)
/* SERVER - type */
switch(server.type) {
/* INFO - server */
case 1:
/* MANAGE - ssh login */
conn.on('ready', function() {
/* MANAGE - info */
conn.exec('uptime && cat /proc/cpuinfo', function(err, stream) {
stream.on('close',function(code, signal) {
/* MANAGE - info */
console.log('server info closed...');
conn.end();
}).on('data', function(data) {
console.log('server info...'+data);
conn.end();
}).on('error', function(err) {
console.log('server error...'+err);
conn.end();
})
})
}).connect({
host: '192.168.1.1',
port: '22',
username: 'root',
password: 'myserverpass'
})
})
break;
}
Problem is that when this exeuctes i get from console.log correct data and after i get data it contiunues to execute in loop from beginning so i need to get only this only once:
console.log('server info...'+blablabla);
and i get this:
console.log('server info...'+blablabla);
console.log('server info...'+blablabla);
console.log('server info...'+blablabla);
console.log('server info...'+blablabla);
console.log('server info...'+blablabla);
so how can i exit from switch when command is successfuly execute so that command does not get into loop?
I im using this to connect throught SSH on node:
https://github.com/mscdex/ssh2
I have previus used switch case statement and no problem executing in loop...i was thinking that ssh2 need return or conn.end() event to exit from loop?
Switch cases don't loop on their own. So your switch case must be inside a loop that is causing it to be run more than once. As the code loops if any cases match those cases will be triggered on each loop.
You're best bet is to put your connection into a function and call it inside you loop only if the connection has not already been made. This way you can have one simple script that handles connections and all you have to do is pass the connoection params to the function.
I am trying to understand about the SSH2 for nodeJS https://github.com/mscdex/ssh2, but I can't find more documentation, does anybody has more related to the client events?
I am trying to connect from my Node project to a Unix server and execute commands from node using this library SSH2 such as mkdir, ls or some other unix commands but I can't find any documentation of how to do it.
I am able to establish connection, but now I need to execute unix commands
var Client = require('ssh2').Client;
//
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
console.log('Client :: SSH open');
output.add("ls");
conn.end();
});
}).connect({
host: 'hostname',
port: 22,
username: 'user',
password: 'password'
});
Or if this is not achievable with SSH2 can somebody recommend another Node Library were I can connect to an unix server? I have a Node application that creates a HTML file but after the creation I need to name it in base of the last file name that I have in a unix server, create the directory in unix and the upload it using sftp-upload plugin. Trying to achieve this with node instead of doing manually.
You can do this with node-exec or ssh2-exec which uses ssh2. ssh2 is low level so for exec you can use other libs like ssh2-exec and ssh2-connect.
There are plenty of examples in README.md.
Example (from ssh2-exec README):
connect = require('ssh2-connect');
exec = require('ssh2-exec');
connect({host: localhost}, function(err, ssh){
child = exec({cmd: 'ls -la', ssh: ssh}, function(err, stdout, stderr){
console.log(stdout);
});
child.stdout.on('data', function(data){
console.log(stdout);
});
child.on('exit', function(code){
console.log('Exit', code);
});
})
I am running my node.js server by forever and my script gets killed in 1-2 days and i get this error in the log file:
error: Forever detected script was killed by signal: SIGSEGV
Now i have many functions in my node.js script. Upon writing a console.log at the beginning of each function i ended up getting this in the log:
info: transport end (undefined)
debug: set close timeout for client CbU1mvlYaIvDWHB4ChQa
debug: cleared close timeout for client CbU1mvlYaIvDWHB4ChQa
disconnection function
debug: discarding transport
debug: clearing poll timeout
debug: client authorized
info: handshake authorized 2O3m1B3dGWFOJ4W9ChQc
error: Forever detected script was killed by signal: SIGSEGV
the log makes it seem as if either the connect or the disconnect function has a problem, but as the script seg faults after 2 days of running and over 10000 connections/disconnections i think that that might not be really the problem.
Here are my connection and disconnection functions. i also connect to my pgsql database via node-dbi:
var DBWrapper = require('node-dbi').DBWrapper;
var DBExpr = require('node-dbi').DBExpr;
var dbConnectionConfig = { host: 'localhost', user: 'user', password: 'pass', database: 'dbname' };
dbWrapper = new DBWrapper( "pg", dbConnectionConfig );
dbWrapper.connect();
io.sockets.on('connection', function(socket) {
console.log("socket connection");
socket.on('set username', function(userName) {
var milliseconds = (new Date).getTime();
var data = { socketid: socket.id, time: milliseconds };
dbWrapper.insert('all_sockets', data , function(err) {
});
});
socket.on('disconnect', function() {
console.log("disconnection function");
dbWrapper.remove('all_sockets', [['socketid=?', socket.id]] , function(err) {} );
});
});
where could the segment fault be coming from?
I would recommend using a segfault handler to determine the STDERR. This way you will have some more useful debug info.
You can find one here