I want to send a CTRL + C command to client how can I achieve this in NodeJS?

1.2k Views Asked by At

My Code Looks Like this

var Client = require('ssh2').Client;
var fs=require('fs');
var conn = new Client();
conn.on('ready', function() {
    console.log('Client :: ready');
    conn.shell('xtail', function(err, stream) {
        stream.write('xtail\n\r');
        if (err) throw err;
        stream.on('close', function(code, signal) {
            console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
            conn.end();
        }).on('data', function(data) {
           // stream.stdin.write('?');
            console.log('hey');
            console.log('STDOUT: ' + data);
            fs.appendFile('D:\\Breme\\As1.txt',data,function(err){
                if(err)
                {
                    console.log(err);
                }
                //console.log('file saving..')
            });
            // setTimeout(function(){
            //     process.exit(1);
            // }, 20000);
        }).stderr.on('data', function(data) {
            console.log('STDERR: ' + data);
            conn.destroy();

        });
    });
}).connect({
    host: '10.214.14.15',
    port: 22,
    username: 'bwadn',
    password: 'bwain'
});

after connecting to server I am downloading the file but I want to send 'Ctrl+C' command from client, so that it stops receiving data

Can anyone please help me in solving this, As i am new to NodeJS I need your support in solving this...thanks

1

There are 1 best solutions below

0
Alex Pakka On

Most reliable way in this particular case, since you are using a variant of tail in your shell, is to use

 stream.write('\x03'); //send ctrl+c

you would need to send it when you know you don't need xtail output anymore. It is beyond the scope of this question to discuss the means, but setTimeout is definitely not a good idea.

Alternative (preferred) method:

stream.signal('INT')

and for other uses see Ssh2 Channel API