telnet.go 1.9 KB

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