GithubHelp home page GithubHelp logo

mcluck90 / simple-ssh Goto Github PK

View Code? Open in Web Editor NEW
194.0 8.0 37.0 96 KB

A simple wrapper for Brian White's ssh2 module to make it easier to perform sequential commands.

License: MIT License

JavaScript 100.00%
ssh ssh2 javascript

simple-ssh's Introduction

Note: I really don't work on this project anymore. It's still fully functional, I'm just not interested in working on it anymore. If you post an issue, I might respond and I might not. If you submit a pull request, I'll most likely accept it. Hopefully it continues to help people around the world. 🌎

simple-ssh

A wrapper for the ssh2 client module by Brian White which makes it easier to run a sequence of commands over SSH.

Requirements

Install

npm install simple-ssh

Examples

  • Echoing out a users PATH:
var SSH = require('simple-ssh');

var ssh = new SSH({
    host: 'localhost',
    user: 'username',
    pass: 'password'
});

ssh.exec('echo $PATH', {
    out: function(stdout) {
        console.log(stdout);
    }
}).start();

/*** Using the `args` options instead ***/
ssh.exec('echo', {
    args: ['$PATH'],
    out: function(stdout) {
        console.log(stdout);
    }
}).start();
  • Connecting with the active SSH Agent with Agent Forwarding
var ssh = new ssh({
    host: 'localhost',
    user: 'username',
    agent: process.env.SSH_AUTH_SOCK,
    agentForward: true
})
  • Capturing error output:
ssh.exec('this-does-not-exist', {
    err: function(stderr) {
        console.log(stderr); // this-does-not-exist: command not found
    }
}).start();
  • Capturing error codes:
ssh.exec('exit 69', {
    exit: function(code) {
        console.log(code); // 69
    }
}).start();
  • Sending data to stdin:
ssh.exec('cat > /path/to/remote/file', {
   in: fs.readFileSync('/path/to/local/file')
}).start();
  • Chaining commands together:
ssh
    .exec('echo "Node.js"', {
        out: console.log.bind(console)
    })
    .exec('echo "is"', {
        out: console.log.bind(console)
    })
    .exec('echo "awesome!"', {
        out: console.log.bind(console)
    })
    .start();

// Output:
// Node.js
// is
// awesome!
  • Get the number of commands:
ssh
    .exec('exit 1')
    .exec('exit 2')
    .exec('exit 3');

console.log(ssh.count()); // 3
  • Running a command using sudo
ssh.exec('sudo echo "Pseudo-sudo"', {
    pty: true,
    out: console.log.bind(console)
}).start();
  • Resetting a connection and the commands
// Echos out any messages the user sent in if 10 or more have been queued
var msgInterval = setInterval(function() {
    if (ssh.count() > 10) {
        ssh.start();
    }
}, 1000);

socket.on('message', function(msg) {
    // If a 'reset' message is received, clear previous messages
    if (msg === 'reset') {
        ssh.reset(function(err) {
            if (err) {
                throw err;
            }

            ssh.exec('echo "reset"');
        });
    } else {
        ssh.exec('echo "' + msg + '"');
    }
});
  • Listening for additional events
ssh.on('error', function(err) {
    console.log('Oops, something went wrong.');
    console.log(err);
    ssh.end();
});
  • Event handlers can be chained as well
ssh
    .on('error', onSSHError)
    .on('ready', onSSHReady);

API

Functions

  • Constructor( [ config ] )
    • config { Object }:
      • config.host { String }: Hostname
      • config.port { Number }: Port number (default: 22)
      • config.user { String }: Username
      • config.pass { String }: Password
      • config.timeout { Number }: Connection timeout in milliseconds (default: 10000)
      • config.key { String }: SSH key
      • config.passphrase { String }: Passphrase
      • config.baseDir { String }: Base directory. If this is set, each command will be preceeded by cd ${this.baseDir}
      • config.agent { String }: Connects with the given SSH agent. If this is set, no need to specify a private key or password.
      • config.agentForward { Boolean }: Set to true to connect with agent forwarding.
  • exec( command, [ options ] ): Adds a command to the stack
    • command { String }: Command to be executed
    • options { Object }:
      • options.args { String[] }: Additional command line arguments (default: null)
      • options.in { String }: Input to be sent to stdin
      • options.out { Function( stdout ) }: stdout handler
        • stdout { String }: Output streamed through stdout
      • options.err { Function( stderr ) }: stderr handler
        • stderr { String }: Output streamed through stderr
      • options.exit { Function( code, stdout, stderr ) }: Exit handler
        • code { Number }: Exit code
        • stdout { String }: All of the standard output concatenated together
        • stderr { String }: All of the error output concatenated together
      • options.pty { Boolean }: Allocates a pseudo-tty, useful for command which require sudo (default: false)
  • on( event, callback ): Add a listener for the specified event (Courtesy of @alexjab)
    • event { String }: Event to listen to
    • callback { Function }: Executed on the event
  • start( [ options ] ): Starts executing the commands
    • options { Object }:
      • options.success { Function() }: Called on successful connection
      • options.fail { Function( err ) }: Called if the connection failed
        • err { Error }: Error information
  • reset( [ callback ] ): Clears the command queue and resets the current connection
    • callback { Function( err ) }: Called when the connection has been successfully reset
      • err { Error }: Error information
  • end(): Ends the SSH session (this is automatically called at the end of a command queue).

Properties

  • host { String }: Host to connect to
  • port { Number }: Port to connect through (default: 22)
  • user { String }: User name
  • pass { String }: Password
  • timeout { Number }: Connection timeout in milliseconds (default: 10000)
  • key { String }: SSH key
  • baseDir { String }: If set, will change directory to baseDir before each command

Flow Control

Sometimes you may find yourself needing to change which commands are executed. The flow can be changed by returning false from an exit handler.

