Answer the question
In order to leave comments, you need to log in
Asynchronous functions in a for in/forEach loop, which is correct?
Hello!
I want to loop through the ip list through node.js, connect to each via ssh and remove the information.
I'm using the npm "simple-ssh" package:
const SSH = require('simple-ssh');
const hosts = ['192.168.10.1', '192.168.20.1',];
hosts.forEach(function (ip) {
//console.log(ip);
const ssh = new SSH({
host: ip,
port: '22',
user: 'root',
pass: 'password'
});
ssh
.exec('cat /proc/uptime', {
out: function(stdout) {
console.log(hosts);
console.log(stdout);
}
})
.start();
});
Answer the question
In order to leave comments, you need to log in
Here is a post on the topic (in English)
Try something like this (did not check)
const SSH = require('simple-ssh');
const hosts = ['192.168.10.1', '192.168.20.1',];
async function processIPs(ipArr) {
for (ip of hosts) {
//console.log(ip);
const ssh = new SSH({
host: ip,
port: '22',
user: 'root',
pass: 'password'
});
const pr = new Promise((res, rej) => {
ssh
.exec('cat /proc/uptime', {
out: function(stdout) {
res(stdout);
}
})
.start();
});
const result = await pr;
console.log("ip: %s, result: %s", ip, result);
}
});
processIPs (hosts);
console.log("Done");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question