ftp4go

package module
v0.0.0-...-bc329bf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2019 License: Apache-2.0 Imports: 16 Imported by: 0

README

This is an FTP client started as a port of the standard Python FTP client library
Forked form code.google.com/p/ftp4go and change some dependenes of the package

Installation

go get github.com/shenshouer/ftp4go

How to use it

Import the library in your code and call the methods exposed by the FTP structure, for instance:

package main  
import (
  "fmt"
  "os"
  ftp4go "github.com/shenshouer/ftp4go"
)  
func main() {
  ftpClient := ftp4go.NewFTP(0) // 1 for debugging
  //connect
  _, err := ftpClient.Connect("myFtpAddress", ftp4go.DefaultFtpPort)
  if err != nil {
    fmt.Println("The connection failed")
    os.Exit(1)
  }   
  defer ftpClient.Quit()
  _, err = ftpClient.Login("myUsername", "myPassword", "")
  if err != nil {
    fmt.Println("The login failed")
    os.Exit(1)
  }      
  //Print the current working directory
  var cwd string
  cwd, err = ftpClient.Pwd()
  if err != nil {
    fmt.Println("The Pwd command failed")
    os.Exit(1)
  }
  fmt.Println("The current folder is", cwd)
}

断点续传示例

package main

import (
	ftp4go "github.com/shenshouer/ftp4go"
	"fmt"
	"os"
)

var(
	downloadFileName 	= "DockerToolbox-1.8.2a.pkg"
	BASE_FTP_PATH 		= "/home/bob/"					// base data path in ftp server
)

func main() {
	ftpClient := ftp4go.NewFTP(0) // 1 for debugging

	//connect
	_, err := ftpClient.Connect("172.8.4.101", ftp4go.DefaultFtpPort, "")
	if err != nil {
		fmt.Println("The connection failed")
		os.Exit(1)
	}
	defer ftpClient.Quit()

	_, err = ftpClient.Login("bob", "p@ssw0rd", "")
	if err != nil {
		fmt.Println("The login failed")
		os.Exit(1)
	}

	//Print the current working directory
	var cwd string
	cwd, err = ftpClient.Pwd()
	if err != nil {
		fmt.Println("The Pwd command failed")
		os.Exit(1)
	}
	fmt.Println("The current folder is", cwd)


	// get the remote file size
	size, err := ftpClient.Size("/home/bob/"+downloadFileName)
	if err != nil {
		fmt.Println("The Pwd command failed")
		os.Exit(1)
	}
	fmt.Println("size ", size)

	// start resume file download
	if err = ftpClient.DownloadResumeFile("/home/bob/"+downloadFileName, "/Users/goyoo/ftptest/"+downloadFileName, false); err != nil{
		panic(err)
	}

}

More on the code

Being a port of a Python library, the original Python version is probably the best reference.
Python ftplib

Differences to the original version

Some new methods have been implemented to upload and download files, recursively in a folder as well.

TODOs and unsupported functionality

  • TLS is not supported yet
  • add multi goroutine for one download task support

Documentation

Overview

Package ftp implements an FTP client.

Package ftp implements an FTP client.

Index

Constants

View Source
const (
	DefaultFtpPort       = 21
	DefaultTimeoutInMsec = 1000
	CRLF                 = "\r\n"
	BLOCK_SIZE           = 8192
)

The default constants

