Ftp ruby

Ftp ruby DEFAULT

FTP Integration in Rails App

FTP stands for File transfer protocol. It is basically used to transfer files from the local computer to the client/remote server and manage client and server side data of the application. 

Ruby provides a library to implement FTP into your web application.

Experts at any Ruby on Rails development company need to understand how to integrate FTP in a rails application. Here you go.

In this article we will learn how to 

  • Integrate FTP in rails application.
  • Methods of FTP library and use of these methods.

First you need a library of FTP class.

Get Estimate for Ruby on Rails Application

There are some methods which will be useful to users.

  • ::open
  • getbinaryfilefile
  • gettextfile
  • putbinaryfile
  • puttextfile
  • chdir
  • rename
  • Delete
  • Login

1. ::open

This method is similar to FTP.new with mandatory host parameters.

Users have to provide the mandatory parameters as an argument in this method.

This method will pass to the FTP object and make a connection to the remote server and close it when the blocks finish or exception is raised.





2. Getbinaryfilefile(remote_file_path, local_file_path, blocksize = DEFAULT_BLOCKSIZE )

This method is used for retrieving files from the remote server in binary mode and storing the results in a specified  local file. If the local file is nil, it returns retrieved data.

DEFAULT_BLOCKSIZE value is by default 1024 bytes per block(Not Mandatory).





3. Gettextfile(remote_file_path, local_file_path)

This method retrieves files in ASCII(text) mode from the remote server and stores the results in a specified  local file. If the local file is nil, it returns retrieved data. 

If blocks supplied it is passed retrieved data one line at a time.





4. Putbinaryfile(local_file_path, remote_file_path)

Transfer local file to the remote server in binary mode at the specified file location given in the remotefile parameter and store the data into the remote file.





5. Puttextfile

Transfer local file to the remote server in ASCII(text) mode at the specified file location given in the remotefile parameter and store the data into the remote file.





6. Chdir

Changes the remote directory.

List method returns all the files of the current remote directory.





7. Rename

Used for renaming a file.





8. Delete

Used to delete files from the remote server.




So, using the above method and the use of getbinaryfile and putbinaryfile, we can download files from the FTP server and send the file to the FTP server.

Sours: https://www.botreetechnologies.com/blog/ftp-integration-in-rails-app/

Net::FTP

abort()click to toggle source

Aborts the previous command (ABOR command).

defabortline = "ABOR"+CRLFprint"put: ABOR\n"[email protected][email protected](line, Socket::MSG_OOB) resp = getmultilineunless ["426", "226", "225"].include?(resp[0, 3]) raiseFTPProtoError, respendreturnrespend

acct(account)click to toggle source

Sends the ACCT command.

This is a less common FTP command, to send account information if the destination host requires it.

defacct(account) cmd = "ACCT "+accountvoidcmd(cmd) end

binary=(newmode)click to toggle source

A setter to toggle transfers in binary mode. is either or

defbinary=(newmode) [email protected]@binary = [email protected]_inendend

chdir(dirname)click to toggle source

Changes the (remote) directory.

defchdir(dirname) ifdirname==".."beginvoidcmd("CDUP") returnrescueFTPPermError =>eife.message[0, 3] !="500"raiseeendendendcmd = "CWD #{dirname}"voidcmd(cmd) end

close()click to toggle source

Closes the connection. Further operations are impossible until you open a new connection with connect.

[email protected]@[email protected](Socket::SHUT_WR) rescuenilorig, self.read_timeout = self.read_timeout, [email protected]@sock.closeself.read_timeout = origendendend

closed?()click to toggle source

Returns iff the connection is closed.

connect(host, port = FTP_PORT)click to toggle source

Establishes an FTP connection to host, optionally overriding the default port. If the environment variable is set, sets up the connection through a SOCKS proxy. Raises an exception (typically ) if the connection cannot be established.

defconnect(host, port = FTP_PORT) [email protected]_modeprint"connect: ", host, ", ", port, "\n"[email protected] = [email protected]_sock = open_socket(host, port) @sock = BufferedSocket.new(@bare_sock, read_timeout:@read_timeout) [email protected]_contextbeginvoidcmd("AUTH TLS") ssl_sock = start_tls_session(@bare_sock) @sock = BufferedSSLSocket.new(ssl_sock, read_timeout:@read_timeout) [email protected]_data_connectionvoidcmd("PBSZ 0") voidcmd("PROT P") endrescueOpenSSL::SSL::SSLError, [email protected]

