Golang 监听 FTP 下载文件


import (
 "github.com/magiconair/properties"
 "github.com/CrowdSurge/banner"
 ftp "github.com/jlaffaye/ftp"
 "fmt"
 "time"
 "math/rand"
 "io/ioutil"
 "log"
 "os"
 "strconv"
 "path/filepath"
)

var syncInteval int64

var checkRemoteDir string

var remoteFtpAddress string

var remoteFtpUserName string

var remoteFtpUserPass string

var remoteFtpFolder string

const (
 LACK_PROPERTIES_CFG = "缺少配置参数,请检查 config.properties 文件"
 REMOTE_FTP_CANT_CONN = "无法连接远程 FTP 服务器"
 ACCOUNT_OR_PASSWORD_ERROR = "FTP 账户或密码错误"
 CANT_FOUND_DIRECTORY = "找不到 FTP 目录"
 REMOVE_FILE_ERROR = "无法删除文件,请检查权限"
 FTP_UPLOAD_ERROR = "上传失败, 请检查远程 FTP 服务"

)

func showBannner()  {
 b := [6] string {"test", "who am i", "great programming", "not bug!", "not smoking!"}

 banner.Print(b[RandRangInt64(0,int64(len(b)))])

}

func RandRangInt64(min, max int64) int64 {
 rand.Seed(time.Now().UnixNano())
 return min + rand.Int63n(max-min)
}

func main() {
 showBannner()
 time.Sleep(time.Second * 1)

 p := properties.MustLoadFile("config.properties", properties.UTF8)

 syncInteval = p.GetInt64("syncInteval",5)

 checkRemoteDir = p.GetString("checkRemoteDir","")

 remoteFtpAddress = p.GetString("remoteFtpAddress","")

 remoteFtpUserName = p.GetString("remoteFtpUserName","anonymous")

 remoteFtpUserPass = p.GetString("remoteFtpUserPass","")

 remoteFtpFolder = p.GetString("remoteFtpFolder","/")

 if(checkRemoteDir == "" || remoteFtpAddress == "") {
  log.Fatal(LACK_PROPERTIES_CFG)
  os.Exit(-1)
 }

 for {
  files, err := ioutil.ReadDir(checkRemoteDir)
  if err != nil {
   log.Fatal(err)
  }

  //检测并上传文件
  for _, f := range files {

   if(!f.IsDir()) {
    fmt.Println("found: " + f.Name() + " createTime: " + f.ModTime().Format("2006-01-02 15:04:05") +  " size: " + strconv.FormatInt(f.Size(),10))

    ftp, err := ftp.Connect(remoteFtpAddress)
    checkError(err, REMOTE_FTP_CANT_CONN)

    err = ftp.Login(remoteFtpUserName, remoteFtpUserPass)
    checkError(err, ACCOUNT_OR_PASSWORD_ERROR)

    err = ftp.ChangeDir(remoteFtpFolder)
    checkError(err, CANT_FOUND_DIRECTORY)

    checkRemoteFile := filepath.Join(checkRemoteDir, "/" + f.Name())

    //上传文件
    file, err := os.Open(checkRemoteFile)
    checkError(err, FTP_UPLOAD_ERROR)


    err = ftp.Stor(filepath.Join(f.Name()), file)
    checkError(err, FTP_UPLOAD_ERROR)

    ftp.Logout()
    ftp.Quit()

    file.Close()

    removeFileErr := os.Remove(checkRemoteFile);
    checkError(removeFileErr, REMOVE_FILE_ERROR);

    fmt.Println("Deleted File: " + checkRemoteFile)
   }
  }

  //休眠
  var t = time.Duration(syncInteval)
  time.Sleep(time.Second * t)
 }
}

func checkError(e error, msg string) {
 if e != nil {
  log.Fatal(e)
  log.Fatal(msg)
  fmt.Printf("%s", e)

  os.Exit(-1)
 }
}


评论