I am using an SSH session to control certain prompts on a remote machine. I have a working connection, and the code I have correctly responds to two prompts (the correct prompts are identical, and require the same response), but fails to respond to the next two. The second two prompts I believe are getting the same response as the first two, but in one case it does not show me what is being sent. The following code shows the relevant structs and creation of relevant pipes and variables. Some data was changed for obvious reasons.
type Connection struct {
*ssh.Client
password string
}
Creating the connection and the input/output pipe required by the code:
session, err := conn.NewSession()
in, err := session.StdinPipe()
if err != nil {
log.Fatal(err)
}
out, err := session.StdoutPipe()
if err != nil {
log.Fatal(err)
}
And finally the anonymous go function doing the reading of bytes from the output stream of the data. The fetching of bytes works correctly (I have that verified by the printf in there)
go func(in io.WriteCloser, out io.Reader, output *[]byte) {
var (
line string
r = bufio.NewReader(out)
)
for {
b, err := r.ReadByte()
if err != nil {
break
}
/*
Hand our output string the byte, perhaps I can just append a new string after each line completes to save time?
*/
*output = append(*output, b)
/*
If we reach a new line character then we clear the line to make way for the next
I'm printing it for debugging purposes and so you can see the output of all the commands run :)
*/
if b == byte('
') {
line += string(b)
fmt.Println(line)
line = ""
continue
}
/*
Here we check each line to see whats going on inside it
I think the problem right now has to do with not being able to clear the 'in' WriteCloser
*/
line += string(b)
if strings.HasSuffix(line, "Please input next ip for route:") {
_, err = in.Write([]byte("127.0.0.1
"))
if err != nil {
break
}
} else if strings.HasPrefix(line, "Password:") {
_, err = in.Write([]byte("secretpass
"))
if err != nil {
break
}
}
}
}(in, out, &output)
Now the first two prompts reached by this client are Password:
which gets the correct input of secretpass
. The next two require different strings. I think the problem has to do with the original secretpass
being kept in the WriteCloser
. I am rather new to go so I don't know if there is a way for me to clear the underlying buffer found in WriteCloser
or if I'm kinda SOL on that one and I need to find another way around this.
So the specific question is:
How do I clear the buffer found in a
WriteCloser
so that when I give it new input it wont be reading the old input for the first prompt?
And a bonus question:
Is there a way to read the current state of the
Write Closer
to see what I have written to it or is it an input only thing?