实现用户身份验证的 GoLang SSH 服务器
时间:2024-02-06
浏览:382
作者:佚名
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《实现用户身份验证的 GoLang SSH 服务器》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
问题内容
我一直在尝试使用 golang(使用 wish 或 ssh libary)创建 ssh 服务器,但我不知道如何进行基于用户的身份验证,以便它可以与 putty 的正常用户名密码提示一起使用示例。
这是我目前拥有的代码:
package main
import (
"context"
"fmt"
"github.com/charmbracelet/wish"
"log"
"os"
"os/signal"
"syscall"
"time"
)
const (
host = "localhost"
port = 2222
)
func main() {
s, err := wish.NewServer(
wish.WithAddress(fmt.Sprintf("%s:%d", host, port)),
wish.WithIdleTimeout(5*time.Second),
wish.WithPasswordAuth(""),
)
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Printf("Starting SSH server on %s:%d", host, port)
go func() {
if err = s.ListenAndServe(); err != nil {
log.Fatalln(err)
}
}()
<-done
log.Println("Stopping SSH server")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() { cancel() }()
if err := s.Shutdown(ctx); err != nil {
log.Fatalln(err)
}
}正确答案
当然,您可以使用 withpasswordauth 来验证用户的密码。
将这一行 wish.withpasswordauth(""), 替换为类似的内容...
wish.WithPasswordAuth(func(ctx ssh.Context, password string) bool {
log.Printf("Password is: %s, Username is: %s", password, ctx.User() )
if ctx.User() == "me" && password == "secret" {
return true
}
return false
}),
然后登录到您的 ssh 服务器,ssh me@localhost -p xxxx,如果您输入 secret 您的程序将继续,否则您的连接将被关闭。
今天关于《实现用户身份验证的 GoLang SSH 服务器》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