delete(filename)click to toggle source

Deletes a file on the server.

defdelete(filename) resp = sendcmd("DELE #{filename}") ifresp.start_with?("250") returnelsifresp.start_with?("5") raiseFTPPermError, respelseraiseFTPReplyError, respendend

dir(*args)click to toggle source

Alias for: list

features()click to toggle source

Issues a FEAT command

Returns an array of supported optional features

deffeaturesresp = sendcmd("FEAT") if!resp.start_with?("211") raiseFTPReplyError, respendfeats = [] resp.split("\n").eachdo|line|nextif!line.start_with?(' ') feats<<line.stripendreturnfeatsend

get(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE)click to toggle source

Retrieves in whatever mode the session is set (text or binary). See gettextfile and getbinaryfile.

defget(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected](remotefile, localfile, blocksize, &block) elsegettextfile(remotefile, localfile, &block) endend

getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE)click to toggle source

Retrieves in binary mode, storing the result in . If is nil, returns retrieved data. If a block is supplied, it is passed the retrieved data in chunks.

defgetbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE, &block) f = nilresult = [email protected]_offset = File.size?(localfile) f = File.open(localfile, "a") elserest_offset = nilf = File.open(localfile, "w") endelsif!block_given?result = String.newendbeginf&.binmoderetrbinary("RETR #{remotefile}", blocksize, rest_offset) do|data|f&.write(data) block&.(data) result&.concat(data) endreturnresultensuref&.closeendend

getdir()click to toggle source

Alias for: pwd

gettextfile(remotefile, localfile = File.basename(remotefile))click to toggle source

Retrieves in ASCII (text) mode, storing the result in . If is nil, returns retrieved data. If a block is supplied, it is passed the retrieved data one line at a time.

defgettextfile(remotefile, localfile = File.basename(remotefile), &block) f = nilresult = niliflocalfilef = File.open(localfile, "w") elsif!block_given?result = String.newendbeginretrlines("RETR #{remotefile}") do|line, newline|l = newline?line+"\n":linef&.print(l) block&.(line, newline) result&.concat(l) endreturnresultensuref&.closeendend

help(arg = nil)click to toggle source

Issues the HELP command.

defhelp(arg = nil) cmd = "HELP"ifargcmd = cmd+" "+argendsendcmd(cmd) end

list(*args)click to toggle source

Returns an array of file information in the directory (the output is like `ls -l`). If a block is given, it iterates through the listing.

deflist(*args, &block) cmd = "LIST"args.eachdo|arg|cmd = "#{cmd} #{arg}"endlines = [] retrlines(cmd) do|line|lines<<lineendifblocklines.each(&block) endreturnlinesend

Also aliased as: ls, dir

login(user = "anonymous", passwd = nil, acct = nil)click to toggle source

Logs in to the remote host. The session must have been previously connected. If is the string “anonymous” and the is , “[email protected]” is used as a password. If the parameter is not , an FTP ACCT command is sent following the successful login. Raises an exception on error (typically ).

deflogin(user = "anonymous", passwd = nil, acct = nil) ifuser=="anonymous"andpasswd==nilpasswd = "[email protected]"endresp = ""synchronizedoresp = sendcmd('USER '+user) ifresp.start_with?("3") raiseFTPReplyError, respifpasswd.nil?resp = sendcmd('PASS '+passwd) endifresp.start_with?("3") raiseFTPReplyError, respifacct.nil?resp = sendcmd('ACCT '+acct) endendif!resp.start_with?("2") raiseFTPReplyError, [email protected] = [email protected]_in = trueend

ls(*args)click to toggle source

Alias for: list

mdtm(filename)click to toggle source

Returns the raw last modification time of the (remote) file in the format “YYYYMMDDhhmmss” (MDTM command).

Use if you want a parsed Time instance.

defmdtm(filename) resp = sendcmd("MDTM #{filename}") ifresp.start_with?("213") returnget_body(resp) endend

mkdir(dirname)click to toggle source

Creates a remote directory.

defmkdir(dirname) resp = sendcmd("MKD #{dirname}") returnparse257(resp) end

mlsd(pathname = nil)click to toggle source

Returns an array of the entries of the directory specified by . Each entry has the facts (e.g., size, last modification time, etc.) and the pathname. If a block is given, it iterates through the listing. If is omitted, the current directory is assumed.

