[英]Nodejs SSH2 connect multiple times
I want connect to remote machine and execute a shell command on that machine. 我想连接到远程计算机并在该计算机上执行shell命令。 I can upload a file and execute a command successfully.
我可以上传文件并成功执行命令。 But I can do it only once.
但是我只能做一次。 I want to be able to do it multiple times.
我希望能够多次执行。
Below is my JS file which uses SSH2 module. 下面是我的使用SSH2模块的JS文件。
var Connection = require('ssh2');
var fs = require('fs');
c = new Connection();
c.on('ready', function() {
console.log('Connection :: ready');
c.sftp(
function (err, sftp) {
if ( err ) {
console.log( "Error, problem starting SFTP: %s", err );
//process.exit( 2 );
}
console.log( "- SFTP started" );
sftp.unlink( "testfile.py", function(err){
if ( err ) {
console.log( "Error, problem starting SFTP: %s", err );
//process.exit( 2 );
}
else
{
console.log( "file unlinked" );
}
});
// upload file
var readStream = fs.createReadStream( "testfile.py" );
var writeStream = sftp.createWriteStream( "testfile.py" );
writeStream.on('end', function () {
console.log( "sftp connection closed" );
});
// what to do when transfer finishes
writeStream.on(
'close',
function () {
console.log( "- file transferred" );
sftp.chmod( "testfile.py", 777, function(err){
if ( err ) {
console.log( "Error, problem starting SFTP: %s", err );
//process.exit( 2 );
}
else
{
console.log( "Mode changed" );
}
});
//execute the program
c.exec('python testfile.py', function(err, stream) {
if (err) throw err;
stream.on('data', function(data, extended) {
console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
+ data);
});
stream.on('end', function() {
console.log('Stream :: EOF');
});
stream.on('close', function() {
console.log('Stream :: close');
// close the ftp connection
sftp.end();
// fs.end();
//process.exit( 0 );
});
stream.on('exit', function(code, signal) {
console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
//c.end();
});
});
}
);
// initiate transfer of file
readStream.pipe( writeStream );
}
);
});
c.on('keyboard-interactive', function(name, instructions, instructionsLang, prompts, finish) {
console.log('Connection :: keyboard-interactive');
finish(['pwd']);
});
c.on('error', function(err) {
console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
console.log('Connection :: end');
});
c.on('close', function(had_error) {
console.log('Connection :: close');
});
c.connect({
host: 'host',
port: 22,
username: 'uname',
password: 'pwd',
tryKeyboard: true
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.