how to execute remote operation to windows machine via nodejs - node.js

I finally joined the community
So for my first question in this community:
Generally I want to execute some remote operations to a remote windows machine in node.js (of course I have permissions, credential and so on to the remote machine).
Specifically, right now I'm trying to retrieve list of services from windows machine.
I've tried using the wmi-client package in order to do so:
const WmiClient = require('wmi-client');
var wmi = new WmiClient({
username: '*****', //credentials - username
password: '*****', //credentials - password
host: '*********', // remote windows machine
});
wmi.query(`Select * from Win32_Service`, function (err, result) {
console.log(result);
});
but I keep receiving error: Exit code: 44125. Invalid Global Switch.
I'll mention that using wmi in powershell make no issues for me.
but when I trying to use the same technology in nodejs its failed.
what am I doing wrong? Any other suggestions?
just to mention, when I need to retrieve same info from linux machine I easiliy do it using 'simple-ssh' package, without any issues:
const SSH = require('simple-ssh');
var ssh = new SSH({
host: '*******', // remote linux machine
user: '*******', // credentials - username
pass: '*******' // credentials - password
});
ssh.exec(`systemctl list-units --full -all`, {
out: function(stdout) {
// stdout as expected
}
}).start()});
but things getting complicated when trying to do the same for windows remote machine.
any ideas?
Thank you very much!

seems like the following is working for me:
var exec = require('node-ssh-exec');
var config = {
host: '*******',
username: '***',
password: '***'
},
command = 'sc query';
exec(config, command, function (error, response) {
if (error) {
throw error;
}
the response is as expected, but for some reason the error associated with it is not empty:
{
errno: -4077,
code: "ECONNRESET",
syscall: "read",
level: "connection-socket",
}

Related

Error:read ECONNRESET - I cannot successfully authenticate with the hp-ux server in node.js

I have a problem with the connection into a hpux server that we host locally in our local network. I get the following error:
Hello world
Connected to Nemesis
true
rejected: Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
level: 'client-socket'
}
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
level: 'client-socket'
}
Here is my code:
console.log('Hello world');
const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
ssh.connect({
host: "server",
username: "admin account",
password: "password"
}).then(console.log("Connected to Nemesis"))
console.log(ssh.isConnected());
ssh.exec('hh_client', ['--json'], { cwd: '/', stream: 'stdout', options: { pty: true } }).then(fulfilled => {
console.log("fulfilled:", fulfilled)
}).catch(rejected => {
console.log("rejected:", rejected)
})
I believe it is connecting to the server OK, tested by changing the IP, where I get a message to say that it cannot find the server. That said, the username and password does not seem to be being used, as I can type the user and password wrong, and I get the same error message.
the exec code is just lifted from the npm website for the module.
for a little more context, I am fairly new to hpux and linux in general, as most of this is inherited. I have seen a lot of information about using RSA and public/private keys, but there are already some on the server and I don't want to overwrite anything in the .ssh folder if I can help it.
In terms of connecting via other methods, I can use the username and password using ssh user#server and connect in fine, and do anything I want on the server with full permissions.
Any help appreciated.
Thank you,
Craig
Seing the exact same problem.
It's seems from the logs on the target server that the library is still trying to use key auth, maybe because we are not using it correctly or because it's simply considered insecure by the developers, or maybe they just negleted that option since most people won't use it for security reasons.
Here is the relevant server log:
Jan 23 20:43:55 debian sshd[6152]: error: kex_exchange_identification: banner line contains invalid characters
Jan 23 20:43:55 debian sshd[6152]: banner exchange: Connection from <source_ip_edited_for_privacy> port 42544: invalid format
Here is the code:
const readline = require("readline");
const { NodeSSH } = require("node-ssh");
// function to get input from user
const getInput = () => {
// required to take input from user
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// required to connect
const ssh = new NodeSSH();
rl.question("What is the host? ", (host) => {
console.log(host);
rl.question("What is the user? ", (user) => {
console.log(user);
rl.question("What is the password?", (password) => {
console.log(password);
rl.question("What is the command?", (command) => {
console.log(command);
// Connect
ssh.connect({
host: host,
username: user,
password: password,
//privateKeyPath: '/home/steel/.ssh/id_rsa'
});
// Excute Command
ssh
.execCommand(`${command}`, { cwd: `/home/${user}` })
.then((result) => {
// rl.write(result.stdout);
console.log("STDOUT: " + result.stdout);
console.log("STDERR: " + result.stderr);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
ssh.dispose();
rl.close();
});
});
});
});
});
};
getInput();