View Source
const (
	StatusInitiating    = 100
	StatusRestartMarker = 110
	StatusReadyMinute   = 120
	StatusAlreadyOpen   = 125
	StatusAboutToSend   = 150

	StatusCommandOK             = 200
	StatusCommandNotImplemented = 202
	StatusSystem                = 211
	StatusDirectory             = 212
	StatusFile                  = 213
	StatusHelp                  = 214
	StatusName                  = 215
	StatusReady                 = 220
	StatusClosing               = 221
	StatusDataConnectionOpen    = 225
	StatusClosingDataConnection = 226
	StatusPassiveMode           = 227
	StatusLongPassiveMode       = 228
	StatusExtendedPassiveMode   = 229
	StatusLoggedIn              = 230
	StatusLoggedOut             = 231
	StatusLogoutAck             = 232
	StatusRequestedFileActionOK = 250
	StatusPathCreated           = 257

	StatusUserOK             = 331
	StatusLoginNeedAccount   = 332
	StatusRequestFilePending = 350

	StatusNotAvailable             = 421
	StatusCanNotOpenDataConnection = 425
	StatusTransfertAborted         = 426
	StatusInvalidCredentials       = 430
	StatusHostUnavailable          = 434
	StatusFileActionIgnored        = 450
	StatusActionAborted            = 451
	Status452                      = 452

	StatusBadCommand              = 500
	StatusBadArguments            = 501
	StatusNotImplemented          = 502
	StatusBadSequence             = 503
	StatusNotImplementedParameter = 504
	StatusNotLoggedIn             = 530
	StatusStorNeedAccount         = 532
	StatusFileUnavailable         = 550
	StatusPageTypeUnknown         = 551
	StatusExceededStorage         = 552
	StatusBadFileName             = 553
)

FTP status codes, defined in RFC 959

View Source
const (
	BYTE_BLK = 1024
)
View Source
const MSG_OOB = 0x1 //Process data out of band

Variables

View Source
var (
	NewErrReply = func(error error) error { return errors.New("Reply error: " + error.Error()) }
	NewErrTemp  = func(error error) error { return errors.New("Temporary error: " + error.Error()) }
	NewErrPerm  = func(error error) error { return errors.New("Permanent error: " + error.Error()) }
	NewErrProto = func(error error) error { return errors.New("Protocol error: " + error.Error()) }
	NewErrStop  = fmt.Errorf("Stop by human behavior: call FTP.Stop()")
)
View Source
var DIRECTORY_NON_EXISTENT = errors.New("The folder does not exist and can not be removed")

Functions

func Dial

func Dial(network, addr string) (net.Conn, error)

Dial connects to the given address on the given network using net.Dial and then returns a new Conn for the connection.

func TrimBytes

func TrimBytes(b []byte) []byte

TrimBytes returns b without leading and trailing ASCII space.

func TrimString

func TrimString(s string) string

TrimString returns s without leading and trailing ASCII space.

Types

type Callback

type Callback func(info *CallbackInfo)

type CallbackInfo

type CallbackInfo struct {
	Resourcename     string
	Filename         string
	BytesTransmitted int64
	Eof              bool
}

type Error

type Error struct {
	Code int
	Msg  string
}

An Error represents a numeric error response from a server.

func (*Error) Error

func (e *Error) Error() string

type FTP

type FTP struct {
	Host string
	Port int
	// contains filtered or unexported fields
}

The FTP client structure containing: - host, user, password, acct, timeout

func NewFTP

func NewFTP(debuglevel int) *FTP

NewFTP creates a new FTP client using a debug level, default is 0, which is disabled. The FTP server uses the passive tranfer mode by default.

Debuglevel:
	0 -> disabled
	1 -> information
	2 -> verbose

func (*FTP) Abort

func (ftp *FTP) Abort() (response *Response, err error)

Abort interrupts a file transfer, which uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that does not seem to work with all servers. Instead just send the ABOR command as OOB data.

func (*FTP) Acct

func (ftp *FTP) Acct() (response *Response, err error)

Acct sends an ACCT command.

func (*FTP) Connect

func (ftp *FTP) Connect(host string, port int, socks5ProxyUrl string) (resp *Response, err error)

Connect connects to the host by using the specified port or the default one if the value is <=0.

func (*FTP) Cwd

func (ftp *FTP) Cwd(dirname string) (response *Response, err error)

Cwd changes to current directory.

func (*FTP) Delete

func (ftp *FTP) Delete(filename string) (response *Response, err error)

Delete deletes a file.

func (*FTP) Dir

func (ftp *FTP) Dir(params ...string) (filelist []string, err error)

Dir returns a list of file in a directory in long form, by default the current.

func (*FTP) DownloadFile

func (ftp *FTP) DownloadFile(remotename string, localpath string, useLineMode bool) (err error)

