Пример #1
0
	            stream.on('close', function(err, stream) {
	                if (didStr == "" || didStr == null) {
	            		alyConn.end();
	            	}else{

	            		alyConn.end();
		                console.log("退出121.42.193.51成功!!!!!!!");

		               alyConn.on('ready', function() {			            	
			            	
			            	alyConn.exec(contentCmd, function(err, stream) {
					            if (err) throw err;
					            stream.on('close', function(err, stream) {
					                alyConn.end();
					            }).on('data', function(data) {
					            	contentData += "\n\n"
					            	contentData += data;
					            	console.log("返回内容: "+contentData);
					            	res.render('cloudDisk.ejs', { modelsAttributes: modelsAttributesData, modelsPropertys: modelsPropertysData, serverIP: global.reqServerIP, account: reqAccount, content: contentData});
					            	return;
					            }).stderr.on('data', function(data) {
					                console.log('STDERR: ' + data);
					            });

					        });
					            	
					    }).connect({
					        host: dbServerInfo.ip,
					        port: 22,
					        username: dbServerInfo.userName,
					        password: dbServerInfo.passWord
					    });
					}

	            }).on('data', function(data) {
Пример #2
0
        _engage.getUserName(function(err, username) {

            var connection;

            if (err) {
                process.nextTick(function() { cb(err); });
                return;
            }

            connection = new Client();

            connection.on('ready', function() {
                connection.sftp(function(err, sftp) {
                    if (err) {
                        process.nextTick(function() { cb('Failed to connect to Engage SFTP: ' + err); });
                    } else {
                        process.nextTick(function() { cb(null, connection, sftp); });
                    }
                });
            }).on('error', function(err) {
                process.nextTick(function() { cb('SFTP error: ' + JSON.stringify(err)); });
            }).connect({
                host: _hostname,
                username: username,
                privateKey: _privateKey
            });
        });
Пример #3
0
	.get('/', function translate (req, res, next) {
		
		var conn = new ssh(),
			all = [],
			fin = '';

		conn.on('ready', function () {
			conn.exec('./bobo.sh;./bobo1.sh', function (err, stream) {
				if (err) {
					return res.send(500, err);
				}
				stream
					.on('data', function (data) {
						fin += data;
					})
					.on('close', function (code, signal) {
						res.send(200, { data: fin, code: code, signal: signal });
						conn.end();
					});
			});
		});

		conn.connect({
			host: '10.0.0.76',
			port: 22,
			username: '******',
			privateKey: require('fs').readFileSync('/home/ubuntu/prerender.pem'),
		});
	});
Пример #4
0
 it('should return auth header if success', function(done) {
     TestAuthenticator.SSH_VALID = true;
     var conn = new Client();
     conn.on('ready', function(err) {
         conn.exec('git-lfs-authenticate user/repo.git download', function(err, stream) {
             if (err) return done(err);
             var result;
             stream.on('close', function(code, signal) {
                 conn.end();
             }).on('data', function(data) {
                 let resultObject = JSON.parse(data);
                 should.exist(resultObject.header);
                 should.exist(resultObject.header['Authorization']);
                 should.exist(resultObject.href);
                 resultObject.href.should.equal(`${BASE_URL}:${PORT}/user/repo.git`);
                 done();
             });
         });
     }).connect({
         host: '127.0.0.1',
         port: SSH_PORT,
         username: '******',
         privateKey: fs.readFileSync('./ssh/client.pri')
     });
 });
Пример #5
0
router.get('/:ip', function(req, res, next) {

    var conn = new Client();
    conn
        .on('keyboard-interactive',
            function(name, instructions, instructionsLang, prompts, finish) {
                // Pass answers to `prompts` to `finish()`. Typically `prompts.length === 1`
                // with `prompts[0] === "Password: "`
                finish(['test']);
            })
        .on('ready', function() {
            console.log('Client :: ready');
            conn.exec('uptime', function(err, stream) {
                if (err) throw err;
                stream.on('close', function(code, signal) {
                    console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                    conn.end();
                }).on('data', function(data) {
                    console.log('STDOUT: ' + data);
                }).stderr.on('data', function(data) {
                    console.log('STDERR: ' + data);
                });
            });
        })
        .connect({
            host: 'localhost',
            port: 22,
            username: '******',
            tryKeyboard: true
        });

    console.log(req);

    res.send('respond with a ip');
});
Пример #6
0
function maybeTunnel (redis, config) {
  let bastions = match(config, /_BASTIONS/)
  let hobby = redis.plan.indexOf('hobby') === 0
  let uri = url.parse(redis.resource_url)

  if (bastions != null) {
    let tunnel = new Client()
    tunnel.on('ready', function () {
      let localPort = Math.floor(Math.random() * (65535 - 49152) + 49152)
      tunnel.forwardOut('localhost', localPort, uri.hostname, uri.port, function (err, stream) {
        if (err) {
          cli.error(err)
        }
        stream.on('close', function () {
          tunnel.end()
        })
        redisCLI(uri, stream)
      })
    })
    tunnel.connect({
      host: bastions.split(',')[0],
      username: '******',
      privateKey: match(config, /_BASTION_KEY/)
    })
  } else {
    let client
    if (!hobby) {
      client = tls.connect({port: parseInt(uri.port, 10) + 1, host: uri.hostname, rejectUnauthorized: false})
    } else {
      client = net.connect({port: uri.port, host: uri.hostname})
    }
    redisCLI(uri, client)
  }
}
Пример #7
0
 return new Promise(function (resolve, reject) {
     var output = []
     var exitCode = 0;
     var conn = new Client();
     conn.on('ready', function () {
         console.log('Executing command: ' + command + ' @ ' + ssh_config.host);
         conn.exec(command, function (err, stream) {
             if (err) reject(err);
             stream.on('close', function (code, signal) {
                 conn.end();
                 if (exitCode !== 0)
                     reject('Exit code: ' + exitCode);
                 else {
                     resolve(output.join('\n'));
                 }
                 console.log('Exit code: ' + exitCode);
             }).on('data', function (data) {
                 output.push(data);
                 console.log('STDOUT: ' + data);
             }).on('exit', function (code) {
                 exitCode = code;
             }).stderr.on('data', function (data) {
                 console.log('STDERR: ' + data);
             });
         });
     }).connect(ssh_config);
 });
Пример #8
0
var reconnect = function (callback) {
  conn = new Client();
  conn.on('ready', function() {
    log.info("Connected to ssh-server!");
    conn.sftp(function(err, sftp) {
      if (err) {
        log.error("Couldn't initialize sftp-session!");
        process.exit(1);
      }
      sftp_session = sftp;
      if (firstConnect) {
        callback();
      } firstConnect = false;
    });
  }).on('error', function (err) {
    log.error("The remote server-connection couldn't be established:", err);
  }).on('close', function() {
    log.error("The connection was closed.");
    log.info("Reconnecting in 15s...");
    setTimeout(function () {reconnect(callback);}, 15000);
  }).connect({
    host: config.address,
    port: config.port,
    username: config.username,
    privateKey: require('fs').readFileSync(config.privatekey_path)
  });

  log.info("Connecting to ssh-server...");
};
Пример #9
0
gulp.task('deploy:swellrt', function(done) {
  var connection = new ssh();

  connection.on('ready', function() {
    var cmd = 'SWELLRT_VERSION=' + config.deploy.swellrt.tag +
          ' docker-compose -f ' + config.deploy.swellrt.config +
          ' -p ' + config.deploy.swellrt.name +
          ' up -d';

    console.log(cmd);

    connection.exec(cmd, function(err, stream) {

      if (err) { throw err ; }

      stream.
        on('data', function(d) {
          console.log('ssh: ' + d);
        }).
        on('close', function() {
          done();
          connection.end();
        }).
        stderr.on('data', function(data) { console.log('STDERR: ' + data); });
    });
  }).connect(config.deploy.swellrt.ssh);
});
Пример #10
0
  return new Promise((resolve, reject) => {
    let conn = new Client();
    conn.on('ready', function() {
      conn.exec('sudo shutdown now', function(err, stream) {
        if (err) {
          logService.error('Shutting down command error: ', err);
          reject(err);
          return;
        }

        stream.on('close', function() {
          conn.end();
          resolve();
        });
      });
    });

    conn.on('error', function(err) {
      logService.error('Shutting down connection error: ', err);
      reject(err);
    });

    conn.connect({
      host: '127.0.0.1',
      port: 22,
      username: config.configuration.shutdown.username,
      password: config.configuration.shutdown.password
    });
  });
Пример #11
0
 _initSSH(deploy) {
     const auths = deploy._getConnectOptions();
     const ssh2 = new SSH2();
     ssh2.on('ready', this._onReady.bind(this, deploy, ssh2, this._recursion));
     ssh2.on('error', err => T.log.error(err.message));
     ssh2.connect(auths);
 }
Пример #12
0
 constructor(delegate: SshConnectionDelegate, connection?: SshConnection) {
   this._delegate = delegate;
   this._connection = connection ? connection : new SshConnection();
   this._connection.on('ready', this._onConnect.bind(this));
   this._connection.on('error', this._onSshConnectionError.bind(this));
   this._connection.on('keyboard-interactive', this._onKeyboardInteractive.bind(this));
 }
addresses.forEach(function (a) { // For each IP Address

// Where to store the files
var nginxFile = "/[CHOOSE YOUR OWN ADVENTURE]/" + currDate + "/nginx-error" + i++ + ".log";
var phpFile = "/[CHOOSE YOUR OWN ADVENTURE]/" + currDate + "/php-error" + i++ + ".log";

  var conn = new Client();
  conn.on('ready', function() {
    conn.sftp(function(err, sftp) {
      if (err) throw err;
      // Get nginx-error.log files
      sftp.fastGet(nginxRemote, nginxFile,function(err) {
      if (err) throw err;
      console.log('Getting file...');
      });
      // Get php-error.log files
      sftp.fastGet(phpRemote, phpFile,function(err) {
      if (err) throw err;
      console.log('Getting file...');
      // End the connection when you've downloaded all the files: 2 files on 6 different servers.
      // This will be your number of app servers x 2.
      if (i == 12) {
        conn.end();
      }
      });            
    });
  }).connect({
      host: a,
      port: 2222,
      username: usr,
      privateKey: fs.readFileSync('[/YOUR PATH TO FREEDOM/].ssh/id_rsa', 'utf8')
    });

   }); // End of forEach.
Пример #14
0
// ssh to server
function sshToRemote() {
  console.info('connect to ' + sshConfig.host);
  const conn = new Client();
  conn
    .on('ready', async () => {
      console.info('connect success');
      conn.shell(async (err, stream) => {
        if (err) {
          console.error(err);
          return conn.end();
        }

        const isRestart = cmd.startsWith('restart');
        const exec = cmd => stream.write(`${cmd}\n`);
        const endSymbol = '>>ConnectEnd<<';
        stream.stdout.on('data', chunk => {
          process.stdout.write(chunk);
          if (chunk.toString().includes(`\n${endSymbol}`)) {
            console.timeEnd('update cost');
            stream.end();
            conn.end();
          }
        });
        stream.stderr.pipe(process.stderr);

        exec('ls');
        exec('cd blog');
        exec('ls');

        // clean files
        exec(`rm -rf ${getCleanFiles().join(' ')}`);

        // unzip new file
        exec('unzip -uo ./pack.zip');

        if (isRestart && !skipDeps) {
          // reinstall deps
          exec('rm -rf ./node_modules/');
          exec('npm install --production');
        }

        // execute command
        if (cmd && pkgInfo.scripts[cmd]) {
          exec(`time npm run ${cmd}\n`);
        }

        // show process
        isRestart && exec(`ps aux | grep ${pkgInfo.name}`);

        // end
        exec(`echo '${endSymbol}'`);
      });
    })
    .connect({
      host: sshConfig.host,
      port: sshConfig.port,
      privateKey: fs.readFileSync(sshConfig.privateKey),
      username: sshConfig.username,
    });
}
Пример #15
0
function connectToServer( host, port, username, password, callback ){
    var connection = new sshClient();

    connection.on( 'ready', function() {
        //console.log( 'Connected' );
        callback( connection );
    })
    .on( 'error', function( error ){
        // handle errors?
        console.log( error );
    })
    .on( 'end', function(){
        //console.log( 'Disconnected' );
    })
    .on( 'close', function( hadError ){
        var message = 'Connection closed';

        if( hadError ){
            message = message + ' due to an error.';
            console.log( message );
        }
    })
    .connect({
        host: host,
        port: port || 22,
        username: username,
        password: password
    });
}
Пример #16
0
var SSHClient = function(opts, accept, reject){
  server = new ssh2.Client();
  server.on('ready', function(){
    accept(server);
  }).on('error', function(err){
    reject(server, err);
  }).connect(opts);
}
Пример #17
0
gulp.task('kill-processes', function () {
    conn = new Client();
    conn.on('ready', function () {
        //var path = config.projectName + '/' + config.startFile;
        var path = config.startFile;
        conn.exec('kill -9 `ps | grep "' + path + '" | grep -v grep | awk \' { print $1 }\'`', execCallback);
    }).connect({ host: config.host, port: config.sshPort, username: config.user, password: config.password });
});
Пример #18
0
 initSSH() {
     if (!this.ssh2) {
         this.ssh2 = new SSH2();
     }
     this.ssh2.on('ready', this._onReady.bind(this));
     this.ssh2.on('error', this.deploy.onError.bind(this.deploy));
     this.ssh2.on('end', this.deploy.onSSHEnd.bind(this.deploy));
     this.ssh2.on('close', this.deploy.onClose.bind(this.deploy));
 }
function commandNCheck(command, res) {


    TheConnection = new TheClient();

    TheConnection.on('ready', function () {

        TheConnection.shell(function (err, stream) {
            if (err) {
                console.log(err);
                console.log('SSH problem detected trying to fix it');
                return;
            }
            console.log('Shell is son');

            var out = '';
            stream.on('close', function () {
                console.log('Stream :: close');
                if (out.search('Active') > 0) {
                    res.send('{"status" : "Active"}');
                    return;
                }
                if (out.search('Installed') > 0) {
                    res.send('{"status" : "Installed"}');
                    return;
                }
                if (out.search('Resolved') > 0) {
                    res.send('{"status" : "Ready"}');
                    return;
                }
                res.send('{"status" : "Not installed"}');

            }).on('data', function (data) {
                //if (!gs) gs = stream;
                //if (gs._writableState.sync == false) process.stdout.write(''+data);
                out = data + out;

            }).stderr.on('data', function (data) {
                console.log('STDERR: ' + data);

            });
            stream.end(command + '\n logout \n');
        });
    });

    TheConnection.connect({
        host: '127.0.0.1',
        port: 8101,
        username: '******',
        privateKey: require('fs').readFileSync('./server/config/karaf.id_dsa'),
        keepaliveInterval: 10000
    });

}
Пример #20
0
 it('should reject if username is not git', function(done) {
     var conn = new Client();
     conn.on('error', function(err) {
         err.message.should.equal('All configured authentication methods failed');
         done();
     }).connect({
         host: '127.0.0.1',
         port: SSH_PORT,
         username: '******'
     });
 });
Пример #21
0
 disconnect(){
   Logger.log("disconnect()");
   if (this.controllerConnected){
     this.controller_connection.end();
     this.controllerConnected = false;
   }
   if (this.soloConnected) {
     this.solo_connection.end();
     this.soloConnected = false;
   }
 }
Пример #22
0
/** 
 * 描述:连接远程电脑 
 * 参数:server 远程电脑凭证;then 回调函数 
 * 回调:then(conn) 连接远程的client对象 
 */
function Connect(server, then) {
    var conn = new Client();
    conn.on("ready", function() {
        then(conn);
    }).on('error', function(err) {
        //console.log("connect error!");  
    }).on('end', function() {
        //console.log("connect end!");  
    }).on('close', function(had_error) {
        //console.log("connect close");  
    }).connect(server);
}
Пример #23
0
 it('should accept if valid publickey', function(done) {
     TestAuthenticator.SSH_VALID = true;
     var conn = new Client();
     conn.on('ready', function(err) {
         done();
     }).connect({
         host: '127.0.0.1',
         port: SSH_PORT,
         username: '******',
         privateKey: fs.readFileSync('./ssh/client.pri')
     });
 });
Пример #24
0
 it('should reject if not using publickey authentication', function(done) {
     var conn = new Client();
     conn.on('error', function(err) {
         err.message.should.equal('All configured authentication methods failed');
         done();
     }).connect({
         host: '127.0.0.1',
         port: SSH_PORT,
         username: '******',
         password: '******'
     });
 });
Пример #25
0
var sshConnect = (callback) => {
    var errCb = (err) => {
        callback(err);
    }
    ssh.on('error', errCb);
    ssh.on('ready', () => {
        console.log("connected");
        ssh.removeListener('error', errCb);
        callback();
    });
    console.log("connecting to host " + conn.host);
    ssh.connect(conn);
}
Пример #26
0
 it('should reject if not valid publickey', function(done) {
     TestAuthenticator.SSH_VALID = false;
     var conn = new Client();
     conn.on('error', function(err) {
         err.message.should.equal('All configured authentication methods failed');
         done();
     }).connect({
         host: '127.0.0.1',
         port: SSH_PORT,
         username: '******',
         privateKey: fs.readFileSync('./ssh/client.pri')
     });
 });
Пример #27
0
function createClient(userConfig, callback) {
  var config = createConfig(userConfig);

  var remoteHost = config.dstHost;
  var remotePort = config.dstPort;
  var localHost = config.localHost;
  var localPort = config.localPort;

  var conn = new Client();
  var errors = [];

  conn.on('ready', function() {
    conn.forwardIn(remoteHost, remotePort, function(err) {
      if (err) {
        errors.push(err);
        throw err;
      }
      console.log('Listening for connections on server on port ' + remotePort + '!');
    });
  });

  conn.on('tcp connection', function(info, accept, reject) {
    var remote;
    var local = new Socket();

    debug('tcp connection', info);
    local.on('error', function(err) {
      errors.push(err);
      if (remote === undefined) {
        reject();
      } else {
        remote.end();
      }
    });

    local.connect(localPort, localHost, function() {
      remote = accept();
      debug('accept remote connection');
      local.pipe(remote).pipe(local);
      if (errors.length === 0) {
        callback(null, true);
      } else {
        callback(errors, null);
      }
    });

  });
  return conn.connect(config);
};
Пример #28
0
remotelog.prototype.connect = function(){
    var connection = new sshClient(),
        _this = this;

    connection.on( 'ready', function() {
        _this.handleMessage( 'Connected' );
        connection.shell( function( error, stream ) {
            if( error ) {
                throw error;
            }

            stream.on( 'close', function() {
                _this.handleMessage( 'Disconnected' );
                connection.end();
            }).on( 'data', function( data ) {
                _this.handleMessage( data );
            }).stderr.on( 'data', function( data ) {
                console.log( 'STDERR: ' + data );
            });

            stream.end( _this.logCommand + '\n' );
        });
    })
    .on( 'error', function( error ){
        // handle errors?
        //console.log( 'got error' );
        _this.handleMessage( error );
    })
    .on( 'end', function(){
        //console.log( 'got end' );
        _this.handleMessage( 'Disconnected' );
    })
    .on( 'close', function( hadError ){
        var message = 'Connection closed';

        if( hadError ){
            message = message + ' due to an error.';
        }

        _this.handleMessage( message );
    })
    .connect( {
        host: _this.serverName + '.' + _this.domain,
        port: 22,
        username: _this.username,
        password: _this.password,
        keepaliveInterval: 30000
    } );
};
Пример #29
0
  return new Promise((resolve, reject) => {
    const start = process.hrtime()
    const conn = new sshRequest()

    conn
      .on('ready', () => {
        resolve()
      })
      .on('error', reject)
      .connect({
        host: connData.hostname,
        port: connData.port,
        username: connData.user
      })
  })
Пример #30
0
router.post('/getFilesForServerFolder', function(req, res,next){
    var folder = req.body;
    var Client = require('ssh2').Client; 
    var conn = new Client();
    conn.on('ready', function() {
      conn.sftp(function(err, sftp) {
        if (err) return res.status(400).json(err);
        sftp.readdir('private/rtorrent/data/TV/'+ folder.filename, function(err, list) {
          if (err) return res.status(400).json(err);         
          res.status(200).json(list);
          conn.end();
        });
      });
    }).connect(connectiondetails);    
});