Failed to connect SQL Server from Node.js using tedious

I am trying to connect to SQL Server in our domain network. I am able to connect using python but not able to connect in Node.js using Tedious.
Node.js code snippet:
var config = {
server: 'serverName.domain.com',
authentication: {
type: 'default',
options: {
userName: 'DOMAINID\\username',
password: 'password'
}
},
options: {
database: 'dbName',
port: 1234,
}
};
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log('err', err);
} else {
console.log("Connected");
executeStatement();
}
});
connection.connect();
Receiving error:
Login Failed for the user DOMAINID/username. The login is from an untrusted domain and cannot be used with Windows authentication.
But when trying to connect from Python, I am able to connect successfully.
Python snippet:
import sqlalchemy
conn = sqlalchemy.create_engine('mssql+pymssql://DOMAINID\\username:password#serverName.domain.com:1234/dbName')
print(conn.execute('SELECT * FROM table_name').fetchall())
Data received successfully in python.
And also I tried with mssql and msnodesqlv8 with Microsoft ODBC 11 for Microsoft SQL Server drivers.
I am able to connect. Following is the code snippet.
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "server.domain.com",
database: "dbName",
port: 1234,
user:'DomainId\\username', // Working without username and password
password:'password',
options: {
trustedConnection: true // working only with true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = 'select * from table';
const result = await request.query(query);
console.dir(result);
};
main();
In the above snippet, I am able to connect without username and password but with trustedConnection true only. I am using windows authentication not SQL authentication. How can I connect using tedious js

Is it possible to connect to mssql with windows auth mode from a nodejs app running on linux?