defmlsd(pathname = nil, &block) cmd = pathname?"MLSD #{pathname}":"MLSD"entries = [] retrlines(cmd) do|line|entries<<parse_mlsx_entry(line) endifblockentries.each(&block) endreturnentriesend

mlst(pathname = nil)click to toggle source

Returns data (e.g., size, last modification time, entry type, etc.) about the file or directory specified by . If is omitted, the current directory is assumed.

defmlst(pathname = nil) cmd = pathname?"MLST #{pathname}":"MLST"resp = sendcmd(cmd) if!resp.start_with?("250") raiseFTPReplyError, respendline = resp.lines[1] unlesslineraiseFTPProtoError, respendentry = line.sub(/\A(250-| *)/, "") returnparse_mlsx_entry(entry) end

mtime(filename, local = false)click to toggle source

Returns the last modification time of the (remote) file. If is , it is returned as a local time, otherwise it’s a UTC time.

defmtime(filename, local = false) returnTIME_PARSER.(mdtm(filename), local) end

nlst(dir = nil)click to toggle source

Returns an array of filenames in the remote directory.

defnlst(dir = nil) cmd = "NLST"ifdircmd = "#{cmd} #{dir}"endfiles = [] retrlines(cmd) do|line|files.push(line) endreturnfilesend

noop()click to toggle source

Issues a NOOP command.

Does nothing except return a response.

defnoopvoidcmd("NOOP") end

option(name, params = nil)click to toggle source

Issues an OPTS command

  • name Should be the name of the option to set

  • params is any optional parameters to supply with the option

example: option(‘UTF8’, ‘ON’) => ‘OPTS UTF8 ON’

defoption(name, params = nil) cmd = "OPTS #{name}"cmd+=" #{params}"ifparamsvoidcmd(cmd) end

put(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block)click to toggle source

Transfers to the server in whatever mode the session is set (text or binary). See puttextfile and putbinaryfile.

defput(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected](localfile, remotefile, blocksize, &block) elseputtextfile(localfile, remotefile, &block) endend

putbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE)click to toggle source

Transfers to the server in binary mode, storing the result in . If a block is supplied, calls it, passing in the transmitted data in chunks.

defputbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected]_offset = size(remotefile) rescueNet::FTPPermErrorrest_offset = nilendelserest_offset = nilendf = File.open(localfile) beginf.binmodeifrest_offsetstorbinary("APPE #{remotefile}", f, blocksize, rest_offset, &block) elsestorbinary("STOR #{remotefile}", f, blocksize, rest_offset, &block) endensuref.closeendend

puttextfile(localfile, remotefile = File.basename(localfile))click to toggle source

Transfers to the server in ASCII (text) mode, storing the result in . If callback or an associated block is supplied, calls it, passing in the transmitted data one line at a time.

defputtextfile(localfile, remotefile = File.basename(localfile), &block) f = File.open(localfile) beginstorlines("STOR #{remotefile}", f, &block) ensuref.closeendend

pwd()click to toggle source

Returns the current remote directory.

defpwdresp = sendcmd("PWD") returnparse257(resp) end

Also aliased as: getdir

quit()click to toggle source

Exits the FTP session.

defquitvoidcmd("QUIT") end

read_timeout=(sec)click to toggle source

Setter for the #read_timeout attribute.

defread_timeout=(sec) @sock.read_timeout = [email protected]_timeout = secend

rename(fromname, toname)click to toggle source

Renames a file on the server.

defrename(fromname, toname) resp = sendcmd("RNFR #{fromname}") if!resp.start_with?("3") raiseFTPReplyError, respendvoidcmd("RNTO #{toname}") end

retrbinary(cmd, blocksize, rest_offset = nil)click to toggle source

Puts the connection into binary (image) mode, issues the given command, and fetches the data returned, passing it to the associated block in chunks of characters. Note that is a server command (such as “RETR myfile”).

defretrbinary(cmd, blocksize, rest_offset = nil) synchronizedowith_binary(true) dobeginconn = transfercmd(cmd, rest_offset) whiledata = conn.read(blocksize) yield(data) endconn.shutdown(Socket::SHUT_WR) conn.read_timeout = 1conn.readensureconn.closeifconnendvoidrespendendend

retrlines(cmd)click to toggle source

Puts the connection into ASCII (text) mode, issues the given command, and passes the resulting data, one line at a time, to the associated block. If no block is given, prints the lines. Note that is a server command (such as “RETR myfile”).

