Skip to content

Instantly share code, notes, and snippets.

@nikolaifedorov
Forked from 3dd13/ruby_ftp_example.rb
Last active December 21, 2015 19:19
Show Gist options
  • Save nikolaifedorov/6353364 to your computer and use it in GitHub Desktop.
Save nikolaifedorov/6353364 to your computer and use it in GitHub Desktop.
Sample code of using Ruby Net::FTP library. Login to FTP server, list out files with parsing for unix-like ftp, check directory existence, upload files
require 'net/ftp'
CONTENT_SERVER_DOMAIN_NAME = "one-of-the-ftp-server.thought-sauce.com.hk"
CONTENT_SERVER_FTP_LOGIN = "saucy-ftp-server-login"
CONTENT_SERVER_FTP_PASSWORD = "saucy-ftp-server-password"
# LOGIN and LIST available files at default home directory
Net::FTP.open(CONTENT_SERVER_DOMAIN_NAME, CONTENT_SERVER_FTP_LOGIN, CONTENT_SERVER_FTP_PASSWORD) do |ftp|
files = ftp.list.map{ |obj| parse_ls_unix_like_format(obj) }
puts "list out files in root directory:"
puts files
end
#
# Avalable params:
# type
# mode
# number
# owner
# group
# size
# mod_time
# path
#
def parse_ls_unix_like_format(str="")
str = str.force_encoding('utf-8')
reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/
str.match(reg)
end
# check if the directory existence
# create the directory if it does not exist yet
Net::FTP.open(CONTENT_SERVER_DOMAIN_NAME, CONTENT_SERVER_FTP_LOGIN, CONTENT_SERVER_FTP_PASSWORD) do |ftp|
ftp.mkdir("/root_level") if !ftp.list("/").any?{|dir| dir.match(/\sroot_level$/)}
# create nested directory
# it does not create directory tree
# therefore, create "/root_level" before creating "/root_level/nested"
ipad_folder = ftp.list("/root_level")
ftp.mkdir("/root_level/nested") if !ipad_folder.any?{|dir| dir.match(/\snested$/)}
end
# upload files
TXT_FILE_OBJECT = File.new("/home/though-sauce/to_be_uploaded/0001.txt")
Net::FTP.open(CONTENT_SERVER_DOMAIN_NAME, CONTENT_SERVER_FTP_LOGIN, CONTENT_SERVER_FTP_PASSWORD) do |ftp|
ftp.putbinaryfile(TXT_FILE_OBJECT)
end
# upload files and rename it
Net::FTP.open(CONTENT_SERVER_DOMAIN_NAME, CONTENT_SERVER_FTP_LOGIN, CONTENT_SERVER_FTP_PASSWORD) do |ftp|
ftp.putbinaryfile(TXT_FILE_OBJECT, "0001.txt.in_process")
end
# upload files to nested directory
Net::FTP.open(CONTENT_SERVER_DOMAIN_NAME, CONTENT_SERVER_FTP_LOGIN, CONTENT_SERVER_FTP_PASSWORD) do |ftp|
ftp.putbinaryfile(TXT_FILE_OBJECT, "/root_level/nested/#{File.basename(TXT_FILE_OBJECT)}")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment