Home > Software design >  golang ssh write backspace to stdin
golang ssh write backspace to stdin

Time:06-27

I am writing an ssh client to parse the configuration of a switch. This is not an interactive client. In some cases, I need to erase part of the previous typed command. If I was using PuTTY, I would do it by pressing the backspace button or the Ctrl-X keyboard shortcuts.

How to send a Ctrl-X or Backspace command to the server? I've already tried sending \b and 0x08 and in this case it doesn't work as expected.

Below exemplary code without error handling etc...

Dial and write:

 c,_ := ssh.Dial( <dial ,_parameters> )
 session, _= c.NewSession()
 
 modes := ssh.TerminalModes{
        ssh.ECHO:          0,     // disable echoing
        ssh.TTY_OP_ISPEED: 38400, // input speed = 14.4kbaud
        ssh.TTY_OP_OSPEED: 38400, // output speed = 14.4kbaud
    }

session.RequestPty("xterm", 80, 40, modes); err != nil {
        return err
    }

stdin, _ = session.StdinPipe()

stdin.Write([]byte( <command> ))

Read:

var buf = make([]byte, 1024)
for {
    n, e := c.stdout.Read(buf)
    if e != nil {
        fmt.Println(e.Error())
        break
    }

    if n != 0 {
        fmt.Print(string(buf[:n]))
    }

    ...
}

EDIT: Problem is after displaying output, command still stay the same because i didn't write "\n" to the stdin.

For instance if i'll send "display bla ?" and i see this

<some_switch>display bla ?
bla
bla-bla
...
bla-bla-bla

<some_switch>display bla

And if i want to see something else i need erase "display bla". The question is HOW?

P.S. Sorry for my english.

CodePudding user response:

Non-printing ASCII symbols must be sending separately from the command. No need read stdout if there is no output.

//To write Ctrl-X
stdin.Write([]byte{0x18})

//Then send the command
stdin.Write([]byte(<command>))

//To write Backspace
stdin.Write([]byte{0x8})
  • Related