I’m facing an issue with a Node.js/Express.js backend where I need to establish a connection to a Windows server, read files from a specific path, and print the content.
I have the server’s IP address, username, and password, and I’ve verified that the credentials work using Remote Desktop.
What I’ve Tried:
I attempted using ssh2, but it didn’t work.
I also tried using SMB2, but it wasn’t successful either.
My goal is to avoid hosting my backend on the server itself since I need to connect to multiple servers and read files from a specific path via my backend.
Thank you for your help.
Below is the code I’ve written so far:
async function sshConnection(ip, userName, password, privateKeyPath) {
const conn = new Client();
return new Promise((resolve, reject) => {
conn
.on("ready", () => {
console.log("SSH Connection Established");
conn.sftp((err, sftp) => {
if (err) {
console.error("SFTP Error:", err);
conn.end();
return reject(err);
}
sftp.readFile("<file-path>", (err, data) => {
if (err) {
console.error("File Read Error:", err);
conn.end();
return reject(err);
}
console.log("File Data:", data);
conn.end();
return resolve(data);
});
});
})
.on("error", (err) => {
console.error("SSH Connection Error:", err);
conn.end();
return reject(err);
})
.on("debug", (info) => {
console.log("Debug info:", info);
})
.on("close", () => {
console.log("Connection Closed");
})
.connect({
host: ip,
port: 22,
username: userName,
password: password,
});
});
}