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

Golang terminal.NewTerminal函数代码示例

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

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



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

示例1: startTerminal

func startTerminal(c *config) {
	var clear, protected bool

	fmt.Println("Starting terminal mode.")
	fmt.Println("Enter h for [h]elp.")
	fmt.Println("Enter l for [l]ist of commands.")
	fmt.Println("Enter q for [q]uit.")

	termState, err := terminal.MakeRaw(int(os.Stdin.Fd()))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to set raw mode on STDIN: %v\n",
			err)
		return
	}
	n := terminal.NewTerminal(os.Stdin, "> ")
	n.SetSize(int(^uint(0)>>1), 0)

	var ln string
	for {
		if !protected {
			ln, err = n.ReadLine()
		} else {
			ln, err = n.ReadPassword(">*")
		}
		terminal.Restore(int(os.Stdin.Fd()), termState)
		if err != nil {
			break
		}

		quit := execute(&protected, c, ln, &clear)
		if quit {
			break
		}

		if clear {
			fmt.Println("Clearing history...")
			termState, err = terminal.MakeRaw(int(os.Stdin.Fd()))
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to set raw "+
					"mode on STDIN: %v\n", err)
				break
			}
			n = terminal.NewTerminal(os.Stdin, "> ")
			n.SetSize(int(^uint(0)>>1), 0)
			clear = false
		} else {
			termState, err = terminal.MakeRaw(int(os.Stdin.Fd()))
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to set raw "+
					"mode on STDIN: %v\n", err)
				break
			}
		}
	}
	fmt.Println("exiting...")
}
开发者ID:decred,项目名称:dcrd,代码行数:56,代码来源:terminal.go


示例2: NewCLI

// NewCLI creates a new cliUI instance
func NewCLI(version string) UI {
	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		panic(err.Error())
	}

	term := terminal.NewTerminal(os.Stdin, "")
	updateTerminalSize(term)
	term.SetBracketedPasteMode(true)

	resizeChan := make(chan os.Signal)
	go func() {
		for _ = range resizeChan {
			updateTerminalSize(term)
		}
	}()
	signal.Notify(resizeChan, syscall.SIGWINCH)

	return &cliUI{
		term:      term,
		oldState:  oldState,
		terminate: make(chan bool),
		input: &input{
			term:        term,
			uidComplete: new(priorityList),
		},
		RosterEditor: RosterEditor{
			PendingRosterChan: make(chan *RosterEdit),
		},
		events:   make(chan interface{}),
		commands: make(chan interface{}, 5),
	}
}
开发者ID:PMaynard,项目名称:coyim,代码行数:34,代码来源:ui.go


示例3: promptConfirm

// promptConfirm prompts a user to confirm (or deny) something.
//
// True is returned iff the prompt is confirmed.
// Errors are reported to the log, and return false.
//
// Valid confirmations:
// 	y, yes, true, t, aye-aye
//
// Valid denials:
//	n, no, f, false
//
// Any other prompt response will return false, and issue a warning to the
// user.
func promptConfirm(msg string) bool {
	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		log.Err("Could not get terminal: %s", err)
		return false
	}
	defer terminal.Restore(0, oldState)

	f := readerWriter(log.Stdin, log.Stdout)
	t := terminal.NewTerminal(f, msg+" (y/N) ")
	res, err := t.ReadLine()
	if err != nil {
		log.Err("Could not read line: %s", err)
		return false
	}
	res = strings.ToLower(res)
	switch res {
	case "yes", "y", "true", "t", "aye-aye":
		return true
	case "no", "n", "false", "f":
		return false
	}
	log.Warn("Did not understand answer %q, assuming No", res)
	return false
}
开发者ID:colonelmo,项目名称:helm,代码行数:38,代码来源:uninstall.go


示例4: 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


示例5: sshHandleChannel

func sshHandleChannel(conn net.Conn, newChannel ssh.NewChannel) {
	// 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")
		return
	}
	channel, requests, err := newChannel.Accept()
	if err != nil {
		log.Errorln(err)
		return
	}

	// 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
				}
			case "pty-req":
				ok = true
			}
			req.Reply(ok, nil)
		}
	}(requests)

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

	go func() {
		defer channel.Close()

		for {
			line, err := term.ReadLine()
			start := time.Now().UnixNano()
			if err != nil {
				if err != io.EOF {
					log.Errorln(err)
				}
				return
			}
			sshReportChan <- uint64(len(line))
			// just echo the message
			log.Debugln("ssh received: ", line)
			term.Write([]byte(line))
			term.Write([]byte{'\r', '\n'})

			stop := time.Now().UnixNano()
			log.Info("ssh %v %vns", conn.RemoteAddr(), uint64(stop-start))
		}
	}()
}
开发者ID:cdshann,项目名称:minimega,代码行数:58,代码来源:ssh.go


示例6: startTerminal

func (s *shellHandler) startTerminal(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel) error {
	defer channel.Close()

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

	// // Try to make the terminal raw
	// oldState, err := terminal.MakeRaw(0)
	// if err != nil {
	//     logger.Warn("Error making terminal raw: ", err.Error())
	// }
	// defer terminal.Restore(0, oldState)

	// Get username
	username, ok := sshConn.Permissions.Extensions["username"]
	if !ok {
		username = "user"
	}

	// Write ascii text
	term.Write([]byte(fmt.Sprintf("\r\n Nice job, %s! You are connected!\r\n", username)))
	defer term.Write([]byte(fmt.Sprintf("\r\nGoodbye, %s!\r\n", username)))

	// Start REPL
	for {

		select {
		case <-parentTomb.Dying():
			return nil
		default:
			s.logger.Info("Reading line...")
			input, err := term.ReadLine()
			if err != nil {
				fmt.Errorf("Readline() error")
				return err
			}

			// Process line
			line := strings.TrimSpace(input)
			if len(line) > 0 {

				// Log input and handle exit requests
				if line == "exit" || line == "quit" {
					s.logger.Info("Closing connection")
					return nil
				}

				// Echo input
				channel.Write(term.Escape.Green)
				channel.Write([]byte(line + "\r\n"))
				channel.Write(term.Escape.Reset)
			}
		}
	}
	return nil
}
开发者ID:blacklabeldata,项目名称:sshh,代码行数:56,代码来源:terminal.go


示例7: ReadPassword

// Read a password from stdin without echoing input to stdout.
func ReadPassword(prompt string) (string, error) {
	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		return "", err
	}
	defer terminal.Restore(0, oldState)
	term := terminal.NewTerminal(os.Stdin, "")
	pass, err := term.ReadPassword(prompt)
	return pass, err
}
开发者ID:mpage,项目名称:onepassword,代码行数:11,代码来源:util.go


示例8: newTerm

func newTerm(prompt string) *Term {
	term := new(Term)
	var err error
	term.s, err = terminal.MakeRaw(0)
	if err != nil {
		panic(err)
	}
	term.t = terminal.NewTerminal(os.Stdin, prompt)
	return term
}
开发者ID:zyxar,项目名称:doubanfm,代码行数:10,代码来源:term.go


示例9: terminalInit

func terminalInit() {
	var err error
	oldTermState, err = terminal.MakeRaw(syscall.Stdin)
	if err != nil {
		fatalf("Failed to get raw terminal: %v", err)
	}

	term = terminal.NewTerminal(os.Stdin, prompt)
	term.AutoCompleteCallback = autoComplete
}
开发者ID:Cepave,项目名称:lvs-metrics,代码行数:10,代码来源:main.go


示例10: terminalInit

func (i *Interactive) terminalInit() {
	var err error
	i.oldTermState, err = terminal.MakeRaw(syscall.Stdin)
	if err != nil {
		i.fatalf("Failed to get raw terminal: %v", err)
	}

	i.term = terminal.NewTerminal(os.Stdin, i.Prompt)
	i.term.AutoCompleteCallback = i.defaultAutoComplete
}
开发者ID:justinwalz,项目名称:interaction,代码行数:10,代码来源:interaction.go


示例11: handleChannel

func (server *SshServer) handleChannel(user string, newChannel ssh.NewChannel) {
	if t := newChannel.ChannelType(); t != "session" {
		newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t))
		return
	}

	connection, requests, err := newChannel.Accept()
	if err != nil {
		fmt.Printf("Could not accept channel (%s)", err)
		return
	}
	defer connection.Close()

	logfile, err := os.Create(fmt.Sprintf("%s_%s", user, storyLogFilename(server.story)))
	if err != nil {
		panic(err)
	}
	defer logfile.Close()

	logger := log.New(logfile, "", log.LstdFlags)

	terminal := terminal.NewTerminal(connection, "")
	zsshterm := &gork.ZSshTerminal{Term: terminal}

	zm, err := gork.NewZMachine(server.mem, server.header, zsshterm, logger)
	if err != nil {
		fmt.Println(err)
		return
	}

	go func() {
		for req := range requests {
			switch req.Type {
			case "shell":
				if len(req.Payload) == 0 {
					req.Reply(true, nil)
				}
			case "pty-req":
				termLen := req.Payload[3]
				w, h := parseDims(req.Payload[termLen+4:])
				terminal.SetSize(w, h)
			case "window-change":
				w, h := parseDims(req.Payload)
				terminal.SetSize(w, h)
			}
		}
	}()

	defer func() {
		recover()
	}()

	zm.InterpretAll()

}
开发者ID:d-dorazio,项目名称:gork,代码行数:55,代码来源:sshserver.go