defretrlines(cmd) synchronizedowith_binary(false) dobeginconn = transfercmd(cmd) whileline = conn.getsyield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?) endconn.shutdown(Socket::SHUT_WR) conn.read_timeout = 1conn.readensureconn.closeifconnendvoidrespendendend

rmdir(dirname)click to toggle source

Removes a remote directory.

defrmdir(dirname) voidcmd("RMD #{dirname}") end

sendcmd(cmd)click to toggle source

Sends a command and returns the response.

defsendcmd(cmd) synchronizedoputline(cmd) returngetrespendend

set_socket(sock, get_greeting = true)click to toggle source

Set the socket used to connect to the FTP server.

May raise FTPReplyError if is false.

defset_socket(sock, get_greeting = true) [email protected] = sockifget_greetingvoidrespendendend

site(arg)click to toggle source

Issues a SITE command.

defsite(arg) cmd = "SITE "+argvoidcmd(cmd) end

size(filename)click to toggle source

Returns the size of the given (remote) filename.

defsize(filename) with_binary(true) doresp = sendcmd("SIZE #{filename}") if!resp.start_with?("213") raiseFTPReplyError, respendreturnget_body(resp).to_iendend

status(pathname = nil)click to toggle source

Returns the status (STAT command).

pathname

when stat is invoked with pathname as a parameter it acts like list but a lot faster and over the same tcp session.

defstatus(pathname = nil) line = pathname?"STAT #{pathname}":"STAT"if/[\r\n]/=~lineraiseArgumentError, "A line must not contain CR or LF"endprint"put: #{line}\n"[email protected][email protected](line+CRLF, Socket::MSG_OOB) returngetrespend

storbinary(cmd, file, blocksize, rest_offset = nil)click to toggle source

Puts the connection into binary (image) mode, issues the given server-side command (such as “STOR myfile”), and sends the contents of the file named to the server. If the optional block is given, it also passes it the data, in chunks of characters.

defstorbinary(cmd, file, blocksize, rest_offset = nil) ifrest_offsetfile.seek(rest_offset, IO::SEEK_SET) endsynchronizedowith_binary(true) dobeginconn = transfercmd(cmd) whilebuf = file.read(blocksize) conn.write(buf) yield(buf) ifblock_given?endconn.shutdown(Socket::SHUT_WR) conn.read_timeout = 1conn.readensureconn.closeifconnendvoidrespendendrescueErrno::EPIPEgetrespraiseend

storlines(cmd, file)click to toggle source

Puts the connection into ASCII (text) mode, issues the given server-side command (such as “STOR myfile”), and sends the contents of the file named to the server, one line at a time. If the optional block is given, it also passes it the lines.

defstorlines(cmd, file) synchronizedowith_binary(false) dobeginconn = transfercmd(cmd) whilebuf = file.getsifbuf[-2, 2] !=CRLFbuf = buf.chomp+CRLFendconn.write(buf) yield(buf) ifblock_given?endconn.shutdown(Socket::SHUT_WR) conn.read_timeout = 1conn.readensureconn.closeifconnendvoidrespendendrescueErrno::EPIPEgetrespraiseend

system()click to toggle source

Returns system information.

defsystemresp = sendcmd("SYST") if!resp.start_with?("215") raiseFTPReplyError, respendreturnget_body(resp) end

voidcmd(cmd)click to toggle source

Sends a command and expect a response beginning with ‘2’.

defvoidcmd(cmd) synchronizedoputline(cmd) voidrespendend
Sours: https://ruby-doc.org/stdlib-2.4.0/libdoc/net/ftp/rdoc/Net/FTP.html
  1. Pellet pistol
  2. Javax persistence query
  3. Beeman air rifles
  4. Lolis tacos

Public Class methods

new(host = nil, user = nil, passwd = nil, acct = nil)

Creates and returns a new object. If a is given, a connection is made. Additionally, if the is given, the given user name, password, and (optionally) account are used to log in. See login.

[Source]

definitialize(host = nil, user = nil, passwd = nil, acct = nil) super() @binary = [email protected] = [email protected]_mode = [email protected] = falseifhostconnect(host) ifuserlogin(user, passwd, acct) endendend

open(host, user = nil, passwd = nil, acct = nil) {|ftp| ...}

A synonym for , but with a mandatory host parameter.

If a block is given, it is passed the object, which will be closed when the block finishes, or when an exception is raised.

[Source]

