• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ssh.NewServerConn函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/ssh.NewServerConn函数的典型用法代码示例。如果您正苦于以下问题:Golang NewServerConn函数的具体用法?Golang NewServerConn怎么用?Golang NewServerConn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewServerConn函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: handleLocalSshConn

func handleLocalSshConn(lnConn net.Conn) {
	defer func() {
		if Config.Ssh_Reverse_Proxy.Exit_On_Panic {
			return
		}
		if r := recover(); r != nil {
			Log.Error("Recovered from panic in connection from "+
				lnConn.RemoteAddr().String()+":", r)
		}
	}()

	Log.Info("Received connection from", lnConn.RemoteAddr())

	var sClient *ssh.Client
	psConfig := getProxyServerSshConfig(&sClient)
	psConn, psChans, psReqs, err := ssh.NewServerConn(lnConn, psConfig)
	if err != nil {
		Log.Info("Could not establish connection with " + lnConn.RemoteAddr().String() + ": " + err.Error())
		return
	}
	defer psConn.Close()
	defer sClient.Close()

	go ssh.DiscardRequests(psReqs)

	for newChannel := range psChans {
		handleChannel(newChannel, sClient)
	}

	Log.Info("Lost connection with", lnConn.RemoteAddr())
}
开发者ID:Freeaqingme,项目名称:SshReverseProxy,代码行数:31,代码来源:daemon.go


示例2: listen

func listen(config *ssh.ServerConfig, port int) {
	listener, err := net.Listen("tcp", "0.0.0.0:"+com.ToStr(port))
	if err != nil {
		panic(err)
	}
	for {
		// Once a ServerConfig has been configured, connections can be accepted.
		conn, err := listener.Accept()
		if err != nil {
			log.Error(3, "Error accepting incoming connection: %v", err)
			continue
		}
		// Before use, a handshake must be performed on the incoming net.Conn.
		sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
		if err != nil {
			log.Error(3, "Error on handshaking: %v", err)
			continue
		}

		log.Trace("Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
		// The incoming Request channel must be serviced.
		go ssh.DiscardRequests(reqs)
		go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
	}
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:25,代码来源:ssh.go


示例3: main

func main() {
	mylogger = logger.NewLogger("", 0)

	configPath := flag.String("config", "", "fssh config file")
	flag.Parse()

	if _, err := toml.DecodeFile(*configPath, &config); err != nil {
		mylogger.Fatal(err)
	}

	sshConfig := ssh.ServerConfig{
		PublicKeyCallback: keyHandler,
		PasswordCallback:  passwdHandler,
	}
	sshConfig.AddHostKey(readSecretKey(config.Key))

	s, err := net.Listen("tcp", config.Address+":"+strconv.Itoa(config.Port))
	if err != nil {
		mylogger.Fatal(err)
	}
	defer s.Close()

	for {
		c, err := s.Accept()
		if err != nil {
			mylogger.Fatal(err)
		}

		ssh.NewServerConn(c, &sshConfig)
	}
}
开发者ID:Senior-Design-May1601,项目名称:fssh,代码行数:31,代码来源:main.go


示例4: serve

func (s *Server) serve(conn net.Conn) error {
	config := ssh.ServerConfig{
		PublicKeyCallback: s.config.PublicKeyCallback.wrap(),
		PasswordCallback:  s.config.PasswordCallback.wrap(),
	}

	for _, hostKey := range s.config.HostKeys {
		config.AddHostKey(hostKey)
	}

	serverConn, channelRequestCh, globalRequestCh, err := ssh.NewServerConn(conn, &config)
	if err != nil {
		return err
	}

	// connection succeeded at this point. create the ssh connection and start the go procs.
	newConn := sshConn{
		handler:    s.config.Handler,
		conn:       serverConn,
		newChannel: channelRequestCh,
		requests:   globalRequestCh,
	}
	go newConn.processChannelRequests()
	go newConn.processGlobalRequests()
	return nil
}
开发者ID:jsternberg,项目名称:gitolite,代码行数:26,代码来源:conn.go


示例5: start

func (s *server) start(port string) error {
	socket, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		return err
	}
	log.Infof("Server listening on :%s :)", port)
	for {
		conn, err := socket.Accept()
		if err != nil {
			log.Errorf("unable to accept connection %v", err)
			continue
		}

		// From a standard TCP connection to an encrypted SSH connection
		sshConn, newChans, _, err := ssh.NewServerConn(conn, s.config)
		if err != nil {
			log.Errorf("ssh handshake failed, %v", err)
			continue
		}
		defer sshConn.Close()

		log.Infof("connection from %s", sshConn.RemoteAddr())
		go func() {
			for chanReq := range newChans {
				go s.handleChanReq(chanReq, sshConn.Permissions.CriticalOptions)
			}
		}()
	}
}
开发者ID:robinmonjo,项目名称:dockpack,代码行数:29,代码来源:server.go


示例6: Handle

func (c *adapter) Handle(conn net.Conn, ui packer.Ui) error {
	log.Print("SSH proxy: accepted connection")
	_, chans, reqs, err := ssh.NewServerConn(conn, c.config)
	if err != nil {
		return errors.New("failed to handshake")
	}

	// discard all global requests
	go ssh.DiscardRequests(reqs)

	// Service the incoming NewChannels
	for newChannel := range chans {
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}

		go func(ch ssh.NewChannel) {
			if err := c.handleSession(ch); err != nil {
				c.ui.Error(err.Error())
			}
		}(newChannel)
	}

	return nil
}
开发者ID:arizvisa,项目名称:packer,代码行数:26,代码来源:adapter.go


示例7: handleConn

func handleConn(conn net.Conn, handler Handler, config *ssh.ServerConfig) {
	sconn, channels, requests, err := ssh.NewServerConn(conn, config)
	if err != nil {
		conn.Close()
		// TODO: log
		fmt.Printf("Error accepting serverconn: %v\n", err)
		return
	}
	defer sconn.Close()

	go func() {
		for request := range requests {
			request.Reply(false, nil)
		}
	}()
	channel, requests, err := getSession(channels)
	if err != nil {
		fmt.Printf("Error getting session channel: %v\n", err)
		return
	}
	go ignoreChannels(channels)
	err = prepHandle(channel, requests, handler)
	if err != nil {
		fmt.Printf("Error in prephandle: %v\n", err)
		return
	}
}
开发者ID:PieterD,项目名称:crap,代码行数:27,代码来源:server.go


示例8: Handle

// Handle is the SSH client entrypoint, it takes a net.Conn
// instance and handle all the ssh and ssh2docker stuff
func (s *Server) Handle(netConn net.Conn) error {
	if err := s.Init(); err != nil {
		return err
	}

	log.Debugf("Server.Handle netConn=%v", netConn)
	// Initialize a Client object
	conn, chans, reqs, err := ssh.NewServerConn(netConn, s.SshConfig)

	if err != nil {
		log.Infof("Received disconnect from %s: 11: Bye Bye [preauth]", netConn.RemoteAddr().String())
		return err
	}
	client := NewClient(conn, chans, reqs, s)

	// Handle requests
	if err = client.HandleRequests(); err != nil {
		return err
	}

	// Handle channels
	if err = client.HandleChannels(); err != nil {
		return err
	}
	return nil
}
开发者ID:moul,项目名称:ssh2docker,代码行数:28,代码来源:server.go


示例9: handleConn

// handleConn handles an individual client connection.
//
// It manages the connection, but passes channels on to `answer()`.
func (s *server) handleConn(conn net.Conn, conf *ssh.ServerConfig) {
	defer conn.Close()
	log.Info("Accepted connection.")
	sshConn, chans, reqs, err := ssh.NewServerConn(conn, conf)
	if err != nil {
		// Handshake failure.
		log.Err("Failed handshake: %s", err)
		return
	}

	// Discard global requests. We're only concerned with channels.
	go ssh.DiscardRequests(reqs)

	condata := sshConnection(conn)

	// Now we handle the channels.
	for incoming := range chans {
		log.Info("Channel type: %s\n", incoming.ChannelType())
		if incoming.ChannelType() != "session" {
			incoming.Reject(ssh.UnknownChannelType, "Unknown channel type")
		}

		channel, req, err := incoming.Accept()
		if err != nil {
			// Should close request and move on.
			panic(err)
		}
		go s.answer(channel, req, condata, sshConn)
	}
	conn.Close()
}
开发者ID:aledbf,项目名称:builder,代码行数:34,代码来源:server.go


示例10: newMockLineServer

func newMockLineServer(t *testing.T) string {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("Unable to listen for connection: %s", err)
	}

	go func() {
		defer l.Close()
		c, err := l.Accept()
		if err != nil {
			t.Errorf("Unable to accept incoming connection: %s", err)
		}
		defer c.Close()
		conn, chans, _, err := ssh.NewServerConn(c, serverConfig)
		if err != nil {
			t.Logf("Handshaking error: %v", err)
		}
		t.Log("Accepted SSH connection")
		for newChannel := range chans {
			channel, _, err := newChannel.Accept()
			if err != nil {
				t.Errorf("Unable to accept channel.")
			}
			t.Log("Accepted channel")

			go func(channelType string) {
				defer channel.Close()
				conn.OpenChannel(channelType, nil)
			}(newChannel.ChannelType())
		}
		conn.Close()
	}()

	return l.Addr().String()
}
开发者ID:c12simple,项目名称:packer,代码行数:35,代码来源:communicator_test.go


示例11: handleConnection

func (server *Server) handleConnection(conn net.Conn) {
	showConnCount := func() {
		server.Logger.Debugf("Current Connections: (%d/%d)",
			atomic.LoadInt32(&server.ClientCount), server.Config.MaxClient)
	}

	defer func() {
		conn.Close()
		server.Logger.Debugf("The connection from %s is closed", conn.RemoteAddr().String())
		atomic.AddInt32(&server.ClientCount, -1)
		showConnCount()
	}()

	atomic.AddInt32(&server.ClientCount, 1)
	showConnCount()
	if atomic.LoadInt32(&server.ClientCount) > server.Config.MaxClient {
		server.Logger.Errorf("Failed to accept incoming connection due to too many connections (%d/%d)",
			server.ClientCount, server.Config.MaxClient)
		return
	}

	sshConnection, chans, reqs, err := ssh.NewServerConn(conn, server.ServerConfig)
	if err != nil {
		if err != io.EOF {
			server.Logger.Errorf("Failed to start SSL connection with %s due to %s",
				conn.RemoteAddr().String(), err)
		}
		return
	}
	server.Logger.Debugf("Built SSL connection with %s, sessionId: %s, client version: %s, user: %s",
		conn.RemoteAddr().String(), hex.EncodeToString(sshConnection.SessionID()),
		sshConnection.ClientVersion(), sshConnection.User())
	go ssh.DiscardRequests(reqs)
	server.handleChannels(chans, sshConnection)
}
开发者ID:bachue,项目名称:pages,代码行数:35,代码来源:sshd.go


示例12: StartSSHD

// StartSSHD starts the ssh server on address:port provided
func StartSSHD(addr string) error {
	handler.Board = make(map[string]*handler.Handler, 0)

	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return fmt.Errorf("Failed to listen on %v port. Reason: (%s)", addr, err.Error())
	}

	fmt.Printf("GoSSHa is listening on %v port!\n", addr)

	for {
		tcpConn, err := listener.Accept()
		if err != nil {
			fmt.Printf("Failed to accept incoming connection (%s)\n", err)
			continue
		}
		h := handler.New()
		config := h.MakeSSHConfig()
		_, chans, reqs, err := ssh.NewServerConn(tcpConn, config)
		//		sshConn, chans, reqs, err := ssh.NewServerConn(tcpConn, config)
		if err != nil {
			fmt.Printf("Failed to handshake (%s)\n", err.Error())
			continue
		}

		//		fmt.Sprintf("New SSH connection from %s (%s)", sshConn.RemoteAddr(), sshConn.ClientVersion())
		go ssh.DiscardRequests(reqs)
		go handleChannels(chans, &h)
	}
}
开发者ID:vodolaz095,项目名称:gossha,代码行数:31,代码来源:ssh.go


示例13: HandleConnection

func (p *Proxy) HandleConnection(netConn net.Conn) {
	logger := p.logger.Session("handle-connection")
	defer netConn.Close()

	serverConn, serverChannels, serverRequests, err := ssh.NewServerConn(netConn, p.serverConfig)
	if err != nil {
		return
	}
	defer serverConn.Close()

	clientConn, clientChannels, clientRequests, err := NewClientConn(logger, serverConn.Permissions)
	if err != nil {
		return
	}
	defer clientConn.Close()

	emitLogMessage(logger, serverConn.Permissions)

	go ProxyGlobalRequests(logger, clientConn, serverRequests)
	go ProxyGlobalRequests(logger, serverConn, clientRequests)

	go ProxyChannels(logger, clientConn, serverChannels)
	go ProxyChannels(logger, serverConn, clientChannels)

	Wait(logger, serverConn, clientConn)
}
开发者ID:sykesm,项目名称:diego-ssh,代码行数:26,代码来源:proxy.go