示例12: readCredentials

// Read credentials from standard input
func readCredentials() (username string, password string, err error) {
	state, err := terminal.MakeRaw(0)
	if err == nil {
		t := terminal.NewTerminal(os.Stdin, "Username: ")
		username, err = t.ReadLine()
		if err == nil {
			password, err = t.ReadPassword("Password: ")
		}
		terminal.Restore(0, state)
	}
	return username, password, nil
}
开发者ID:timburks,项目名称:remote,代码行数:13,代码来源:remote.go


示例13: handleConn

func handleConn(nConn net.Conn, config *ssh.ServerConfig) {
	addr := nConn.RemoteAddr().String()
	log.Printf("Connection opened from %s", addr)
	defer log.Printf("Connection closed from %s", addr)

	// Negotiate SSH.  This is where passwords are checked.
	_, chans, _, err := ssh.NewServerConn(nConn, config)
	if err != nil {
		log.Printf("Couldn't handshake %s: %s", addr, err)
	}

	// A ServerConn multiplexes several channels, which must
	// themselves be Accepted.
	for newChannel := range chans {
		// Accept reads from the connection, demultiplexes packets
		// to their corresponding channels and returns when a new
		// channel request is seen. Some goroutine must always be
		// calling Accept; otherwise no messages will be forwarded
		// to the channels.
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}
		channel, _, err := newChannel.Accept()
		if err != nil {
			break
		}

		// 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.
		log.Printf("Channel from %s : %s", addr, newChannel.ChannelType())

		prompt := "$ "
		term := terminal.NewTerminal(channel, prompt)
		go func() {
			defer log.Printf("Channel closed from %s", addr)
			defer channel.Close()

			// Just log every line that the attacker sends.
			for {
				line, err := term.ReadLine()
				if err != nil {
					break
				}
				log.Printf("%s > %s", addr, line)
			}
		}()
	}
}
开发者ID:thatkarlperson,项目名称:fakessh,代码行数:51,代码来源:fakessh.go


示例14: askConfig

func askConfig() (cfg, error) {
	stdinState, err := terminal.MakeRaw(syscall.Stdin)
	if err != nil {
		return cfg{}, err
	}
	defer terminal.Restore(syscall.Stdin, stdinState)
	stdoutState, err := terminal.MakeRaw(syscall.Stdout)
	if err != nil {
		return cfg{}, err
	}
	defer terminal.Restore(syscall.Stdout, stdoutState)
	t := struct {
		io.Reader
		io.Writer
	}{os.Stdin, os.Stdout}

	term := terminal.NewTerminal(t, "")

	msg := "Configure git-erickson for first time use.\nErickson server URL: "
	if _, err := term.Write([]byte(msg)); err != nil {
		return cfg{}, err
	}

	url, err := term.ReadLine()
	if err != nil {
		return cfg{}, err
	}

	cmd := exec.Command("git", "config", "--global", "erickson.url", string(url))
	if err := cmd.Run(); err != nil {
		return cfg{}, err
	}

	if _, err := term.Write([]byte("Erickson username: ")); err != nil {
		return cfg{}, err
	}

	username, err := term.ReadLine()
	if err != nil {
		return cfg{}, err
	}

	cmd = exec.Command("git", "config", "--global", "erickson.username", string(username))
	if err := cmd.Run(); err != nil {
		return cfg{}, err
	}

	return cfg{url: url, username: username}, nil
}
开发者ID:echlebek,项目名称:erickson,代码行数:49,代码来源:main.go


示例15: runTerm

func runTerm(cmd *cobra.Command, args []string) {
	if len(args) != 0 {
		cmd.Usage()
		return
	}

	db := makeSQLClient()

	readWriter := struct {
		io.Reader
		io.Writer
	}{
		Reader: os.Stdin,
		Writer: os.Stdout,
	}

	// We need to switch to raw mode. Unfortunately, this masks
	// signals-from-keyboard, meaning that ctrl-C cannot be caught.
	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = terminal.Restore(0, oldState)
	}()

	term := terminal.NewTerminal(readWriter, "> ")
	for {
		line, err := term.ReadLine()
		if err != nil {
			if err != io.EOF {
				fmt.Fprintf(os.Stderr, "Input error: %s\n", err)
			}
			break
		}
		if len(line) == 0 {
			continue
		}

		shouldExit, err := processOneLine(db, line, term)
		if err != nil {
			fmt.Fprintf(term, "Error: %s\n", err)
		}
		if shouldExit {
			break
		}
	}
}
开发者ID:backend2use,项目名称:cockroachdb,代码行数:48,代码来源:sql.go


示例16: main

func main() {
	if len(os.Args) > 1 {
		input := strings.Replace(strings.Join(os.Args[1:], ""), " ", "", -1)
		res, err := compute.Evaluate(input)
		if err != nil {
			fmt.Println("Error: " + err.Error())
			return
		}
		fmt.Printf("%s\n", decimalToString(res))
		return
	}

	var err error
	regularState, err = terminal.MakeRaw(0)
	if err != nil {
		panic(err)
	}
	defer terminal.Restore(0, regularState)

	term := terminal.NewTerminal(os.Stdin, "> ")
	term.AutoCompleteCallback = handleKey
	for {
		text, err := term.ReadLine()
		if err != nil {
			if err == io.EOF {
				// Quit without error on Ctrl^D
				fmt.Println()
				break
			}
			panic(err)
		}

		text = strings.Replace(text, " ", "", -1)
		if text == "exit" || text == "quit" {
			break
		}

		res, err := compute.Evaluate(text)
		if err != nil {
			fmt.Println("Error: " + err.Error())
			continue
		}
		fmt.Printf("%s\n", res)
	}
}
开发者ID:gpahal,项目名称:calc,代码行数:45,代码来源:main.go


示例17: NewShell

// NewShell returns a new Shell Adapter.
func NewShell(b bot.Bot) bot.Adapter {
	// Get terminal old state.
	state, err := t.MakeRaw(int(os.Stdin.Fd()))
	if err != nil {
		panic(err)
	}

	// Create a new terminal struct.
	term := t.NewTerminal(os.Stdin, "")
	prompt := fmt.Sprintf("\033[36m%s\033[0m> ", b.Name)
	term.SetPrompt(prompt)

	return Shell{
		bot:         b,
		MessagePool: bot.NewMessagePool(),
		Terminal:    term,
		State:       state,
	}
}
开发者ID:szkkentaro,项目名称:g-3po,代码行数:20,代码来源:shell.go


示例18: handleChannel

func handleChannel(ch ssh.Channel) {
	term := terminal.NewTerminal(ch, "> ")
	serverTerm := &ssh.ServerTerminal{
		Term:    term,
		Channel: ch,
	}
	ch.Accept()
	defer ch.Close()
	for {
		line, err := serverTerm.ReadLine()
		if err == io.EOF {
			return
		}
		if err != nil {
			log.Println("handleChannel readLine err:", err)
			continue
		}
		fmt.Println(line)
	}
}
开发者ID:larmog,项目名称:honeypot.go,代码行数:20,代码来源:honeypot.go


示例19: termechoMain

func termechoMain() error {
	oldState, err := terminal.MakeRaw(int(syscall.Stdin))
	if err != nil {
		return err
	}
	defer terminal.Restore(int(syscall.Stdin), oldState)
	fmt.Println("enter 'q' to quit")
	t := terminal.NewTerminal(os.Stdin, "> ")
	for {
		line, err := t.ReadLine()
		if err != nil {
			return err
		}
		if line == "q" {
			break
		}
		fmt.Println(line)
	}
	return nil
}
开发者ID:frankbraun,项目名称:kitchensink,代码行数:20,代码来源:termecho.go


示例20: askCredentials

func askCredentials(username string) (password string, err error) {
	stdinState, err := terminal.MakeRaw(syscall.Stdin)
	if err != nil {
		return
	}
	defer terminal.Restore(syscall.Stdin, stdinState)
	stdoutState, err := terminal.MakeRaw(syscall.Stdout)
	if err != nil {
		return
	}
	defer terminal.Restore(syscall.Stdout, stdoutState)
	t := struct {
		io.Reader
		io.Writer
	}{os.Stdin, os.Stdout}
	term := terminal.NewTerminal(t, "")
	msg := fmt.Sprintf("Password for %s: ", username)
	password, err = term.ReadPassword(msg)
	return
}
开发者ID:echlebek,项目名称:erickson,代码行数:20,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang terminal.ReadPassword函数代码示例发布时间:2022-05-28
下一篇:
Golang terminal.MakeRaw函数代码示例发布时间: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