Note: This only works if false is explicitly returned. "Falsy" values are not sufficient (since undefined is implicitly returned and it's "falsy").

  • Ending prematurely:
ssh
    .exec('pwd', {
        exit: function() {
            return false;
        }
    })
    .exec('echo "Not executed"')
    .start();
  • Running a new queue of commands:
ssh
    .exec('exit', {
        args: [ Math.round(Math.random()) ],
        exit: function(code) {
            if (code === 1) {
                // Setup the new command queue
                ssh.exec('echo "new queue"');
                return false;
            }
        }
    })
    .exec('exit 0', {
        exit: function() {
            console.log('Previous command did not return false');
        }
    })
    .start();

simple-ssh's People

Contributors

alexjab avatar bogdanbruma avatar chuntley avatar frank-dspeed avatar mcluck90 avatar toddses avatar tonymasse avatar wolfgang42 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-ssh's Issues

List of events

Hey there,

Is it possible to get a list of events which can be bound to with the .on function? I can't see anything in the list of examples or documentation.

Am I right in assuming this is the complete list given simple-ssh is a wrapper?
https://github.com/mscdex/ssh2#connection-events

Cheers!

Doctype error

Following the simple examples over on https://www.npmjs.com/package/simple-ssh, an error is triggered. Here is my code:

    var ssh = new SSH({
    host: '[email protected]',
    user: 'me',
    agent: process.env.SSH_AUTH_SOCK,
    agentForward: true
    });
    ssh.exec('echo', {
    args: ['$PATH'],
    out: function(stdout) {
        console.log(stdout);
    }
    }).start();

Here is the error:

While building the application:
node_modules/simple-ssh/node_modules/xtend/node_modules/is-object/test/static/index.html:1: Can't set DOCTYPE
here. (Meteor sets for you)

=> Your application has errors. Waiting for file change.

can't use privateKey

Is it possible to use a privateKey (private key) instead of pass (password).

I believe ssh2 have privateKey implemented. But I don't see this as an option to pass into the config objective for simple-ssh

{ _c:
   Client {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     config:
      { host: undefined,
        port: undefined,
        forceIPv4: undefined,
        forceIPv6: undefined,
        keepaliveCountMax: undefined,
        keepaliveInterval: undefined,
        readyTimeout: undefined,
        username: undefined,
        password: undefined,
        privateKey: undefined,
        publicKey: undefined,
        tryKeyboard: undefined,
        agent: undefined,
        allowAgentFwd: undefined,
        hostHashAlgo: undefined,
        hostHashCb: undefined,
        strictVendor: undefined,
        debug: undefined },
     _readyTimeout: undefined,
     _channels: undefined,
     _callbacks: undefined,
     _forwarding: undefined,
     _acceptX11: undefined,
     _agentFwdEnabled: undefined,
     _curChan: undefined,
     _remoteVer: undefined,
     _sshstream: undefined,
     _sock: undefined,
     _resetKA: undefined },
  _commands: [],
  host: 'ec2-52-38-224-37.us-west-2.compute.amazonaws.com',
  port: 22,
  user: 'rancher',
  pass: '',
  timeout: 10000,
  key: '',
  passphrase: '',
  baseDir: '',
  agent: '',
  agentForward: '' }

using passphrase doesn't work with github enterprise

I am using this to make an ssh connection to github enterprise. I'd like to point out

  • the doc contains a passphrase config param, but it is being ignored. The code uses the pass config param instead.
  • when I set the following 2 params user, key, pass (pass contains the passphrase), I get the following error "Error: Authentication failure. Available authentication methods: publickey"

ssh2 error

ssh2 ver 0.5.0 fixes 'connection error: Error: Disconnected by host (PROTOCOL_ERROR): Packet integrity error',while latest simple-ssh still depends on ssh2 ver 0.3.6.

Would you please update simple-ssh ?

Great pakage,
.t

Weird variable scoping and/or value issue in exec string

I've got a weird thing happening in my app.

I'm building a batch deployment tool which will connect to numerous raspberry pi boards and check a code version, and then pull down new code if available.

Everything is working great except for one strange thing.

I have a global variable called latestVersion which gets set to the latest version of software. within the out and exit functions, it has the correct value. However, when I reference it within the exec command string, it reverts to the original value.

I've also tried storing the variable in an object (data.latestVersion) thinking that if it was a scoping issue, it would throw an error since data would be undefined if it didn't exist in a specific scope. However, that behaved identically.

I will attempt to create a simplified version of my code so you can reproduce.

The ip address won't work for you, but hopefully you have something you can use to test.

var Ssh = require('simple-ssh');

var singleIp = ['10.119.73.74'];

var ssh = new Ssh({
  host: singleIp[0],
  user: 'pi',
  pass: 'raspberry'
});

var latestVersion = '0.05';

ssh.exec('echo "changing latestVersion"', {
  exit: function() {
    // setting the latestVersion to a new value
    latestVersion = '0.1';
    console.log(latestVersion, 'should be: 0.1');
  }
}).exec('echo "' + latestVersion + '" > current_version', {
  exit: function() {
    console.log('current_version file written');
    console.log('latestVersion', latestVersion);
    // latestVersion still logs out as 0.1
  }
}).exec('cat current_version', {
  // value used in current_version was still 0.05
  out: function(stdout) {
    console.log('current_version:', stdout);
  },
  exit: function() {
    console.log('exiting final command!');
  }
}).start();

memory lead detected

I got the member leak detected error in my production server log when running a ssh codes calling bash sh.

(node) warning: possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
    at Connection.addListener (events.js:179:15)
    at Connection.once (events.js:204:8)
    at new ChannelStream (/myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Channel.js:578:17)
    at /myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Channel.js:360:20
    at Parser.<anonymous> (/myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Channel.js:142:30)
    at Parser.emit (events.js:104:17)
    at Parser.parsePacket (/myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Parser.js:632:12)
    at Parser.execute (/myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Parser.js:249:14)
    at Socket.<anonymous> (/myfolder/shared/node_modules/simple-ssh/node_modules/ssh2/lib/Connection.js:536:18)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:529:20)


Private Key errors

Hello,
I am having an issue with private key authentication, wherein keys without properly escaped newlines cause a failure. I am fairly certain this is the issue, and if so, could you please advise on how to properly escape the private key before using it with simple-ssh

The error I receive is:
[Error: Incorrect passphrase: Error: privateKey value does not contain a (valid) private key]

Thank you

Differences between "out: console.log" and "out: function(stdout)"?

What are the exact differences for both of these cases for outputting the results from SSH commands?

First Method

.exec('yum -y update', {
    pty: true,
    out: console.log
})

Second Method

.exec('yum -y update', {
    out: function(stdout) {
        console.log(stdout);
    }
})

I am finding that using the 2nd method in my functions does not always rending an output, whereas the 1st one always seems to work. Again, thanks for your helps so far!

no timeout response?

I love simple-ssh, a great module, but how can I get a response if I get timeout?
It is possible to set the timeout but there is no event or key that let you know that there is a timeout
something like this:

timeout: function(msg) {
console.log('sorry, timeout: ', msg);
}

or

ssh.on('timeout', function(msg) { console.log('sorry, you have a timeout: ', msg); });

Is this specific output possible?

I've created a bash script which installs the Teamspeak 3 software. Post installation, after starting the server for the first time, there is output that is provided to the end user.

When using Simple-SSH I noticed that that particular block / output isn't logged and streamed back. I've attached an image of what it looks like.

screenshot 2014-11-24 16 05 23

Is there any possible way of capturing this output and providing it to the end user?

Validate connection

Hello, simple question
Is there any way to verify that the connection was successful?

const Connection = require('simple-ssh')
ssh = new Connection({...})

if (ssh)... something like

Thanks.

can't capture err with sudo

here's my code

let SSH = require('simple-ssh')

let ssh = new SSH({
    "host": "1x9.xx.xx.xx",
    "user": "xxplxe",
    "pass": "axxxxx11"
})
ssh.exec('sudo bad_command ', {
    pty: true,
    out: function(stdout) {
        stdout !== '\r\n' ? console.log(stdout) : ''
    },
    err: function(err) {
        console.log(err)
        console.log('I\'m not execute!')
        ssh.end()
    }
}).start()

Maybe this is ssh2's bug, and I can't fix it.
I hope you can see this issues.

Missing Environment variables

I am not sure if the problem is simple-ssh or my configuration, so lets explain the problem.

I have a openSSH server that I want to connect with a node js client, using simple-ssh. When I connect to the server, I try to call npm, that is installed on the server, using exec but the simple-ssh can't find npm (I try doing npm-v).

When I am connected with a real ssh client, I have no problem doing npm -v

Also, I export node js binary folder and they are visible in the $PATH env , but missing in the simple-ssh connection.

Any idea?

Chaining commands failing.

Tried the code example on the front page:

ssh
    .exec('echo "Node.js"', {
        out: console.log.bind(console)
    })
    .exec('echo "is"', {
        out: console.log.bind(console)
    })
    .exec('echo "awesome!"', {
        out: console.log.bind(console)
    })
    .start();

which only resulted in:

Node.js

is

No response if My connect failed

Hi, my nodejs sends ssh exec to the client servers,
And the scripts itself succeed.

However, I found that for a new servers which haven't updated the sshd to allow Root, it failed silently, nothing appears in the console.

It is very easy for me to update the sshd_config, however,

I wonder how can I know a log or make sure a ssh connect doesn't failed quitely?

   ssh.exec("echo \"" + process_public_key + "\" > /tmp/process.pub", {
          out: console.log
    })
    .exec("su deploy -c `cat /tmp/process.pub >>  /myuser/.ssh/authorized_keys`", {
        out: function(stdout) {
            console.log(stdout);
        }
    })
    .exec("rm /tmp/process.pub")
    .start();
console.log("finished set keys");


change directory command is not working

I used cd command to change directory for remote server as below and it is not changing the directory.

var SSH = require('simple-ssh');

var ssh = new SSH({
host: 'remote_server_ip',
user: 'username',
pass: 'password'
});

ssh.exec('cd /home/etc/sanjeev', {
out: function(stdout) {
console.log(stdout);
}
.exec('ls', {
out: function(stdout) {
console.log(stdout);
}
}).start();

So in last 'ls' is not listing files/directory from /home/etc/sanjeev but listing from /home/sanjeev.

callback for upload file

How to check the end of the file upload to the server via ssh?

resolution:

ssh.exec('cat > '+send_file_server_url+'/18.png', {
    in: fs.readFileSync('./17.png'),
    exit: function(code) {
        console.log("final load 17.png"); // 69 
    }
}).start();

connection using key

I have read all the topics with the related subject, it did not help.

I generated my key:
ssh-keygen -m PEM -t rsa
ssh-copy-id

When I use this:
key: '/root/.ssh/id_rsa' I have following return ... "Error: Can not parse privateKey: Unsupported key format"

And so:
key: fs.readFileSync('/root/.ssh /id_rsa') ... "Error: All configured authentication methods failed"

I'm adding the passphrase parameter as well.
What is the correct way to connect using keys? Where am I going wrong?

Authentication using keys?

Hi,

I was wondering if there are any plans to also use keys for authentication for connecting to a server via SSH.

exit:function(code , stdout , stderr) no stdout when pty is true

when set the pty to true , the exit method return no stdout and stderr .
ssh.exec(req.body.command, {
pty:true,
out: function(stdout) {
console.log('in stdout ' + stdout);
},
err:function(stderr){
console.log('in stderr ' + stderr);
},
exit:function(code , stdout , stderr){
console.log('exit ' + code);
console.log('exit stdout ' + stdout);
}
}).start();

Like #11, I can't iterate

Hi,

I follow your answer in issue #11

Here is my code :

var SSH = require('simple-ssh');

function createConnection(config){
    var myssh = new SSH({
      host: config.host,
      user: config.user,
      pass: config.pass
    });
    myssh
      .exec('nproc',{
        out:function(stdout){
          console.log(config.host+" : "+stdout);
        }
      }).start();
}

    var config = [{
      host: 'server1',
      user: 'myuser1',
      pass: 'mypass1'
    },{
      host: 'server2',
      user: 'myuser2',
      pass: 'mypass2'
    }];

    for (var i=0;i<config.length;i++){
      createConnection(config[i]);
    }

The result is only :

server1 : 24

It seems that the second connection does not work at all and is not started.

I installed simple-ssh from npm and I use nodejs v0.10.32

Thanks for your help

Call synchronously or any proper way to detect end of response ?

Is there any possible way to execute ssh commands synchronously or if that's not possible how can I detect if a command execution is completed ..?

I see, callback out is called multiple times and I am not being able to figure out a way to find the end of the response.

Please help.

Run multiple commands?

I would love to be able to use this to replace my perl modules.

I need to be able to log into Network Devices and run commands and parse the output.

Is it possible to run more then one command on the target host? Also how would I run through a loop or hosts from say a file?

Thanks

Exit handler not being called

In exec options, I've added 3 handlers - out, err, exit.
The out and err handlers get called successfully, however, the exit handler that is supposed to provide concatenated result doesn't get called at all.

My code is as follows -

`
//ssh to remote machine
ssh.exec(shellCommand, {

	out: function(stdout) {
		let successData = stdout.toString('utf8') || "Script executed successfully";
		console.log(successData);
	},
	exit: function(code,stdout,stderr) {
		console.log(stdout);
	} ,
	err: function(stderr) {
		let errorData = stderr.toString('utf8') || "Error in script execution";							
		console.log(errorData);
	}

}).start();

`

Please let me know if there's anything wrong with the above code, or as how to invoke the exit handler.

Regards,
Ashish Deshpande

Changing directory

Hey there,

I've got simple-ssh up and running , it connects, all is swanky (thank you!), except, for the life of me I can't figure out how to change directory when connected (cd).

.exec( "cd mydirectory" ) exits with code 0, but the active directory does not change.

Am I doing something wrong?

Keep connection alive

As I see in documentation:
end(): Ends the SSH session (this is automatically called at the end of a command queue).
after .exec connection is closed. Is it possible to keep connection alive so I could reuse it later without reconnecting to SSH server?

Format of ssh-key

The documentation doesn't say, which format the ssk-key for privatekey login is supposed to have. Can you help on that? I always get “All configured authentication methods failed” although I can log-in through a console using the same key used. This is on a mac with node v8.8.1.

Interactive prompt?

Is there any way to gain control over interactive prompts and pass arguments?

repeat call to callback

I am putting a simple print statement in the out and the callback is being executing multiple times. The command I am running returns a filepath and that is a single line output. Any idea what could be causing this? There is a loop outside of ssh.exec though and I am using async.each() for that.

ssh.exec(cmd, {
    out: function(stdout) {
      var path = new String(stdout);
      console.log(path.trim());      
    },
    err: function(stderr) {
    }
  })
  .on('error', function(err) {
  })
  .start();

Cannot parse privateKey: Unsupported key format

I want to log in using the key.
Can I show you an example of how to use it?

`var sshLinux = new SSH({
host: IP,
user: NAME,
key : key
});

	sshLinux.exec('ifconfig', {
	    err: function(stderr) {
	        console.log(stderr); // this-does-not-exist: command not found
	    },
	    out: function(stdout) {
	        console.log(IP + " - Echo : " , stdout);
	    }
	    
	}).start();
	
	sshLinux.on('error', function(err) {
	    console.log('[ SSH ]  ERROR ');
	    console.log(err);
	    sshLinux.end();
	});
	callback();`

This error has occurred.
The value of key gave the path value of id_rsa.

0|app | Error: Cannot parse privateKey: Unsupported key format
0|app | at Client.connect (/usr/local/src/nodejs/dnsm_system/node_modules/ssh2/lib/client.js:230:13)
0|app | at SSH.start (/usr/local/src/nodejs/dnsm_system/node_modules/simple-ssh/lib/ssh.js:214:19)
0|app | at Object.exports.linux_shutdown (/usr/local/src/nodejs/dnsm_system/routes/node_ssh_MD.js:67:6)
0|app | at Query._callback (/usr/local/src/nodejs/dnsm_system/routes/node_mysql_MD.js:277:10)
0|app | at Query.Sequence.end (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/protocol/sequence s/Sequence.js:88:24)
0|app | at Query._handleFinalResultPacket (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/proto col/sequences/Query.js:139:8)
0|app | at Query.EofPacket (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/protocol/sequences/Q uery.js:123:8)
0|app | at Protocol._parsePacket (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/protocol/Proto col.js:279:23)
0|app | at Parser.write (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/protocol/Parser.js:76:1 2)
0|app | at Protocol.write (/usr/local/src/nodejs/dnsm_system/node_modules/mysql/lib/protocol/Protocol.js: 39:16)

In the above options, should the value of the key specify the path?
I have not used it yet.

Sorry.
I am a beginner.
and Thank u

Fix on stream

Hello,

I'm using your lib and sometimes, I execute command with a big result. Your line 104 cut the result because of this line :
Line 104 stream.on('exit', function(code) {
The handle 'exit' on a stream doesn't wait until the end of result.

I suggest you to change by this line and your user could use your lib without bug.
Line 104 stream.on('close', function(code) {

Kind regards,

JB.

SSH Configuration works Different when the Values are iterated

I have a Program which gets the system values from the db and in return adds the values from a loop like this

var succ=[{hostname:"192.168.1.2",hostuser:"admin",hostport:"22",hostpassword:"password"},{hostname:"192.168.1.4",hostuser:"admin",hostport:"22",hostpassword:"password"}]

for (var i = 0; i < succ.length; i++) {

                    var host = succ[i].hostname,
                        user = succ[i].username;

                    var ssh = new SSH({
                        host: succ[i].hostname,
                        port: succ[i].hostport,
                        user: succ[i].hostuser,
                        pass: succ[i].hostpassword
                    });

}

If i like to do any operation inside then the ssh configuration takes 1.4 instead of 1.2 first.

Unable exec linux command of options

Can you use it or do I use it in the wrong way?

ssh.exec('rm -r', {
      args: [remotes.scriptPath],
      err: (err) => console.log('removeOldScript', err),
      out: (res) => console.log('removeOldScript', res),
    }).exec('mkdir -p', {
      args: [remotes.scriptPath],
      err: (err) => console.log('removeOldScript mkdir', err),
      out: (res) => console.log('removeOldScript mkdir', res),
    }).start()

image

Pass executed command to callback

As the title say, can we have the executed command passed to the callback? This is pretty useful in debugging. I had such a use just recently.

For example:-

ssh.exec('echo "Hello World"', {exit: function(a,b,c, command) {
  console.log(command); // prints 'echo "Hello World"' without the single quotes.
}}).start();
``

bot not updating and spamming.

Hello. I am trying to make a !pingip command which pings a specific IP that the user enters.
When the command is executed for the first time, it pings without spamming.
When the command is executed for the second time it pings the first IP.
When the command is executed for the third time, it spams ping with the first IP.

Here is a video with the problem:
https://youtu.be/wGipltLJsJs

I've been trying to fix this problem for like 2 days.

if (message.content.startsWith(`${PREFIX}pingip`)) {
  let msg2;
  const textluuuuung = message.content.substring[500];
  if(message.author != 309333602129281027) 
    return message.channel.send("```ERROR: You are not allowed to use this command !```");
  ssh.reset();
  ssh.end();
  if(!args[1])
    return message.channel.send("```ERROR: You need to input a IP in order to ping it```");
  message.channel.send('Connecting to server...')
  .then((msg)=> {
      msg.edit(`Connection estabilished ! Pinging...`);
      ssh.exec(`timeout 1 ping -c 1 ${args[1]} > logserver1.txt`)
      ssh.reset();
      ssh.end();
      ssh.exec('head -n -1 logserver1.txt', {
        out: function(outubuntu) {
          var cacat = setInterval(function() {
          clearInterval(cacat);
          const embed = new Discord.MessageEmbed();
          const embedcontent = message.content.substring[15];
          embed.setDescription(embedcontent);
          embed.setTitle("PingIP");
          embed.setColor(color=0xff0000);
          embed.setAuthor(name="Ping Info:")
          embed.addField(name=`IP:`, value=`${args[1]}`,embedcontent)
          embed.addField(name="Output:", value=`${outubuntu}`, embedcontent)
          message.channel.send(embed);
          ssh.end();
        }, 1000) 
      }
    }).start();
  })

#10 Issue -- Ssh values Iteration from the array

Hi Mcluck,

Sorry to post this issue again and in the previous issue there wer some errors in the code which i have share .here is the exact code which i'm trying to do

Private.find().exec(function(err,succ){

    if(err) throw err.message;

    console.log(succ);

    for (var i = 0; i < succ.length; i++) {

        /*sails.log(succ.length, m);
         var host = succ[m].hostname,
         user = succ[m].username;
         sails.log(host, user);*/

        var host = succ[i].hostname,
            user = succ[i].username;

        sails.log(host, user);

        var ssh = new SSH({
            host: succ[i].hostname,
            port: succ[i].hostport,
            user: succ[i].hostuser,
            pass: succ[i].hostpassword
        });
        console.log(ssh.host);

        ssh.exec('nproc', {
            out: function (cpucore) {
                console.log(cpucore)
                ssh.exec('cat /proc/meminfo | grep MemTotal | cut -d":" -f2| cut -d"k" -f1|tr -d " "', {
                    out: function (memtotal) {
                        console.log(memtotal);
                        ssh.exec('cat /proc/meminfo | grep MemFree | cut -d":" -f2| cut -d"k" -f1|tr -d " "', {
                            out: function (memfree) {
                                console.log(memfree);
                                ssh.exec('uname -i', {
                                    out: function (arc) {
                                        console.log(arc);

                                        Resource.create({username: user, hostip: host, cpu: cpucore, totalram: memtotal, leftram: memfree, arctype: arc}).exec(function (err, succc) {
                                            if (err) {

                                            } else {
                                                sails.log("Data Created for ip", host);
                                            }
                                        })
                                    }
                                })
                            }
                        })
                    }
                })
            }
        })



}
})

[MAC OS X] .exec does nothing

Hey ! I have a ssh server that is running on my mac for test purpose, but I can't access to it via this framework...
Here is my code :

var SSH = require('simple-ssh');

var ssh = new SSH({
    host: '127.0.0.1',
    user: 'myUsername',
    pass: 'TheRightPassword'
//    passphrase: 'TheRightPasswordToo'
});

ssh.exec('echo $PATH', {
    out: function(out) {
        console.log(out);
    },
    err: function(err) {
        console.log('error: ' + err);
    }
});

sshh.on('error', function(err) {
    console.log('Oops, something went wrong.');
    console.log(err);
    ssh.end();
});

When I run this script, it does nothing on my mac. I tried with other commands ( like mkdir )...
Thx.

Exec Not Returning Response Nor Error

Hello.

I'm attempting to ssh into an EC2 instance from node.js and add a public ssh key from Node.js to authorized_keys on the EC2 instance. I've wrapped the commands in a promise and applied async/await to ensure a response is returned before continuing. The rest of the code executes properly without errors. However, it seems the exec command is either returning nothing immediately or is not executing at all since no error is returned. Is there something I'm missing here?

const ssh_response = await new Promise((resolve, reject) => {

	const ssh = new SSH({
		host: temp_access.ipAddress,
		user: temp_access.username,
		key: temp_access.privateKey,
		passphrase: ""
	})

	ssh.exec("cat " + public_key + " >> ~/.ssh/authorized_keys", {

		out: console.log.bind(console),
		err: stderr => console.log(stderr)

	}).start(resolve, error => {

		throw new Error(error)
	})
})

Maybe the format of the private key, which is currently set to a temporary AWS key?

-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAqXY7pL4Cru+2bFQYKpyUB1ALAvGhRjqdEv1Q85btnQ85QgiN\nCzO19Wfz6z7BtT5hamYDXFGNJ537Cz6zgOVgt0ba8NKNRO1iMGqiQeEezJUGuWzl\nHQ32XETu8BA6JDDZJXXcxNsmY1mo+orhcYJFym7U+mTVMpNHr1+2kDQvuYdep7/y\n9Ip4kkrfQNHrOu6/LE49k/S3kzcPNBeSiDL2MLt0ksC/KjNH95GvPnpc4xbU+fNY\n27lQmgVWQ1dUnxYlu0T/WVei02eNoF0IMUF21sS49i2KJ12GE35s9CCFyC5vvdlM\nZdYSHXfpW7jG3ndQ1ij/brUf//Ku7d+bviyaeQIDAQABAoIBACkTFF/ZAnN+fNwD\nAhyJ+UNQfmrHQIzyNhJdPhrc0VlJUFqWEgHOFeOWv8OcYX1Z0mjksxnUVn9sxmWy\nW/X5IxkpXnYSwtUbKLqNjiijtUBnOssE/v+s27L/rl6XwE/3Wxq+V7WLXOGl4NRh\nh0VpCxuHA65xdE+e7Tgv3eNUEuFH7jhep3HN4dBMQr6erOhTHBAumerPL9j0pOIf\n0CJeyoKgRzGtzUsNqSRmzy/2sZxmr2GjazFJlr/N5GBkndhSv4UXJPn99QJAND2H\nVsdZZqQyhc9/MadHHXqhGN2nFae/0HgOKLqkBYJ52fJkwlw+CsqhDZd/9nUb6hoW\nFYlhDGUCgYEA4b2Eu/1epUaghMVNGEwGVyomfkz6T8I9NbovDPpAQeaWWWMCkgIT\njNGH2lP0F9F3jLIxolqr/FtkNTeJ7TA+x0hibtOELs5TILMc8L9ztxFh0XTRu6Nc\nxCdcdHj3dxoIIU9enJ0EY54b/HNjgyvi3T6inI8IBg5FbIGIfosyvAcCgYEAwC13\n9VF+w3uoPdi53mhfYhr2gv9XcqCzfYoDTVLJvV9K1hUenS4iyjdEWtvDqW/MYMFK\nFnqHV2nC20rMnEs7WqXlpD8P+/g7Ztr7ViPheZvzLFHRHIZX7pVfM+uZ8ZwoI9sK\nnuHVuWp/1z5x137wMsuhQ41AOTUl1bCOPH0VVX8CgYBqDiX8RC9hKutjNWbhEWax\nMOZg1D2Nl042ncBZMoFZ9MGSQUgF3N/eetp+oo69WfX2rglPo5XFvBI6RluQiegU\nrFdChjFF5D190Wi5Wtk8mvf/9ghLRZbhuTRgrCxnUl2beLSUk9hqDPBNDNEl4Up2\nc2TmdPRqE+5d6gV8nl05pQKBgG5Ra5xKpP8onCKsp74RojeaDMqUM6ncsEyvjkez\n75Ui/723L/TAyD3WzgluQHqib+tW6eXPfqPiVXY3EQ/ja/YUZ6gKf22ASPE5YbBI\nNqXtrQFTEjxSrmWKH7WZWKzGnJBArG8aaureRPbVpNo0x0QReshhbG2qocZybKQy\nla2XAoGAE+JOO4QbxHdCjJ9bibqjECnCjK3BKDd1kU+nf0iBMH+0ysdK0fsUYRqk\nWaKLim9PK5RNnb3wIo0UxfPr63jg7nkzXAHlqbrLmRFLGUo7mYrt+h6QFPk79Gos\nln1MZNxZau9PlDO7Uhf5ChQtVPpREJ8MMJyawIwFsZ34WpAkwRE=\n-----END RSA PRIVATE KEY-----\n

Does not work on Mac OS.

Your source is very convenient and powerful.

However, when I try to connect to SSH on Mac OS, I get a problem.

On Linux ssh userName @ IP.
Command to ssh on MacOS, but is there any way to fix this on Windows?

password based authentication doesn't work on Mac

On OS X El Capitan, trying to authenticate with a password always fails with this error:
"Error: All configured authentication methods failed"

I can ssh normally from the command-line with my password so I know that the host, username and password is correct. After doing some digging, I found that this issue was logged for ssh2 itself here:
mscdex/ssh2#238

Basically, when calling connect on ssh2 it needs the tryKeyboard param as true and an implementation for the keyboard-interactive event. I see the option to specify the keyboard-interactive event using 'on', , but no way to specify the tryKeyboard param?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.