-
Notifications
You must be signed in to change notification settings - Fork 2
/
telnet.go
81 lines (66 loc) · 1.86 KB
/
telnet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Package telnet provides very simple interface for interacting with telnet devices from go routines.
package telnet
import (
"bufio"
"bytes"
"net"
"strings"
"time"
)
// Telnet presents struct with net.Conn interface for telnet protocol plus buffered reader and timeout setup
type Telnet struct {
conn net.Conn
reader *bufio.Reader
timeout time.Duration
}
// Dial constructs connection to a telnet device. Address string must be in format: "ip:port" (e.g. "127.0.0.1:23").
// Default timeout is set to 5 seconds.
func Dial(addr string) (t Telnet, err error) {
t.conn, err = net.Dial("tcp", addr)
if err == nil {
t.reader = bufio.NewReader(t.conn)
t.timeout = time.Second * 5 // default
}
return
}
// DialTimeout acts like Dial but takes a specific timeout (in nanoseconds).
func DialTimeout(addr string, timeout time.Duration) (t Telnet, err error) {
t.conn, err = net.DialTimeout("tcp", addr, timeout)
if err == nil {
t.reader = bufio.NewReader(t.conn)
t.timeout = timeout
}
return
}
// Read reads all data into string from telnet device until it meets the expected or stops on timeout.
func (t Telnet) Read(expect string) (str string, err error) {
var buf bytes.Buffer
t.conn.SetReadDeadline(time.Now().Add(t.timeout))
for {
b, e := t.reader.ReadByte()
if e != nil {
err = e
break
}
if b == 255 {
t.reader.Discard(2)
} else {
buf.WriteByte(b)
}
if strings.Contains(buf.String(), expect) {
str = buf.String()
break
}
}
return
}
// Write writes string (command or data) to telnet device. Do not forget add LF to end of string!
func (t Telnet) Write(s string) (i int, err error) {
t.conn.SetWriteDeadline(time.Now().Add(t.timeout))
i, err = t.conn.Write([]byte(s))
return
}
// SetTimeout changes default or start timeout for all interactions
func (t Telnet) SetTimeout(timeout time.Duration) {
t.timeout = timeout
}