several connection to the same server via telnet (script js) - javascript

i'm far to be an expert in js, so be indulgeous.
i'm trying to write a script in js for opening several connection (10 here) from one server to another one via telnet protocol.
Here is my script :
const {
readFileSync
} = require('fs');
//const { Client } = require('telnet-client');
const {
Telnet
} = require('telnet-client');
const conn = (nb) => {
const conn = new Telnet();
conn.on('ready', () => {
console.log(`[${nb}]`, 'Client :: ready');
conn.shell((err, stream) => {
if (err) {
console.log(err);
throw err;
}
stream.on('close', () => {
console.log(`${nb}`, 'Stream :: close');
conn.end();
}).on('data', (data) => {
console.log(`${nb}`, "OUTPUT: " + data);
});
stream.end('sleep 600\n');
});
}).connect({
host: 'srvAP',
port: 23,
username: 'toto',
password: 'toto'
});
}
Array.from(Array(10)).forEach(async(x, nb) => {
let now = Date.now();
setTimeout(function() {
console.log("Sleep ", nb);
console.log(`${nb}`, "Run conn " + nb);
conn(nb);
console.log("Sleep end ", nb, Date.now() - now);
}, nb * 750);
});
When i launch it i have some errors :
/exploit/tmp/SLE/poc_vega-ssh-load/node_modules/telnet-client/lib/index.js:130
return reject(new Error('Cannot connect'));
^
Error: Cannot connect
at Socket.<anonymous> (/exploit/tmp/SLE/poc_vega-ssh-load/node_modules/telnet-client/lib/index.js:130:35)
at Object.onceWrapper (node:events:627:28)
at Socket.emit (node:events:513:28)
at Socket._onTimeout (node:net:550:8)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
Do you have an idea or for correcting this error, or for helping me writing a (more) simple script to do what i want?

Related

Get unread gmail mails with imap

Hello I'm trying to iplement some basics Google Api features and I get some issues when I try to get the unread messages in the gmail mailbox. Here is my code:
require('dotenv').config();
const nodemailer = require('nodemailer')
const { google } = require('googleapis')
const Imap = require('imap');
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET
const REDIRECT_URI = process.env.GOOGLE_REDIRECT_URL
const REFRESH_TOKEN = process.env.GOOGLE_REFRESH_TOKEN
const oauht2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
oauht2Client.setCredentials({refresh_token : REFRESH_TOKEN})
function newMessages(/*onNewEmailCallback*/) {
const imap = new Imap({
user: "mymail#gmail.com",
xoauth2: oauht2Client.getAccessToken(),
host: 'imap.gmail.com',
port: 993,
tls: true,
tlsOptions: {
rejectUnauthorized: false
}
});
function showError(error) {
console.error('Error:', error);
}
function showMessage(msg) {
onNewEmailCallback(msg.subject);
console.log(msg.subject);
}
imap.connect();
imap.once('ready', () => {
imap.openBox('INBOX', true, (err, box) => {
if (err) showError(err);
imap.on('mail', (numNewMsgs) => {
imap.search(['UNSEEN'], (err, results) => {
if (err) showError(err);
results.forEach((result) => {
const f = imap.fetch(result, { bodies: '' });
f.on('message', (msg) => {
msg.on('body', (stream, info) => {
let buffer = '';
stream.on('data', (chunk) => {
buffer += chunk.toString('utf8');
});
stream.on('end', () => {
showMessage(Imap.parseHeader(buffer));
});
});
});
});
});
});
});
});
imap.once('error', showError);
imap.once('end', () => {
console.log('Connection terminée');
});
return imap;
}
When I call it in the index.js I get the error
/home/.../node_modules/imap/lib/Connection.js:1804
return str.replace(RE_BACKSLASH, '\\\\').replace(RE_DBLQUOTE, '\\"');
^
TypeError: str.replace is not a function
at escape
I'm probably passing a bad argument during the imap connection but I don't really know which one and I don't find anything online. Help PLEASE
By the way I had a certificate issue that's why I add the tlsOptions property.
Here the full traceback of the error:
/home/lerou/B-DEV-500-COT-5-2-area-segnon.gnonlonfoun/Back-End/node_modules/imap/lib/Connection.js:1804
return str.replace(RE_BACKSLASH, '\\\\').replace(RE_DBLQUOTE, '\\"');
^
TypeError: str.replace is not a function
at escape (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1804:14)
at Connection.<anonymous> (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1672:24)
at Connection._resTagged (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1535:22)
at Parser.<anonymous> (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:194:10)
at Parser.emit (node:events:512:28)
at Parser._resTagged (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:175:10)
at Parser._parse (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:139:16)
at Parser._tryread (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:82:15)
at Parser._cbReadable (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:53:12)
at TLSSocket.emit (node:events:512:28)

