Module: BBFS::FileCopy

Defined in:
lib/file_copy.rb,
lib/file_copy/copy.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.sftp_copy(username, password, server, files_map) ⇒ Object

Simply copy map files using sftp server on dest_server. Note: stfp.upload support parallel uploads - default is 2. TODO(kolman): packing files, all, not all, determine by part of file.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/file_copy/copy.rb', line 31

def sftp_copy(username, password, server, files_map)
  ssh = FileCopy.ssh_connect(username, password, server)
  ssh.sftp.connect do |sftp|
    uploads = files_map.map { |from,to|
      remote_dir = File.dirname(to)
      sftp_mkdir_recursive(sftp, File.dirname(to))
      p "Copying #{from} to #{to}"
      sftp.upload(from, to)
    }
    uploads.each { |u| u.wait }
    p "Done."
  end # ssh.sftp.connect
end

.sftp_mkdir_recursive(sftp, path) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/file_copy/copy.rb', line 46

def sftp_mkdir_recursive(sftp, path)
  dir_stat = nil
  begin
    p "Stat remote dir: #{path}."
    dir_stat = sftp.stat!(path).directory?
    p "Stat result #{dir_stat}."
  rescue Net::SFTP::StatusException
  end
  if !dir_stat
    p "Directory does not exists: #{path}."
    sftp_mkdir_recursive sftp, File.dirname(path)
    sftp.mkdir!(path)
  end
end

.ssh_connect(username, password, server) ⇒ Object

Creates ssh connection, assumes username and password or without password but with ssh keys.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/file_copy/copy.rb', line 9

def ssh_connect(username, password, server)
  username = (username and username.length > 0) ? username : ENV['USER']
  password = (password and password.length > 0) ? password : nil
  port = 22 # 22 is a standart SSH port
  raise "Undefined server" unless server
  p "Trying to connect(ssh): #{username}, #{password}, #{server}."
  if (username and password)
    Net::SSH.start(server, username,
                   :password => password,
                   :port => port)
  elsif (username)
    Net::SSH.start(server, username,
                   :port => port)
  else
    raise "Undefined username"
  end
end