dongshuang0011 2018-02-17 08:44
浏览 433

Golang中的SSH服务器

I am trying the github.com/gliderlabs/ssh package in order to build a ssh server. The example are working fine. The code below listen and reply some text when I connect, then close the connection.

I would like to keep it open, listening to user input (lines) and echoing "you say : "... but I have no idea of what to do and it seems this is too simple to be explained somewhere.

Can someone give me an indication of what to do ?

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"

    "github.com/gliderlabs/ssh"
)

func main() {
    ssh.Handle(func(s ssh.Session) {

        io.WriteString(s, fmt.Sprintf("Hello %s
", s.User()))
        io.WriteString(s, fmt.Sprintf("Hello 2%s
", s.User()))
        io.WriteString(s, fmt.Sprintf("Hello 3%s
", s.User()))     

        text,err:= bufio.NewReader(s).ReadString('
')
        if err != nil  {
            panic("GetLines: " + err.Error())
        }

        io.WriteString(s, fmt.Sprintf("ton texte %s
", text))   
    })

    log.Println("starting ssh server on port 2223...")
    log.Fatal(ssh.ListenAndServe(":2223", nil))
}
  • 写回答

1条回答 默认 最新

  • duannima8347 2018-11-12 09:14
    关注

    If question is still actual, you shoud use for{} cycle inside handler, and always read input. BTW, it's more suitable to use "golang.org/x/crypto/ssh/terminal" package.

    Here's little example:

    func (s *Server) handler(sess ssh.Session) {
    ...
        term := terminal.NewTerminal(sess, "> ")
            for {
                line, err := term.ReadLine()
                if err != nil {
                    break
                }
                response := router(line)
                log.Println(line)
                if response != "" {
                    term.Write(append([]byte(response), '
    '))
                }
            }
            log.Println("terminal closed")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献