How to open port to access API on nodejs

I am trying to access the Looker API of a self-hosted instance. I am very new to nodejs and not sure how to go about this. THis is the error I am getting:
node:_http_outgoing:742
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:372:5)
at write_ (node:_http_outgoing:742:11)
at ServerResponse.write (node:_http_outgoing:707:15)
at Server.<anonymous> (/Users/the_user/Dropbox/products/LookerBot/index.js:63:13)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17) {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v17.9.0
This is what I tried:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
const axios = require('axios');
const qs = require('qs');
const slack_key = 'xoxb-12345';
const looker_client_id = 'GDKGKDRHJGKR123';
const looker_client_secret = 'sdfgfd6789'
const looker_url = `https://mylooker.cloud.looker.com:19999/client_id=${looker_client_id}&client_secret=${looker_client_secret}`;
let dict = {
"url": "https://mylooker.cloud.looker.com",
"apiBaseUrl": looker_url,
'clientId': looker_client_id,
'clientSecret': looker_client_secret
}
console.log(dict)
axios.get(looker_url, {}, {
'client_id': looker_client_id,
'client_secret': looker_client_secret
})
.then(response => console.log(response))
.catch(error => console.log(error))
let slack_API = 'https://slack.com/api';
let the_text = new URL('https://mylooker.cloud.looker.com/x/123456789');
const greet = () => {
let messageArgs = {
token: slack_key,
channel: '#testing',
text: the_text.toString()
};
post(messageArgs);
};
const post = async (args) => {
const result = await axios.post(`${slack_API}/chat.postMessage`, qs.stringify(args));
try {
console.log(result.data);
} catch (e) {
console.log(e);
}
};
greet();
response.write(request.looker_url);
response.end();
}).listen(19999);
I am trying to create lookerbot and need to build a simple Node.js application. The application needs to be able to reach, both, my Looker instance's API and Slack's API. I am trying to open up port 19999 in order to accesss the Looker API.
What am I doing wrong?

Unable to switch user to root using Node.js ssh2 module

