You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // vi:ts=4:sts=4:sw=4:noet:tw=72
  2. //
  3. // logforward
  4. //
  5. // Copyright (c) 2018 Andreas Neue <an@dnix.de>
  6. package main
  7. import (
  8. "bufio"
  9. "bytes"
  10. "compress/gzip"
  11. "flag"
  12. "fmt"
  13. "os"
  14. "time"
  15. goscp "github.com/bramvdbogaerde/go-scp"
  16. "github.com/bramvdbogaerde/go-scp/auth"
  17. "golang.org/x/crypto/ssh"
  18. )
  19. var (
  20. bufferLimit = flag.Int("b", 1024*1024*1024, "Buffer size limit")
  21. scpUser = flag.String("u", "", "User")
  22. scpHost = flag.String("h", "localhost:22", "Host:Port")
  23. scpKey = flag.String("k", "", "Key")
  24. filePrefix = flag.String("p", "log-", "Filename prefix")
  25. )
  26. func init() {
  27. flag.Parse()
  28. }
  29. func main() {
  30. log := ""
  31. reader := bufio.NewReader(os.Stdin)
  32. for {
  33. time.Sleep(1 * time.Microsecond)
  34. line, err := reader.ReadString('\n')
  35. if err != nil {
  36. fmt.Printf("%s\n", err.Error())
  37. l := []byte(log)
  38. gzipAndSend(l)
  39. break
  40. } else {
  41. log += line
  42. fmt.Printf("%d\r", len(log))
  43. if len(log) >= *bufferLimit {
  44. l := []byte(log)
  45. go gzipAndSend(l)
  46. log = ""
  47. }
  48. }
  49. }
  50. }
  51. func gzipAndSend(l []byte) {
  52. var b bytes.Buffer
  53. fmt.Printf("\nSending buffer ...\n")
  54. w := gzip.NewWriter(&b)
  55. w.Write(l)
  56. w.Close()
  57. r := bufio.NewReader(&b)
  58. clientConfig, _ := auth.PrivateKey(*scpUser, *scpKey, ssh.InsecureIgnoreHostKey())
  59. client := goscp.NewClient(*scpHost, &clientConfig)
  60. err := client.Connect()
  61. if err != nil {
  62. fmt.Printf(err.Error() + "\n")
  63. return
  64. }
  65. defer client.Close()
  66. t := time.Now()
  67. date := t.Format("20060102150405")
  68. client.CopyFile(r, *filePrefix+date+".gz", "0644")
  69. fmt.Printf("Buffer sent\n")
  70. }