在nodejs中使用ssh2实现scp功能

Implement scp function by use ssh2 in nodejs

我想用 ssh2 在 nodejs 中实现一个 sshd 服务器,它可以被 ssh 访问,但它不能被 scp 访问,这是我的代码:

_clientConnectCb = (client)->
  logger.info 'Client connected!'
  _code     = null
  _user     = null
  _password = null
  _hostPort = null
  _clientShell = undefined;
  client.on 'authentication', (ctx)->
    if ctx.method is 'password'
      _tmp = ctx.username.split('_')
      _code = _tmp[0]
      _user = _tmp[1]
      if _tmp.length != 2
        ctx.reject()
        return

      util.GetCodeInfo(_code, true, (err, info)->
        if not err and not info.err and info
          _hostPort = info.data
          _password = ctx.password
          logger.info 'user accept', _user, info
          ctx.accept()
        else
          logger.warn err, info
          ctx.reject()
      )
    else
      ctx.reject(["password"])

  client.on 'ready', ->
    logger.info 'Client authenticated!'
    rows = undefined;
    cols = undefined;
    width = undefined;
    height = undefined;
    term = undefined;
    targetShell = undefined;
    client.on 'session', (accept, reject)->
      session = accept()
      session.once("exec", (accept, reject, info)->
        // when access by scp, 'exec' event will emit, but what to do next
        console.log('Client wants to execute: ', info.command);
        stream = accept();
  client.on 'end', ->
    logger.info 'Client disconnected'

  client.on 'error', (err)->
    logger.info 'client failed:', err
server = new Server {privateKey: fs.readFileSync(__dirname + "/ssh-rsa/#{config.rsaKey}")}, _clientConnectCb
server.listen config.port, '0.0.0.0', ->logger.info 'ssh proxy on port ' + @address().port

您已经为所请求的命令创建了 stream。随心所欲地回应。

您可以使用来自 info.command 的命令字符串调用 child_process.spawn(),然后在该子进程和 stream 之间进行管道传输。但是,您应该注意 validating/securing info.command 并确保它是在他们登录的用户下执行的,等等