defFTP.open(host, user = nil, passwd = nil, acct = nil) ifblock_given?ftp = new(host, user, passwd, acct) beginyieldftpensureftp.closeendelsenew(host, user, passwd, acct) endend

Public Instance methods

abort()

Aborts the previous command (ABOR command).

[Source]

defabortline = "ABOR"+CRLFprint"put: ABOR\n"[email protected][email protected](line, Socket::MSG_OOB) resp = getmultilineunless ["426", "226", "225"].include?(resp[0, 3]) raiseFTPProtoError, respendreturnrespend

acct(account)

Sends the ACCT command. TODO: more info.

[Source]

defacct(account) cmd = "ACCT "+accountvoidcmd(cmd) end

chdir(dirname)

Changes the (remote) directory.

[Source]

defchdir(dirname) ifdirname==".."beginvoidcmd("CDUP") returnrescueFTPPermErrorif$![0, 3] !="500"raiseFTPPermError, $!endendendcmd = "CWD "+dirnamevoidcmd(cmd) end

close()

Closes the connection. Further operations are impossible until you open a new connection with connect.

[Source]

closed?()

Returns iff the connection is closed.

[Source]

connect(host, port = FTP_PORT)

Establishes an FTP connection to host, optionally overriding the default port. If the environment variable is set, sets up the connection through a SOCKS proxy. Raises an exception (typically ) if the connection cannot be established.

[Source]

defconnect(host, port = FTP_PORT) [email protected]_modeprint"connect: ", host, ", ", port, "\n"[email protected] = open_socket(host, port) voidrespendend

delete(filename)

Deletes a file on the server.

[Source]

defdelete(filename) resp = sendcmd("DELE "+filename) ifresp[0, 3] =="250"returnelsifresp[0] ==?5raiseFTPPermError, respelseraiseFTPReplyError, respendend

dir(*args)

get(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Retrieves in whatever mode the session is set (text or binary). See gettextfile and getbinaryfile.

[Source]

defget(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected](remotefile, localfile, &block) elsegetbinaryfile(remotefile, localfile, blocksize, &block) endend

getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Retrieves in binary mode, storing the result in . If a block is supplied, it is passed the retrieved data in chunks.

[Source]

defgetbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected]_offset = File.size?(localfile) f = open(localfile, "a") elserest_offset = nilf = open(localfile, "w") endbeginf.binmoderetrbinary("RETR "+remotefile, blocksize, rest_offset) do|data|f.write(data) yield(data) ifblockendensuref.closeendend

gettextfile(remotefile, localfile = File.basename(remotefile)) {|line| ...}

Retrieves in ASCII (text) mode, storing the result in . If a block is supplied, it is passed the retrieved data one line at a time.

[Source]

defgettextfile(remotefile, localfile = File.basename(remotefile), &block) f = open(localfile, "w") beginretrlines("RETR "+remotefile) do|line|f.puts(line) yield(line) ifblockendensuref.closeendend

help(arg = nil)

Issues the HELP command.

[Source]

defhelp(arg = nil) cmd = "HELP"ifargcmd = cmd+" "+argendsendcmd(cmd) end

list(*args) {|line| ...}

Returns an array of file information in the directory (the output is like `ls -l`). If a block is given, it iterates through the listing.

[Source]

deflist(*args, &block) cmd = "LIST"args.eachdo|arg|cmd = cmd+" "+argendifblockretrlines(cmd, &block) elselines = [] retrlines(cmd) do|line|lines<<lineendreturnlinesendend

login(user = "anonymous", passwd = nil, acct = nil)

Logs in to the remote host. The session must have been previously connected. If is the string "anonymous" and the is , a password of is synthesized. If the parameter is not , an FTP ACCT command is sent following the successful login. Raises an exception on error (typically ).

[Source]

deflogin(user = "anonymous", passwd = nil, acct = nil) ifuser=="anonymous"andpasswd==nilpasswd = getaddressendresp = ""synchronizedoresp = sendcmd('USER '+user) ifresp[0] ==?3resp = sendcmd('PASS '+passwd) endifresp[0] ==?3resp = sendcmd('ACCT '+acct) endendifresp[0] !=?2raiseFTPReplyError, [email protected] = respend

mdtm(filename)

Issues the MDTM command. TODO: more info.

[Source]

defmdtm(filename) resp = sendcmd("MDTM "+filename) ifresp[0, 3] =="213"returnresp[3..-1].stripendend

mkdir(dirname)