DownloadFile downloads a file and stores it locally. There are two modes: - binary, useLineMode = false - line by line (text), useLineMode = true

func (*FTP) DownloadResumeFile

func (ftp *FTP) DownloadResumeFile(remotename string, localpath string, useLineMode bool) (err error)

func (*FTP) Feat

func (ftp *FTP) Feat(params ...string) (fts []string, err error)

Feat lists all new FTP features that the server supports beyond those described in RFC 959.

func (*FTP) GetBytes

func (ftp *FTP) GetBytes(cmd FtpCmd, writer io.Writer, blocksize int, params ...string) (err error)

GetBytes retrieves data in binary mode. Args:

cmd: A RETR command.
callback: A single parameter callable to be called on each
          block of data read.
blocksize: The maximum number of bytes to read from the
          socket at one time.  [default: 8192]

Returns:

The response code.

func (*FTP) GetLines

func (ftp *FTP) GetLines(cmd FtpCmd, writer io.Writer, params ...string) (err error)

GetLines retrieves data in line mode. Args:

cmd: A RETR, LIST, NLST, or MLSD command.
writer: of interface type io.Writer that is called for each line with the trailing CRLF stripped.

returns:

The response code.

func (*FTP) Login

func (ftp *FTP) Login(username, password string, acct string) (response *Response, err error)

Login logs on to the server.

func (*FTP) Mkd

func (ftp *FTP) Mkd(dirname string) (dname string, err error)

Mkd creates a directory and returns its full pathname.

func (*FTP) Mlsd

func (ftp *FTP) Mlsd(path string, facts []string) (ls []*NameFactsLine, err error)

Mlsd lists a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary including a variable number of "facts" depending on the server and whether "facts" argument has been provided.

func (*FTP) NewConn

func (ftp *FTP) NewConn(addr string) error

func (*FTP) Nlst

func (ftp *FTP) Nlst(params ...string) (filelist []string, err error)

Nlst returns a list of file in a directory, by default the current.

func (*FTP) Opts

func (ftp *FTP) Opts(params ...string) (response *Response, err error)

Opts returns a list of file in a directory in long form, by default the current.

func (*FTP) Pwd

func (ftp *FTP) Pwd() (dirname string, err error)

Pwd returns the current working directory.

func (*FTP) Quit

func (ftp *FTP) Quit() (response *Response, err error)

Quits sends a QUIT command and closes the connection.

func (*FTP) Read

func (ftp *FTP) Read(cmd FtpCmd) (resp *Response, err error)

Read reads the response along with the response code from the server

func (*FTP) RemoveRemoteDirTree

func (ftp *FTP) RemoveRemoteDirTree(remoteDir string) (err error)

RemoveRemoteDirTree removes a remote folder and all of its subfolders recursively. The current directory is then set to the orginal one before the operation or to the root of the deleted folder if it fails.

func (*FTP) Rename

func (ftp *FTP) Rename(fromname string, toname string) (response *Response, err error)

Rename renames a file.

func (*FTP) ResumeFile

func (ftp *FTP) ResumeFile(cmd FtpCmd, writer *os.File, offset int64, blocksize int, params ...string) (err error)

func (*FTP) Rmd

func (ftp *FTP) Rmd(dirname string) (response *Response, err error)

Rmd removes a directory.

func (*FTP) Send

func (ftp *FTP) Send(cmd FtpCmd, params ...string) (err error)

Send sends a command to the server.

func (*FTP) SendAndRead

func (ftp *FTP) SendAndRead(cmd FtpCmd, params ...string) (response *Response, err error)

SendAndRead sends a command to the server and reads the response.

func (*FTP) SendPort

func (ftp *FTP) SendPort(host string, port int) (response *Response, err error)

SendPort sends a PORT command with the current host and given port number

func (*FTP) SetPassive

func (ftp *FTP) SetPassive(ispassive bool)

SetPassive sets the mode to passive or active for data transfers. With a false statement use the normal PORT mode. With a true statement use the PASV command.

func (*FTP) Size

func (ftp *FTP) Size(filename string) (size int, err error)

