0

I have the following code:

var sshPromise=require('ssh2-promise');
var x={
    host:'host',
    username:'username',
    password:'mypassword'
};
var ssh=new sshPromise(x);

ssh.connect().then(()=>{
    console.log('connected...');
});

//Get a shell session
ssh.shell().then((socket) => {
    socket.on('data', (data) => {
        console.log(data.toString());

    })
    //Can write to socket 
    //console.log('here<--'); 
    socket.write('my password');// <----sending password to enter the server
});

what is trying to do here is I'm creating a shell session after connecting to a server.After connecting it asks me password to access the server and i want to send my password but it does nothing.

I did a little debugging by adding console.log('here<--') and realised that it gets printed right at the start before the data arrives, meaning the socket.write('my password') gets executed before the data arrives.

I can't figure out how to solve this. Can anyone please help me.

EDIT:

const socket = await ssh.shell();

const data = await new Promise(resolve => socket.on('data', resolve));
socket.write('my password\n');
//to fetch next shell output
const data_1= await new Promise(resolve => socket.on('data', resolve));

is there any way to call use the data multiple times rather than creating a new promise everytime i need to get output from the shell?

1 Answer 1

1

Using async / await you can wait for the "data" event to fire using a Promise:

const socket = await ssh.shell();

const data = await new Promise(resolve => socket.on('data', resolve));

socket.write('my password');

That way, socket.write is only called after you have data.


If this needs to be used multiple times, you could define a function:

const waitForDataAsync = socket => new Promise(resolve => socket.on('data', resolve));

Then use like this:

const socket = await ssh.shell();

const data = await waitForDataAsync(socket);
socket.write('my password\n');
//to fetch next shell output
const data_1 = await waitForDataAsync(socket);
Sign up to request clarification or add additional context in comments.

3 Comments

Okay so it works perfect and here the shell output is stored in data. Now I pass a command to the server using socket.write. To get that output I did this: const data_1 = await new Promise(resolve => socket.on('data', resolve)); which kinda feels wrong to me but just to clarify, Is there any way to use this data without creating any new promise next time if i want to fetch new output ?
@DarthCucumber Can you add your new code to the question?
You could just pass a callback if nothing else relies on the new data, but if your next stage needs to wait for the response, using Promises will be much more readable in my opinion. You could even wrap the logic in a function; see my edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.