Golang中的SSH服务器

我正在尝试 github.com/gliderlabs/ssh </ strong>软件包以构建一个 ssh服务器。
示例运行良好。
连接后,下面的代码侦听并回复一些文本,然后关闭连接。</ p>

我想保持打开状态,倾听用户的声音 输入(行)并回显“您说:” ...,但是我不知道该怎么办,而且似乎太简单了,无法在某处解释。</ p>

有人可以给我吗 </ p>

  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('
')
如果出现错误!= 无{
锅 ic(“ GetLines:” + err.Error())
}

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

log.Println(“正在启动2223端口上的ssh服务器...”)
log.Fatal(ssh.ListenAndServe(“:2223”,nil))
}
</ code> </ pre>
< / DIV>

展开原文

原文

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))
}

ssh
dsms21398
dsms21398 正确的ssh是传输流的一种方式。但是,我的问题是如何充分聆听帽子隧道的尽头。(我有一些代码,但我无法粘贴它)
2 年多之前 回复
douwen5741
douwen5741 我认为这不是ssh的目的。它确保了连接的安全性,而不是假设自己要做某事。例如,您可以通过ssh连接到远程bash,然后安全地使用远程bash。serverfault.com/questions/167416/...
2 年多之前 回复

1个回答

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")
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问