带交互的telnet小工具,golang版

前端之家收集整理的这篇文章主要介绍了带交互的telnet小工具,golang版前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. package netTools //main //
  2.  
  3. import (
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10.  
  11. func smain() {
  12. lis,err := net.Listen("tcp",":1789")
  13. if err != nil {
  14. fmt.Println(err)
  15. }
  16. defer lis.Close()
  17. for {
  18. con,_ := lis.Accept()
  19. go handler(con)
  20. }
  21. }
  22.  
  23. func handler(con net.Conn) {
  24. defer con.Close()
  25. buf := make([]byte,20)
  26. n,_ := con.Read(buf)
  27. fmt.Println(string(buf[:n]))
  28. con.Write(buf)
  29. con.Write(buf)
  30. }
  31.  
  32. //func main() {
  33. // buf,err := Telnet([]string{"w_Hello World","r_50","r_30"},"127.0.0.1:1789",20)
  34. // fmt.Println(err)
  35. // fmt.Println(string(buf))
  36. //}
  37.  
  38. func PortIsOpen(ip string,timeout int) bool {
  39. con,err := net.DialTimeout("tcp",ip,time.Duration(timeout))
  40. if err != nil {
  41. return false
  42. }
  43. con.Close()
  44. return true
  45. }
  46.  
  47. func Telnet(action []string,ip string,timeout int) (buf []byte,err error) {
  48. con,time.Duration(timeout)*time.Second)
  49. if err != nil {
  50. return
  51. }
  52. defer con.Close()
  53. con.SetReadDeadline(time.Now().Add(time.Second * 5))
  54. for _,v := range action {
  55. l := strings.SplitN(v,"_",2)
  56. if len(l) < 2 {
  57. return
  58. }
  59. switch l[0] {
  60. case "r":
  61. var n int
  62. n,err = strconv.Atoi(l[1])
  63. if err != nil {
  64. return
  65. }
  66. p := make([]byte,n)
  67. n,err = con.Read(p)
  68. if err != nil {
  69. return
  70. }
  71. buf = append(buf,p[:n]...)
  72. fmt.Println(buf)
  73. case "w":
  74. _,err = con.Write([]byte(l[1]))
  75. }
  76. }
  77. return
  78. }

猜你在找的Go相关文章