Trying to SSH to a server and able to. However, when I try to run sudo command it prompts me to enter the password of the userid mentioned. How do I prevent any keyboard interruption and hardcode the password so it doesn't prompt for password.
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'password\n', pty: true }, (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'user1',
password: 'password'
});
The prompt I get:
STDOUT: [sudo] password for user1:
STDOUT:
sudo: timed out reading password
The below code works for me.
const Client = require('ssh2').Client;
const conn = new Client();
const encode = 'utf8';
const connection = {
host: 'hostname.foo.com',
username: 'iamgroot',
password: 'root#1234'
}
conn.on('ready', function() {
// Avoid the use of console.log due to it adds a new line at the end of
// the message
process.stdout.write('Connection has been established');
let password = 'root#1234';
let command = '';
let pwSent = false;
let su = false;
let commands = [
`ls -lrt`,
`sudo su - root`,
`ls -lrt`
];
conn.shell((err, stream) => {
if (err) {
console.log(err);
}
stream.on('exit', function (code) {
process.stdout.write('Connection closed');
conn.end();
});
stream.on('data', function(data) {
process.stdout.write(data.toString(encode));
// Handles sudo su - root password prompt
if (command.indexOf('sudo su - root') !== -1 && !pwSent) {
if (command.indexOf('sudo su - root') > -1) {
su = true;
}
if (data.indexOf(':') >= data.length - 2) {
pwSent = true;
stream.write(password + '\n');
}
} else {
// Detect the right condition to send the next command
let dataLength = data.length > 2;
let commonCommand = data.indexOf('$') >= data.length - 2;
let suCommand = data.indexOf('#') >= data.length - 2;
console.log(dataLength);
console.log(commonCommand);
console.log(suCommand);
if (dataLength && (commonCommand || suCommand )) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command + '\n');
} else {
// su requires two exit commands to close the session
if (su) {
su = false;
stream.write('exit\n');
} else {
stream.end('exit\n');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command + '\n');
});
}).connect(connection);

Error while trying to get data from table

'// Issue: Not able to fetch data from table.
// My Code
const sql = require('mssql/msnodesqlv8');
const poolPromise = new sql.ConnectionPool({
driver: 'msnodesqlv8',
server: "test.database.windows.net",
user: "username",
password: "password",
database: 'database',
port: 1433,
})
.connect()
.then((pool: any) => {
console.log('Connected to MSSQL')
return pool
})
.catch((err: any) => console.log('Database Connection Failed! Bad Config: ', err))
;
describe('any test', () => {
it('verification', async () => {
try
{
const pool = await poolPromise;
const result = await pool.request()
.query('select * from table where username = "Protractor"');
console.log(result);
}
catch(err)
{
console.log(err);
}
});
});
Error Occurred:
[13:20:25] I/launcher - Running 1 instances of WebDriver
[13:20:25] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Started
Connected to MSSQL
{ RequestError: Invalid column name 'Protractor'.
at handleError (C:\Users\automation\node_modules\mssql\lib\msnodesqlv8\request.js:258:21)
at StreamEvents.emit (events.js:189:13)
at errors.forEach.err (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:37:20)
at Array.forEach ()
at routeStatementError (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:30:14)
at invokeObject.end (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:209:11)
at freeStatement (C:\Users\automation\node_modules\msnodesqlv8\lib\driver.js:183:13)
at cppDriver.freeStatement (C:\Users\automation\node_modules\msnodesqlv8\lib\driver.js:163:13) originalError:
{ Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Protractor'. sqlstate: '42S22', code: 207 },
name: 'RequestError',
number: 207,
state: '42S22' }
Double and single quotes are not interchangeable in T-SQL.
Try this instead:
const result = await pool.request()
.query(`select * from table where username = 'Protractor'`);
or this:
const result = await pool.request()
.query('select * from table where username = \'Protractor\'');

SyntaxError: Unexpected end of JSON input: ALPR using Node and Javascript

The program prints perfectly when there is no License Plate in the frame, but when there is, I get the SyntaxError. Node.js and OpenALPR is installed. Photos are successfully being taken also.
const PiCamera = require('pi-camera');
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
setInterval(function() {
var path = './' + getRandomInt(500) + '.jpg';
const myCamera = new PiCamera({
mode: 'photo',
output: path,
width: 1920,
height: 1080,
nopreview: false,
});
myCamera.snap()
.then((result) => {
var exec = require('child_process').exec;
var cmd = 'alpr -c eu -n 1 --json ' + path;
exec(cmd, function(error, stdout, stderr) {
var data = JSON.parse(stdout);
if (data.results.length > 0) {
console.log(data.results[0].plate);
} else {
console.log("\n\n\nNo license plate found.\n\n");
}
});
console.log(result);
})
.catch((error) => {
console.log(error);
});
}, 2e3);
The error and where it occurs is:
undefined:1
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at /home/pi/Project/project.js:28:33
at ChildProcess.exithandler (child_process.js:301:5)
at ChildProcess.emit (events.js:189:13)
at maybeClose (internal/child_process.js:970:16)
at Socket.stream.socket.on (internal/child_process.js:389:11)
at Socket.emit (events.js:189:13)
at Pipe._handle.close (net.js:600:12)
Output of console.log(stdout); before var data declaration:
{"version":2,"data_type":"alpr_results","epoch_time":1588355061888,"img_width":1920,"img_height":1080,"processing_time_ms":1447.340698,"regions_of_interest":[],"results":[]}
There is a space at the end of the JSON.
try {
var data = JSON.parse(stdout.trim())
} catch (e) {
console.error('Failed to Parse JSON!', e)
}

Categories

Resources