Size retrieves the size of a file.

func (*FTP) Stop

func (ftp *FTP) Stop()

func (*FTP) StoreBytes

func (ftp *FTP) StoreBytes(cmd FtpCmd, reader io.Reader, blocksize int, remotename string, filename string, callback Callback) (err error)

StoreBytes uploads bytes in chunks defined by the blocksize parameter. It uses an io.Reader to read the input data.

func (*FTP) StoreLines

func (ftp *FTP) StoreLines(cmd FtpCmd, reader io.Reader, remotename string, filename string, callback Callback) (err error)

StoreLines stores a file in line mode.

Args:
  cmd: A STOR command.
  reader: A reader object with a ReadLine() method.
  callback: An optional single parameter callable that is called on
          on each line after it is sent.  [default: None]

Returns:
  The response code.

func (*FTP) UploadDirTree

func (ftp *FTP) UploadDirTree(localDir string, remoteRootDir string, maxSimultaneousConns int, excludedDirs []string, callback Callback) (n int, err error)

UploadDirTree uploads a local directory and all of its subfolders localDir -> path to the local folder to upload along with all of its subfolders. remoteRootDir -> the root folder on the FTP server where to store the localDir tree. excludedDirs -> a slice of folder names to exclude from the uploaded directory tree. callback -> a callback function, which is called synchronously. Do remember to collect data in a go routine for instance if you do not want the upload to block. Returns the number of files uploaded and an error if any.

The current workding directory is set back to the initial value at the end.

func (*FTP) UploadFile

func (ftp *FTP) UploadFile(remotename string, localpath string, useLineMode bool, callback Callback) (err error)

UploadFile uploads a file from a local path to the current folder (see Cwd too) on the FTP server. A remotename needs to be specified. There are two modes set via the useLineMode flag: - binary, useLineMode = false - line by line (text), useLineMode = true

type FtpCmd

type FtpCmd int

FTP command strings

const (
	NONE_FTP_CMD       FtpCmd = 0
	USER_FTP_CMD       FtpCmd = 1
	PASSWORD_FTP_CMD   FtpCmd = 2
	ACCT_FTP_CMD       FtpCmd = 3
	ABORT_FTP_CMD      FtpCmd = 4
	PORT_FTP_CMD       FtpCmd = 5
	PASV_FTP_CMD       FtpCmd = 6
	TYPE_A_FTP_CMD     FtpCmd = 7
	NLST_FTP_CMD       FtpCmd = 8
	LIST_FTP_CMD       FtpCmd = 9
	FEAT_FTP_CMD       FtpCmd = 10
	OPTS_FTP_CMD       FtpCmd = 11
	RETR_FTP_CMD       FtpCmd = 12
	TYPE_I_FTP_CMD     FtpCmd = 13
	STORE_FTP_CMD      FtpCmd = 14
	RENAMEFROM_FTP_CMD FtpCmd = 15
	RENAMETO_FTP_CMD   FtpCmd = 16
	DELETE_FTP_CMD     FtpCmd = 17
	CWD_FTP_CMD        FtpCmd = 18
	SIZE_FTP_CMD       FtpCmd = 19
	MKDIR_FTP_CMD      FtpCmd = 20
	RMDIR_FTP_CMD      FtpCmd = 21
	PWDIR_FTP_CMD      FtpCmd = 22
	CDUP_FTP_CMD       FtpCmd = 23
	QUIT_FTP_CMD       FtpCmd = 24
	MLSD_FTP_CMD       FtpCmd = 25
	REST_FTP_CMD       FtpCmd = 26
)

func (FtpCmd) AppendParameters

func (i FtpCmd) AppendParameters(pars ...string) string

func (FtpCmd) String

func (i FtpCmd) String() string

type NameFactsLine

type NameFactsLine struct {
	Name  string
	Facts map[string]string
}

type ProtocolError

type ProtocolError string

A ProtocolError describes a protocol violation such as an invalid response or a hung-up connection.

func (ProtocolError) Error

func (p ProtocolError) Error() string

type Response

type Response struct {
	Code    int
	Message string
	Stream  []byte
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL