在电子

时间:2016-11-17 04:28:25

标签: node.js angular ssh npm angular-services

我想创建一个使用npm包ssh2 - https://www.npmjs.com/package/ssh2的Angular2服务。

我已经按照我的预期安装和配置了它 - 我的服务代码可以在下面看到(此代码基于ssh2 npm网站上显示的第一个示例和github repo(唯一的变化是我正在使用密码而不是用于身份验证的密钥)):

const Client = require('ssh2').Client;
const fs = require('fs');

import { NextObserver } from 'rxjs/Observer';
import { Observable } from 'rxjs/Rx';

export class SSHClient {
    username: string;
    password: string;
    host: string;
    port: number;
    ssh: any;

    constructor() {
    }

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);

        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;


        console.log("Connecting now...");
        var conn = new Client();
        conn.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: this.host,
          port: this.port,
          username: this.username,
          password: this.password
        });
        console.log("SSH Client created and demo has run");
    }

}

我在我的组件中按照此方式调用服务:

this.ssh.init("username","password","my.little.host",22);

我希望通过控制台获取在我的服务器上通过SSH执行的uptime命令的输出。然而不是那样 - 我明白了:

EXCEPTION: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined
TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (file:///Users/myapp/build/app.js:40259:12)
    at new ServerBrowserComponent (file:///Users/myapp/build/app.js:34158:19)
    at new Wrapper_ServerBrowserComponent (/AppModule/ServerBrowserComponent/wrapper.ngfactory.js:7:18)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (/AppModule/ServerBrowserComponent/host.ngfactory.js:16:38)
    at DebugAppView.AppView.create (file:///Users/myapp/build/app.js:27754:26)
    at DebugAppView.create (file:///Users/myapp/build/app.js:27954:49)
    at ComponentFactory.create (file:///Users/myapp/build/app.js:24393:41)
    at ViewContainerRef_.createComponent (file:///Users/myapp/build/app.js:23441:50)
    at RouterOutlet.activate (file:///Users/myapp/build/app.js:72709:45)
    at ActivateRoutes.placeComponentIntoOutlet (file:///Users/myapp/build/app.js:72207:21)
ORIGINAL STACKTRACE:
Error: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined
TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (ssh.service.ts:49)
    at new ServerBrowserComponent (server.browser.component.ts:31)
    at new Wrapper_ServerBrowserComponent (wrapper.ngfactory.js:7)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (host.ngfactory.js:16)
    at DebugAppView.AppView.create (core.umd.js:9170)
    at DebugAppView.create (core.umd.js:9370)
    at ComponentFactory.create (core.umd.js:5809)
    at ViewContainerRef_.createComponent (core.umd.js:4857)
    at RouterOutlet.activate (router.umd.js:3457)
    at ActivateRoutes.placeComponentIntoOutlet (router.umd.js:2955)
    at resolvePromise (zone-node.js:468)
    at zone-node.js:445
    at ZoneDelegate.invoke (zone-node.js:232)
    at Object.onInvoke (core.umd.js:6206)
    at ZoneDelegate.invoke (zone-node.js:231)
    at Zone.run (zone-node.js:114)
    at zone-node.js:502
    at ZoneDelegate.invokeTask (zone-node.js:265)
    at Object.onInvokeTask (core.umd.js:6197)
    at ZoneDelegate.invokeTask (zone-node.js:264)
Unhandled Promise rejection: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined ; Zone: angular ; Task: Promise.then ; Value: ViewWrappedError TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (file:///Users/myapp/build/app.js:40259:12)
    at new ServerBrowserComponent (file:///Users/myapp/build/app.js:34158:19)
    at new Wrapper_ServerBrowserComponent (/AppModule/ServerBrowserComponent/wrapper.ngfactory.js:7:18)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (/AppModule/ServerBrowserComponent/host.ngfactory.js:16:38)
    at DebugAppView.AppView.create (file:///Users/myapp/build/app.js:27754:26)
    at DebugAppView.create (file:///Users/myapp/build/app.js:27954:49)
    at ComponentFactory.create (file:///Users/myapp/build/app.js:24393:41)
    at ViewContainerRef_.createComponent (file:///Users/myapp/build/app.js:23441:50)
    at RouterOutlet.activate (file:///Users/myapp/build/app.js:72709:45)
    at ActivateRoutes.placeComponentIntoOutlet (file:///Users/myapp/build/app.js:72207:21)
Error: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined(…)

其中大部分似乎都在挣扎,因为:Cannot read property 'connect' of undefined - 但我正在关注示例文档。有人可以帮助我理解为什么这不起作用 - 以及我如何解决它?

我试图将代码从我的项目中拉出来并放入自己的文件中,如下所示:

    const Client = require('ssh2').Client; 
console.log("Connecting now...");
         var conn = new Client();
         conn.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: 'my.little.host',
          port: 22,
          username: 'uname',
          password: 'pwd'
        });
         console.log("SSH Client created and demo has run");

但是我得到了同样的错误:

 var conn = new Client();
                ^

ReferenceError: Client is not defined
    at Object.<anonymous> (/Users/myapp/attempt.js:2:21)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.runMain (module.js:575:10)
    at run (node.js:348:7)
    at startup (node.js:140:9)
    at node.js:463:3

这里有一些简单的问题,它可能是什么!?

2 个答案:

答案 0 :(得分:3)

ssh2-package用于node.js,而不是frontend / web。

浏览器不能像那样使用网络(电子使用两个进程,浏览器/渲染器-process无法访问您需要的网络功能)

您的电子应用是否有main.js文件?

您需要实现ssh功能的地方。

即。在主进程中,而不是在渲染器进程中。

http://electron.atom.io/docs/tutorial/quick-start/#main-process

答案 1 :(得分:-1)

在我的ssh2包装器(ssh2shell)中,我在类的构造函数中有this.connection = new require('ssh2')();,或者它可以放在init函数中。在实例中创建它可能有所帮助。

"use strict";

class SSHClient {
    constructor() {}

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);
        var ssh = require('ssh2').Client
        this._conn = new ssh();

        console.log("Connecting");

        console.log('Client :: ready');
        var self = this
        this._conn.on('ready', function() {
            self._conn.exec('uptime', function(err, stream) {
                if (err) throw err;

                stream.on('data', function(data) {
                    console.log('STDOUT: ' + data);
                }).stderr.on('data', function(data) {
                    console.log('STDERR: ' + data);
                }).on('close', function(code, signal) {
                    console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                    self._conn.end();
                });
            });
        }).connect({
            host: host,
            port: port,
            username: username,
            password: password
        });

        console.log("SSH Client created and demo has run");
    }
}
module.exports = SSHClient

或者使用我的package ssh2shell ssh连接实例位于ssh2shell实例的sope中,因此您不必担心它。

"use strict";

class SSHClient {
    constructor() {}

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);

        var host = {
            server: {     
                host:         host,
                port:         port,
                userName:     username,
                password:     password
                },
            commands:      [ "uptime" ]
        }

        var SSH2Shell = require ('ssh2shell'),

            //Use a callback function to handle the response text
            callback = function(sessionText){
                console.log("SSH Client created and demo has run");
                console.log("Response:\n" + sessionText)
            }

        //Create a new instance passing in the host object
        this._conn = new SSH2Shell(host)

        //Start the process
        this._conn.connect(callback);
    }
}

module.exports = SSHClient