I'm trying to connect to a mssql with Windows authentication mode (can't change that) from nodejs running on a linux machine.
I tried many things, all of them resulted in nearly the same error, here is an attempt using tedious with this simple code running on a linux machine with nodejs:
let tedious = require('tedious');
let Connection = tedious.Connection;
const config = {
userName: 'myUserName',
password: 'myPassword',
server: 'MyServ',
options: {
database: 'MyDbName'
}
}
function handleConnection(err: any) {
if (err) console.error("error connecting :-(", err);
else console.log("successfully connected!!")
}
let connection = new Connection(config);
connection.on('connect', handleConnection);
I get this error
error connecting :-( { ConnectionError: Login failed for user ''.
at ConnectionError (./node_modules/tedious/lib/errors.js:13:12)
at Parser.tokenStreamParser.on.token (./node_modules/tedious/lib/connection.js:848:51)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (./node_modules/tedious/lib/token/token-stream-parser.js:37:14)
at Parser.emit (events.js:198:13)
at addChunk (./node_modules/readable-stream/lib/_stream_readable.js:298:12)
at readableAddChunk (./node_modules/readable-stream/lib/_stream_readable.js:280:11)
at Parser.Readable.push (./node_modules/readable-stream/lib/_stream_readable.js:241:10)
at Parser.Transform.push (./node_modules/readable-stream/lib/_stream_transform.js:139:32)
at doneParsing (./node_modules/tedious/lib/token/stream-parser.js:122:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' }
The credentials I used do have SQL rights (tested with ODBC on windows machine).
Am I doing something wrong or is it just impossible ?
#ADyson thank you a lot for your informations, you managed to pinpoint the solution to my poorly formulated problem caused by my total lack of knowledge on the subject, really thank you again. the solution was to use domain login this snippet worked :
const config = {
user: MyUserName,
password: MyPassword,
server: 'MyServAdress',
database: 'MyDbName,
domain: 'MyDomain'
}
const sql = require('mssql');
sql.connect(config).then((pool: any) => {
console.log('connected!');
}).catch((err: any) => {
console.log(err);
});
Yes indeed, it's possible to receive data form a linux client using windows authentication only enabled. MS SQL Server and NodeJS Linux Server are in the same network. The linux Server isn't domain-joined:
I used this to run execute my query:
const sql = require('mssql')
const config = {
server: 'SERVER',
database: 'DATABASE',
user: 'USER',
password: 'PASSWORD',
domain: 'DOMAIN',
options: {
enableArithAbort: true // required, otherwise deprecation warning
}
}
sql.connect(config)
.then((conn) => {
console.log('MSSQL: connected');
conn.query(`SELECT ..`)
.then(data => console.log(data))
.then(() => conn.close())
}).catch(err => { console.log(err) });

Can't connect to SQL Server from my VS Code extension (node.js)

I'm developing VS Code extension and want to get some data from SQL Server database. I've tried many different examples but non of them are working for me.
const Connection = require('tedious').Connection;
const config = {
user: 'ssrs', // tried userName, username
password: 'ssrs',
server: 'localhost',
options: {
database: 'imdb'
}
}
const connection = new Connection(config);
connection.on('connect', function(err: string) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
OR
await sql.connect('mssql://ssrs:ssrs#localhost/imdb')
const result = await sql.query`select 1 as one`
console.dir(result)
OR
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
ConnectionError: Login failed for user ''.
Connecting via sqlcmd:
The port is also open (1433) as I can telnet to it.
Messages from SQL Server log:
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Login failed for user ''. Reason: An attempt to login using
SQL authentication failed. Server is configured for Integrated
authentication only. [CLIENT: 127.0.0.1]
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Error: 18456, Severity: 14, State: 58.
Trying to connect with Powershell:
PS C:\WINDOWS\system32> Invoke-Sqlcmd -query "select CURRENT_USER, USER_NAME()" -ServerInstance "localhost" -username "ssrs" -password "ssrs" -Database 'imdb'
Column1 Column2
------- -------
ssrs ssrs
As shown in your screenshot, you're able to connect via SQLCMD utility. This means there's no issue with the user or the authentication mode in SQL Server.
The error message is however misleading and other users already experienced this here.
I'm no expert of node.js but I'd recommend you to better understand how the mssql plugin and Connection object work. I think that some missing setting in your configuration is making the connection attempt fail.
For example, this code you posted is wrong (userName is not valid):
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
It should be:
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
user: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
The reason you can't connect is written in the log:
Reason: An attempt to login using SQL authentication failed. Server is
configured for Integrated authentication only.
You have to change the authentication mode (which you already did according to the screenshot posted) and restart the SQL Server service with Agent. Did you restart the service after changing the mode?

Unable to use tedious with Azure database

I've a node application which do have a connection to SQL Server.
Also, I'm using database as a service from Azure.
Code Snippet :
import { Connection } from 'tedious';
import { Request } from 'tedious';
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
instanceName: 'SQLEXPRESS', // Removed this line while deploying it on server as it has no instance.
database: 'dbname'
}
};
connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('error : '+err);
} else {
console.log("Connected to Database");
}
});
It has a successful connection, if done, locally.
Console Output => Connected to Database.
Deep dive done using console log :
-> Connection object is being created, but, the event ".on" is not being able to establish.
-> The connection gets established when deployed locally, while, when deployed on server, it doesn't works.
Based on the documentation here, you need to provide an additional option for encrypted connection.
Please try the following for config:
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
database: 'dbname',
encrypt: true //Need to add this for connecting to Azure DB
}
};
Using this configuration, I was able to connect to my database hosted in Azure.

Resources