一、简介
本项目主要实现的功能是远程访问主机FTP目录中文件,并移动文件。使用第三方库
"github.com/gogf/gf"
"gopkg.in/dutchcoders/goftp.v1"
goftp 在使用中访问文件目录会返回Data connection already open; Transfer starting,需要修改目录中ftp.go,将下面代码注释
if !strings.HasPrefix(line, StatusFileOK) { // Really list is not working here err = errors.New(line) return }
二、使用
1. 连接
func Connect(user, password, address string) (*goftp.FTP, error) {
var err error
var ftp *goftp.FTP
// For debug messages: goftp.ConnectDbg("ftp.server.com:21")
if ftp, err = goftp.Connect(address); err != nil {
glog.Error(err)
return ftp, err
}
glog.Info("Successfully connected !!")
// Username / password authentication
if err = ftp.Login(user, password); err != nil {
glog.Error(err)
return ftp, err
}
return ftp, err
}
2. 访问目录
func main() {
ftpRun()
select {}
}
func ftpRun() {
go func() {
for{
ftp,err:=ftpm.Connect("user","123456","127.0.0.1:16088")
if err!=nil{
time.Sleep(5*time.Second)
continue
}else{
if err := ftp.Cwd("/"); err != nil {
glog.Error(err)
continue
}else{
for{
if files, err := ftp.List(""); err != nil {
glog.Error(err)
break
}else{
ftpFiles(files)
time.Sleep(10*time.Second)
continue
}
}
}
}
}
}()
}
func ftpFiles(files []string) {
array := garray.NewArray()
for _, v := range files {
v = gstr.Replace(v, "\r\n", "")
t := gstr.Split(v, " ")
dleip := ""
var new []string
for _, s := range t {
if s == "\u003cDIR\u003e" {
s = "DIR"
}
if s != dleip {
new = append(new, s)
}
}
if len(new) > 0 {
array.Append(new)
}
}
glog.Info(array.Slice())
}
3.移动文件到指定目录
资料来源:http://www.nsftools.com/TIPS/RawFTP.htm
RNFR
Syntax: RNFR from-filename
Used when renaming a file. Use this command to specify the file to be renamed; follow it with an RNTO command to specify the new name for the file.
RNTO
Syntax: RNTO to-filename
Used when renaming a file. After sending an RNFR command to specify the file to rename, send this command to specify the new name for the file.
实现:
因为goftp没有实现移动文件的接口,并且发送指令的send也没有开放,修改下ftp.go文件,增加个接口
func (ftp *FTP) Send(expects string, command string,path string) error {
if _, err := ftp.cmd(expects,command,path); err != nil {
return err
}else{
return nil
}
}
实现文件移动指令
func Move(ftp *goftp.FTP,pathname string,toPathname string) {
if err := ftp.Send("350","RNFR %s",pathname); err != nil {
glog.Error(err)
}else{
if err := ftp.Send("250","RNTO %s",toPathname); err != nil {
glog.Error(err)
}
}
}
/***
调用
Move(ftp,"/1/tmp/11.txt","/1/22.txt")
***/