Creates a remote directory.

[Source]

defmkdir(dirname) resp = sendcmd("MKD "+dirname) returnparse257(resp) end

mtime(filename, local = false)

Returns the last modification time of the (remote) file. If is , it is returned as a local time, otherwise it’s a UTC time.

[Source]

defmtime(filename, local = false) str = mdtm(filename) ary = str.scan(MDTM_REGEXP)[0].collect {|i|i.to_i} returnlocal?Time.local(*ary) :Time.gm(*ary) end

nlst(dir = nil)

Returns an array of filenames in the remote directory.

[Source]

defnlst(dir = nil) cmd = "NLST"ifdircmd = cmd+" "+direndfiles = [] retrlines(cmd) do|line|files.push(line) endreturnfilesend

noop()

Issues a NOOP command.

[Source]

defnoopvoidcmd("NOOP") end

put(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block)

Transfers to the server in whatever mode the session is set (text or binary). See puttextfile and putbinaryfile.

[Source]

defput(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected](localfile, remotefile, &block) elseputbinaryfile(localfile, remotefile, blocksize, &block) endend

putbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Transfers to the server in binary mode, storing the result in . If a block is supplied, calls it, passing in the transmitted data in chunks.

[Source]

defputbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block) [email protected]_offset = size(remotefile) rescueNet::FTPPermErrorrest_offset = nilendelserest_offset = nilendf = open(localfile) beginf.binmodestorbinary("STOR "+remotefile, f, blocksize, rest_offset, &block) ensuref.closeendend

puttextfile(localfile, remotefile = File.basename(localfile)) {|line| ...}

Transfers to the server in ASCII (text) mode, storing the result in . If callback or an associated block is supplied, calls it, passing in the transmitted data one line at a time.

[Source]

defputtextfile(localfile, remotefile = File.basename(localfile), &block) f = open(localfile) beginstorlines("STOR "+remotefile, f, &block) ensuref.closeendend

pwd()

Returns the current remote directory.

[Source]

defpwdresp = sendcmd("PWD") returnparse257(resp) end

rename(fromname, toname)

Renames a file on the server.

[Source]

defrename(fromname, toname) resp = sendcmd("RNFR "+fromname) ifresp[0] !=?3raiseFTPReplyError, respendvoidcmd("RNTO "+toname) end

retrbinary(cmd, blocksize, rest_offset = nil) {|data| ...}

Puts the connection into binary (image) mode, issues the given command, and fetches the data returned, passing it to the associated block in chunks of characters. Note that is a server command (such as "RETR myfile").

[Source]

defretrbinary(cmd, blocksize, rest_offset = nil) synchronizedovoidcmd("TYPE I") conn = transfercmd(cmd, rest_offset) loopdodata = conn.read(blocksize) breakifdata==nilyield(data) endconn.closevoidrespendend

retrlines(cmd) {|line| ...}

Puts the connection into ASCII (text) mode, issues the given command, and passes the resulting data, one line at a time, to the associated block. If no block is given, prints the lines. Note that is a server command (such as "RETR myfile").

[Source]

defretrlines(cmd) synchronizedovoidcmd("TYPE A") conn = transfercmd(cmd) loopdoline = conn.getsbreakifline==nilifline[-2, 2] ==CRLFline = line[0..-3] elsifline[-1] ==?\nline = line[0..-2] endyield(line) endconn.closevoidrespendend

return_code()

Obsolete

[Source]

defreturn_code$stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing") return"\n"end

return_code=(s)

Obsolete

[Source]

defreturn_code=(s) $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing") end

rmdir(dirname)

Removes a remote directory.

[Source]

defrmdir(dirname) voidcmd("RMD "+dirname) end

sendcmd(cmd)

Sends a command and returns the response.

[Source]

defsendcmd(cmd) synchronizedoputline(cmd) returngetrespendend

site(arg)

Issues a SITE command.

[Source]

defsite(arg) cmd = "SITE "+argvoidcmd(cmd) end

size(filename)

Returns the size of the given (remote) filename.

[Source]

defsize(filename) voidcmd("TYPE I") resp = sendcmd("SIZE "+filename) ifresp[0, 3] !="213"raiseFTPReplyError, respendreturnresp[3..-1].strip.to_iend

status()

Returns the status (STAT command).

[Source]

defstatusline = "STAT"+CRLFprint"put: STAT\n"[email protected][email protected](line, Socket::MSG_OOB) returngetrespend

