本文整理汇总了Golang中golang.org/x/crypto/ssh/terminal.NewTerminal函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTerminal函数的具体用法?Golang NewTerminal怎么用?Golang NewTerminal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewTerminal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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...")
}
示例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),
}
}
示例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
}
示例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)
}
}()
}
}
示例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))
}
}()
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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()
}
示例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
}
示例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)
}
}()
}
}
示例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
}
示例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
}
}
}