Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/python
- # fastcopy.py
- # Copy VMware virtual machine directories using cp and vmkfstools.
- # (c) alain.spineux@gmail.com
- # released under GPL
- # usage: fastcopy.py vm_directories_path target_dir
- # The original script can be retrieved from the author's blog:
- # http://magiksys.blogspot.co.nz/2012/09/vmware-esxi-fastcopypy-to-copy-vms.html
- #
- # vm_directories_path - the directory where VMs reside.
- # target_dir - the directory to copy all VMs to.
- #
- # If a corresponding target directory, e.g. target_dir/vm1, exists it will be moved to
- # target_dir/vm1.old and a new copy will be created in its place. After the VM is copied
- # the vm1.old will be removed.
- #
- # ATTN: don't copy recursively
- import sys, os, subprocess, re, shutil
- def copy(srcdir, dstdir):
- skipped=0
- temp_backup=dstdir+'.old'
- # If temporary backup already exists (meaning the last backup failed) leave it alone
- # and try to remove the failed one.
- # Else rename target directory for temporary backup.
- if os.path.exists(temp_backup):
- if os.path.exists(dstdir):
- shutil.rmtree(dstdir)
- else:
- if os.path.exists(dstdir):
- os.rename(dstdir, temp_backup)
- os.mkdir(dstdir)
- for filename in os.listdir(srcdir):
- fullfilename=os.path.join(srcdir, filename)
- if os.path.isdir(fullfilename):
- print fullfilename, 'SKIPPED'
- skipped+=1
- continue
- print filename
- if filename.endswith('-flat.vmdk'):
- # this is the data file, it will be copied by the .vmdk
- continue
- if re.match('.*-s[0-9]{3}.vmdk$', filename):
- # this is part of a sparse file, it will be copied by the .vmdk
- continue
- # dont use vmkfstools for snapshot files
- if filename.endswith('.vmdk') and \
- not re.match('.*-[0-9]{6}-delta.vmdk$', filename) and \
- not re.match('.*-[0-9]{6}.vmdk$', filename):
- args=['vmkfstools', '-i', fullfilename, '-d', 'thin', os.path.join(dstdir, filename) ]
- else:
- args=['cp', fullfilename, os.path.join(dstdir, filename) ]
- # print args
- subprocess.call(args)
- # Remove the temporary backup.
- if os.path.exists(temp_backup):
- shutil.rmtree(temp_backup)
- return skipped
- if len(sys.argv)<3:
- print 'Usage: fastcopy.py vm_directories_path target_dir'
- sys.exit(1)
- dstdir=sys.argv[2].rstrip('/')
- if not os.path.isdir(dstdir):
- print 'target_dir must be a directory'
- sys.exit(1)
- if not os.path.isdir(sys.argv[1]):
- print 'vm_directories_path must be a directory'
- sys.exit(1)
- # Compile a list of source directories
- srcdirs = []
- for srcdir in os.listdir(sys.argv[1]):
- if os.path.isdir(srcdir):
- srcdirs.append(srcdir.rstrip('/'))
- skipped=0
- for srcdir in srcdirs:
- targetdir=os.path.join(dstdir, os.path.basename(srcdir))
- skipped+=copy(srcdir, targetdir)
- if skipped>0:
- print "SKIPPED:", skipped
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement