tofgau
tofgau

Reputation: 73

ssh server in golang

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\n", s.User()))
        io.WriteString(s, fmt.Sprintf("Hello 2%s\n", s.User()))
        io.WriteString(s, fmt.Sprintf("Hello 3%s\n", s.User()))     

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

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

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

Upvotes: 0

Views: 3645

Answers (1)

Ilya T
Ilya T

Reputation: 11

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), '\n'))
            }
        }
        log.Println("terminal closed")
}

Upvotes: 1

Related Questions