Attachment @ Linux live backup file_download
2018-11-26
2018
11-26
«live_backup.rb»
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
#!/usr/bin/env ruby

$VERBOSE = nil

exit if `whoami`.strip != 'root'

puts "USAGE: #{File.basename __FILE__} [root_dir_name|dirs|tools]"

# http://linuxclues.blogspot.it/2007/07/backup-your-system-using-tar.html

bkdir  = File.expand_path(File.dirname(__FILE__))
prefix = "#{bkdir}/#{Time.now.strftime '%F'}"
target = ARGV[0]

# clean system logs
system %Q|find /var/log -path /var/log/installer -prune -o -type f -exec dd if=/dev/null of=\\"{}\\" \\; 2> /dev/null > /dev/null|
system %Q|find /var/log -name "*.[0-9].gz" -exec rm -f \\"{}\\" \\;|

# https://superuser.com/questions/168749/is-there-a-way-to-see-any-tar-progress-per-file
def tar_with_pv(src, filename, opts = {})
  name = "-N #{opts[:name]}" if opts[:name]
  size = `du -sb #{opts[:exclude]} #{src}`.to_i
  system %Q[ tar -cpf - #{opts[:exclude]} #{src} | pv #{name} -w 78 -s #{size} | xz -c > #{filename} ]
end # tar_with_pv

# make compressed backups
Dir.chdir('/') do
  lista = Dir['*'].sort
  lista = lista & [target] if target
  lista.each do |d|
    exclude = "--exclude=#{d}/*"     if %w{media dev proc sys tmp run}.include?(d)
    exclude = "--exclude=#{d}/*/*"   if d == 'mnt'
    exclude = "--exclude=#{d}/log/*" if d == 'var'

    #system %Q| tar -cvpJf "#{prefix}-root_#{d}.txz" #{exclude} #{d} |
    tar_with_pv d, "#{prefix}-root_#{d}.txz", name: d, exclude: exclude

    # keep the most recent backup file
    Dir["#{bkdir}/20??-??-??-root_#{d}.txz"].sort[0..-2].to_a.each{|f| File.unlink f }
  end
end

# backup a folder structure
Dir.chdir('/path/to/folder') do
  system %Q[ find -type d | sort | tar -cpJf #{prefix}-dirs.txz --no-recursion -T - ] if target.nil? || target == 'dirs'
end

Dir.chdir(bkdir) do
  if target.nil? || target == 'tools'
    `mkdir -p tools`
    system "crontab -l > ./tools/crontab_root.txt"
    system "dpkg -l    > ./tools/packages.txt"
    #system "cat /proc/config.gz > config-#{`uname -r`.strip}.gz"
    disk = '/dev/sdX'
    system "sfdisk -d #{disk}  > ./tools/disk.ptable"
    system "dd     if=#{disk} of=./tools/mbr.bin     bs=4K count=1"
    system %Q[ tar -C tools -cvpJf "#{prefix}-tools.txz" . && rm -rf tools ]
  end

  # keep the most recent backup file
  %w{ dirs tools }.each{|k| puts Dir["20??-??-??-#{k}.txz"].sort[0..-2].to_a.each{|f| File.unlink f} }
end

# restore: tar --numeric-owner -xvJf file.txz