storbinary(cmd, file, blocksize, rest_offset = nil) {|data| ...}

Puts the connection into binary (image) mode, issues the given server-side command (such as "STOR myfile"), and sends the contents of the file named to the server. If the optional block is given, it also passes it the data, in chunks of characters.

[Source]

defstorbinary(cmd, file, blocksize, rest_offset = nil, &block) ifrest_offsetfile.seek(rest_offset, IO::SEEK_SET) endsynchronizedovoidcmd("TYPE I") conn = transfercmd(cmd, rest_offset) loopdobuf = file.read(blocksize) breakifbuf==nilconn.write(buf) yield(buf) ifblockendconn.closevoidrespendend

storlines(cmd, file) {|line| ...}

Puts the connection into ASCII (text) mode, issues the given server-side command (such as "STOR myfile"), and sends the contents of the file named to the server, one line at a time. If the optional block is given, it also passes it the lines.

[Source]

defstorlines(cmd, file, &block) synchronizedovoidcmd("TYPE A") conn = transfercmd(cmd) loopdobuf = file.getsbreakifbuf==nilifbuf[-2, 2] !=CRLFbuf = buf.chomp+CRLFendconn.write(buf) yield(buf) ifblockendconn.closevoidrespendend

system()

Returns system information.

[Source]

defsystemresp = sendcmd("SYST") ifresp[0, 3] !="215"raiseFTPReplyError, respendreturnresp[4..-1] end

voidcmd(cmd)

Sends a command and expect a response beginning with ‘2’.

[Source]

defvoidcmd(cmd) synchronizedoputline(cmd) voidrespendend
Sours: https://www.cs.auckland.ac.nz/references/ruby/stdlib/libdoc/net/ftp/rdoc/classes/Net/FTP.html
How to Setup an FTP Server on Windows 10

Name

Net::FTP — FTP connection class

Synopsis

is a class for File Transfer Protocol (FTP) client-side connection.

Required Library

require ‘net/ftp’

Example

require 'net/ftp' ftp = Net::FTP::new("ftp.ruby-lang.org") ftp.login("anonymous", "[email protected]") ftp.chdir("/pub/ruby") tgz = ftp.list("ruby-*.tar.gz").sort.last print "the latest version is ", tgz, "\n" ftp.getbinaryfile(tgz, tgz) ftp.close

Class Methods

Creates a object

Instance Methods

Aborts the previous command.

Sets the account.

Changes the current directory.

Closes the connection.

Returns if the connection is closed.

Connects to host.

Returns the debug mode status.

Sets the debug mode status.

Deletes a file.

Retrieves a remote file from the server. If callback or a block is specified, it’s executed with the retrieved data. performs newline code conversion.

Displays help.

Returns the server’s last response.

Returns an array of file information in the directory. If a block is specified, it iterates through the listing.

f.list("/pub/ruby") ...

Get Ruby in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.

Start your free trial

Sours: https://www.oreilly.com/library/view/ruby-in-a/0596002149/re90.html

Ruby ftp

This class implements the File Transfer Protocol. If you have used a command-line FTP program, and are familiar with the commands, you will be able to use this class easily. Some extra features are included to take advantage of Ruby’s style and strengths.

Example

require'net/ftp'

Example 1

ftp=Net::FTP.new('example.com')ftp.loginfiles=ftp.chdir('pub/lang/ruby/contrib')files=ftp.list('n*')ftp.getbinaryfile('nif.rb-0.91.gz','nif.gz',1024)ftp.close

Example 2

Net::FTP.open('example.com')do|ftp|ftp.loginfiles=ftp.chdir('pub/lang/ruby/contrib')files=ftp.list('n*')ftp.getbinaryfile('nif.rb-0.91.gz','nif.gz',1024)end

Major Methods

The following are the methods most likely to be useful to users:

Constants

FACT_PARSERS = Hash.new(CASE_DEPENDENT_PARSER)

TIME_PARSER = ->(value, local = false) { unless /\A(?

OCTAL_PARSER = ->(value) { value.to_i(8) }

DECIMAL_PARSER = ->(value) { value.to_i }

CASE_INDEPENDENT_PARSER = ->(value) { value.downcase }

CASE_DEPENDENT_PARSER = ->(value) { value }

Attributes

[R]last_response

The server’s last response.

[R]lastresp

The server’s last response code.

[R]last_response_code

The server’s last response code.

[R]welcome

The server’s welcome message.

[R]read_timeout

Number of seconds to wait for one block to be read (via one read(2) call). Any number may be used, including Floats for fractional seconds. If the FTP object cannot read data in this many seconds, it raises a Timeout::Error exception. The default value is 60 seconds.

[RW]ssl_handshake_timeout

Number of seconds to wait for the TLS handshake. Any number may be used, including Floats for fractional seconds. If the FTP object cannot complete the TLS handshake in this many seconds, it raises a Net::OpenTimeout exception. The default value is . If is is used instead.

[RW]open_timeout

Number of seconds to wait for the connection to open. Any number may be used, including Floats for fractional seconds. If the FTP object cannot open a connection in this many seconds, it raises a Net::OpenTimeout exception. The default value is .

[RW]resume

Sets or retrieves the status, which decides whether incomplete transfers are resumed or restarted. Default: .

[RW]debug_mode

When all traffic to and from the server is written to +$stdout+. Default: .

[RW]passive

When the connection is in passive mode. Default: .

[R]binary

When transfers are performed in binary mode. Default: .

Show files where this class is defined (1 file)

Register or log in to add new notes.

Sours: https://apidock.com/ruby/Net/FTP
How much money can a noob make in one day?

Net::FTP hangs

Running ruby 1.8.5 (2006-08-25) on Mac OS X 10.4.8.

I’m trying to get this example from the Ruby_Cookbook to work, but it
hangs in the ftp.list method. What am I doing wrong?

#!/usr/bin/env ruby

require ‘net/ftp’

ftp = Net::FTP.open(“ftp.ibiblio.org”) do |ftp|
ftp.login
ftp.chdir(“pub/linux/”)
ftp.list(‘Linux’) {|file| puts file}
end

Eventually this will fail with these messages:

/opt/local/lib/ruby/1.8/net/ftp.rb:241:in sendcmd’
from /opt/local/lib/ruby/1.8/monitor.rb:238:in sendcmd’
from /opt/local/lib/ruby/1.8/net/ftp.rb:336:in retrlines’
from /opt/local/lib/ruby/1.8/monitor.rb:238:in retrlines’
from /opt/local/lib/ruby/1.8/net/ftp.rb:625:in open’
from ftptest.rb:5

I can connect to this server and issue similar commands using the
command line ftp client:

ruby$ ftp
ftp> open ftp.ibiblio.org
Connected to ibiblio.org.
220 ProFTPD Server (Bring it on…)
Name (ftp.ibiblio.org:tim): anonymous
331 Anonymous login ok, send your complete email address as your
password.
Password:
230-
Welcome to ftp.ibiblio.org, the public ftp server of ibiblio.org. We
hope you find what you’re looking for.

If you have any problems or questions, please send email to

[email protected]

Thanks!

230 Anonymous access granted, restrictions apply.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> cd pub/linux
250 CWD command successful
ftp> ls Linux
229 Entering Extended Passive Mode (|||60724|)
150 Opening ASCII mode data connection for file list
-rw-r–r-- 1 (?) users 531113 Feb 26 11:06 00-find.Linux.gz
-rw-rw-r-- 1 (?) admin 73 Mar 9 2001
How-do-I-get-Linux
226 Transfer complete.
ftp>

Sours: https://www.ruby-forum.com/t/net-ftp-hangs/86945

You will also be interested:

Net::FTP

This class implements the File Transfer Protocol. If you have used a command-line FTP program, and are familiar with the commands, you will be able to use this class easily. Some extra features are included to take advantage of Ruby's style and strengths.

Installation

Add this line to your application's Gemfile:

And then execute:

Or install it yourself as:

Usage

Example 1

ftp=Net::FTP.new('example.com')ftp.loginfiles=ftp.chdir('pub/lang/ruby/contrib')files=ftp.list('n*')ftp.getbinaryfile('nif.rb-0.91.gz','nif.gz',1024)ftp.close

Example 2

Net::FTP.open('example.com')do |ftp| ftp.loginfiles=ftp.chdir('pub/lang/ruby/contrib')files=ftp.list('n*')ftp.getbinaryfile('nif.rb-0.91.gz','nif.gz',1024)end

Development

After checking out the repo, run to install dependencies. Then, run to run the tests. You can also run for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run . To release a new version, update the version number in , and then run , which will create a git tag for the version, push git commits and tags, and push the file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/net-ftp.

Sours: https://github.com/ruby/net-ftp


4 5 6 7 8