示例14: main

func main() {
	config := ssh.ServerConfig{
		PublicKeyCallback: keyAuth,
	}
	config.AddHostKey(hostPrivateKeySigner)

	port := "2222"
	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
	}
	socket, err := net.Listen("tcp", ":"+port)
	if err != nil {
		panic(err)
	}

	for {
		conn, err := socket.Accept()
		if err != nil {
			panic(err)
		}

		// From a standard TCP connection to an encrypted SSH connection
		sshConn, _, _, err := ssh.NewServerConn(conn, &config)
		if err != nil {
			panic(err)
		}

		log.Println("Connection from", sshConn.RemoteAddr())
		sshConn.Close()
	}
}
开发者ID:psihodelik,项目名称:go-ssh-examples,代码行数:31,代码来源:server.go


示例15: handleSSHRequest

func (self *ServerMode) handleSSHRequest(connection *net.Conn, config *ssh.ServerConfig) {

	// TODO: Check if we need to close anything.

	// Before use, a handshake must be performed on the incoming net.Conn.
	_, channels, requests, err := ssh.NewServerConn(*connection, config)
	if err != nil {
		panic("failed to handshake")
	}

	// The incoming Request channel must be serviced.
	go ssh.DiscardRequests(requests)

	// Service the incoming Channel channel.
	for newChannel := range channels {
		// Channels have a type, depending on the application level protocol intended. In the case of a shell, the type is
		// "session" and ServerShell may be used to present a simple terminal interface.
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}

		channel, requests, err := newChannel.Accept()
		if err != nil {
			panic("could not accept channel.")
		}

		// Sessions have out-of-band requests such as "shell", "pty-req" and "env".
		// Here we handle only the "shell" request.
		go func(in <-chan *ssh.Request) {
			for req := range in {
				ok := false
				switch req.Type {
				case "shell":
					ok = true
					if len(req.Payload) > 0 {
						// We don't accept any commands, only the default shell.
						ok = false
					}
				}
				req.Reply(ok, nil)
			}
		}(requests)

		term := terminal.NewTerminal(channel, "> ")

		go func() {
			defer channel.Close()
			for {
				line, err := term.ReadLine()
				if err != nil {
					break
				}
				// TODO: Likely we need to interpret the incoming commands in here.
				fmt.Println("INPUT-SSH:" + line)
			}
		}()
	}
}
开发者ID:jkellerer,项目名称:jenkins-client-launcher,代码行数:59,代码来源:server.go


示例16: handleSSH

// handleSSH runs in a goroutine and handles an incoming SSH connection
func (s *SSHServer) handleSSH(conn net.Conn, config ssh.ServerConfig) {

	_, _, _, err := ssh.NewServerConn(conn, &config)
	if err == nil {
		// this should never happen and if it does we need to shutdown the system
		log.Fatal("ssh server error: successful login. Shutting down system\n")
	}
}
开发者ID:gombadi,项目名称:honeygot,代码行数:9,代码来源:ssh.go


示例17: Execute

func (t *tcpHandler) Execute(c context.Context) {
	select {
	case <-c.Done():
		t.conn.Close()
		return
	default:
	}

	// Create reaper
	g := grim.ReaperWithContext(c)
	defer g.Wait()

	// Convert to SSH connection
	sshConn, channels, requests, err := ssh.NewServerConn(t.conn, t.config)
	if err != nil {
		t.logger.Warn("SSH handshake failed:", "addr", t.conn.RemoteAddr().String(), "error", err)
		t.conn.Close()
		g.Kill()
		return
	}

	// Close connection on exit
	t.logger.Debug("Handshake successful")
	defer sshConn.Close()
	defer sshConn.Wait()

	// Discard all out-of-channel requests
	if t.requestHandler != nil {
		go t.requestHandler.Consume(requests)
	} else {
		go ssh.DiscardRequests(requests)
	}

OUTER:
	for {
		select {
		case <-c.Done():
			break OUTER
		case <-g.Dead():
			break OUTER
		case ch := <-channels:

			// Check if chan was closed
			if ch == nil {
				break OUTER
			}

			// Handle the channel
			g.SpawnFunc(func(ctx context.Context) {
				t.dispatcher.Dispatch(ctx, sshConn, ch)
				return
			})
		}
	}

	g.Kill()
}
开发者ID:blacklabeldata,项目名称:sshh,代码行数:57,代码来源:server.go


示例18: handleSSH

// handleSSH runs in a goroutine and handles an incoming SSH connection
func handleSSH(conn net.Conn, config ssh.ServerConfig) {

	_, _, _, err := ssh.NewServerConn(conn, &config)
	if err == nil {
		log.Fatal("ssh server error: successful login. Shutting down system\n")
	}
	// goroutine ends
	conn.Close()
}
开发者ID:gombadi,项目名称:simplessh,代码行数:10,代码来源:simplessh.go


示例19: main

func main() {

	config := &ssh.ServerConfig{
		//Define a function to run when a client attempts a password login
		PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
			// Should use constant-time compare (or better, salt+hash) in a production setting.
			if c.User() == "vagrant" && string(pass) == "vagrant" {
				return nil, nil
			}
			return nil, fmt.Errorf("password rejected for %q", c.User())
		},
		// NoClientAuth: true,
	}

	// You can generate a keypair with 'ssh-keygen -t rsa'
	privateBytes, err := ioutil.ReadFile("gossh_rsa")
	if err != nil {
		log.Fatal("Failed to load private key (./gossh_rsa)")
	}

	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		log.Fatal("Failed to parse private key")
	}

	config.AddHostKey(private)

	// Once a ServerConfig has been configured, connections can be accepted.
	socket, err := net.Listen("tcp", "0.0.0.0:2200")
	if err != nil {
		log.Fatalf("Failed to listen on 2200 (%s)", err)
	}

	for {
		conn, err := socket.Accept()
		if err != nil {
			panic(err)
		}

		// From a standard TCP connection to an encrypted SSH connection
		sshConn, newChans, _, err := ssh.NewServerConn(conn, config)
		if err != nil {
			panic(err)
		}
		defer sshConn.Close()

		log.Println("Connection from", sshConn.RemoteAddr())
		go func() {
			for chanReq := range newChans {
				go handleChanReq(chanReq)
			}
		}()
	}

}
开发者ID:slawosz,项目名称:ssh-commander,代码行数:55,代码来源:server2.go


示例20: ListenAndServe

// ListenAndServe starts a SCP server.
func (s *Server) ListenAndServe() {
	if len(s.BindAddr) == 0 {
		panic("Must specify BindAddr")
	}
	if len(s.CertPath) == 0 {
		panic("Must specify CertPath")
	}

	privateBytes, err := ioutil.ReadFile(s.CertPath)
	if err != nil {
		panic("Failed to load private key")
	}

	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Failed to parse private key")
	}

	config := &ssh.ServerConfig{
		NoClientAuth: true,
	}

	config.AddHostKey(private)

	// Once a ServerConfig has been configured, connections can be
	// accepted.
	listener, err := net.Listen("tcp", s.BindAddr)
	if err != nil {
		s.Fatal("Failed to bind to address", "addr", bindAddr)
	}

	s.Info("Listening for SCP connections", "addr", bindAddr)

	for {
		nConn, err := listener.Accept()
		if err != nil {
			s.Error("Failed to listen for SCP connections", "err", err)
			continue
		}

		// Before use, a handshake must be performed on the incoming
		// net.Conn.
		_, chans, reqs, err := ssh.NewServerConn(nConn, config)
		if err != nil {
			s.Error("Failed to create SCP connection", "err", err)
			continue
		}

		// Discard all global out-of-band Requests
		go ssh.DiscardRequests(reqs)

		// Accept all channels
		go s.handleChannels(chans)
	}
}
开发者ID:zqzca,项目名称:back,代码行数:56,代码来源:scp.go



注:本文中的golang.org/x/crypto/ssh.NewServerConn函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ssh.NewSignerFromKey函数代码示例发布时间:2022-05-28
下一篇:
Golang ssh.NewPublicKey函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap