Scan and Copy

One of the ways I am able to exercise my Ruby skills is in the day to day network admin tasks. For example, I had to come up with a method of saving all of a users ‘important’ documents off of their desktop computer in preparation for a wipe and re-image. Not only that, but it’s a good idea. So I wrote ‘scan and copy’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#Stuff we need
require 'getoptlong'
require 'ftools'

#Get the command line options
#Required command lines
# --name 'user name'
# a list of extensions to search for

@backed = 0
@collisions = 0
@totfiles = 0
@filetype = Array.new

opts = GetoptLong.new(["--name", "-n", GetoptLong::REQUIRED_ARGUMENT])

#Parse the options, assigning them to the correct variables.
opts.each do |opt, arg|
  case opt
    when  "--name"
      @path = "y\:\\backups\\" + arg.to_s
    end
end

for ext in ARGV
  @filetype << ext
end


#let's tell everyone what we are doing...
  puts ""
  puts "Copying to..."
  puts @path
  puts "Looking for..."
  puts @filetype
  puts ""

#Do basic checking to insure that everything we need is there

unless File.exist?(@path)
  Dir.mkdir(@path)
end

  #Start main process of program
  Dir['/**/**'].each do |item|
    @totfiles = @totfiles + 1
    unless(FileTest.directory?(item))
      if @filetype.include?(File.extname(item))
        if FileTest.exist?(@path + "\\" + File.basename(item))
          p = @path + "\\" + File.basename(item, ".*") +
             "_"+ rand(100000000).to_s + "_" + File.extname(item)
          File.copy item, p
          printf("C")
          @collisions = @collisions + 1
          @backed = @backed + 1
          #Duplicate File Error.
        else 
          p = @path + "\\" + File.basename(item)
          File.copy item, p
          #Backed up file
          printf("B")
          @backed = @backed + 1
        end
      else
        printf(".")
      end
    end
  end


puts ""
puts "Checked #{@totfiles} Files."
puts "#{@backed} Files backed up with #{@collisions} filename collisions"

Leave a Reply