How can I automatically copy files to a USB drive when I connect it to my computer?

94,712

Solution 1

You can quite easily build your own solution for Windows using autorun.inf and a .bat file.

Create a bat file to copy a directory to your usb drive.

xcopy /e /y c:\podcasts\*.* .\dir_on_usb_drive

Place the bat file on your mp3 player and create an autorun.inf using these instructions

Now you should have your own homebuilt solution to your problem but it's certainly possible that there's pre-made solutions out there :)

Solution 2

For Linux:

If you don't mind a little Python scripting you could write a daemon that listens to HAL for events and then launches a script once a device of your choice has been plugged in. An example script would look like this:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import dbus
import dbus.service
if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
    import dbus.glib
import gobject
import sys
import os

class DeviceManager:
    def __init__(self):
        self.bus = dbus.SystemBus()
        self.bus.add_signal_receiver(self.device_added,
                        'DeviceAdded',
                        'org.freedesktop.Hal.Manager',
                        'org.freedesktop.Hal',
                        '/org/freedesktop/Hal/Manager')

        self.bus.add_signal_receiver(self.device_removed,
                        'DeviceRemoved',
                        'org.freedesktop.Hal.Manager',
                        'org.freedesktop.Hal',
                        '/org/freedesktop/Hal/Manager')

    def udi_to_device(self, udi):
        return self.bus.get_object("org.freedesktop.Hal", udi)

    def device_added(self, udi):
        print 'Added', udi
        properties = self.udi_to_device(udi).GetAllProperties()
        if properties.get('info.category') == u'volume':
            label, dev = properties.get('volume.label'), properties.get('block.device')
            print 'Mounting %s on /media/%s' %(dev, label)
            os.system('pmount %s /media/%s' %(dev, label))

    def device_removed(self, udi):
        print 'Removed', udi

if __name__ == '__main__':
    m = DeviceManager()

    mainloop = gobject.MainLoop()
    try:
        mainloop.run()
    except KeyboardInterrupt:
        mainloop.quit()
        print 'Exiting...'
        sys.exit(0)

You just have to modify the device_added() function to limit it to the specific device and replace the os.system() call with your custom script.

For limiting it to the drive the volume.uuid property could be used and a full list of available properties can be displayed with the hal-device program.

To start the daemon on boot, just start it from /etc/rc.local.

Solution 3

Windows 7 and autosync to your flash/USB device on insert!

Download SyncToy and establish your folder pairing and sync name("SyncTest")

see: How-to: Using SyncToy to make a nightly mirror of My Documents

  • Run computer management console
  • Event viewer/windows logs/system
  • Find the media insertion event
    • “The Portable Device Enumerator Service service entered the running state.” (You may need to clear you event log and eject/reinsert you media to trigger this log event)
  • In the upper event window, right click on the event and select "Attach Task To This Event"
  • Windows open "Create Basic Task Window"
  • Give your task a name and hit next
  • Event information is already filled in, next
  • Action should show "Start a Program", next
  • In the Start a Program window, browse to SyncToyCmd.exe(or your chosen sync app)
  • Add arguments. If your backup pairing is called SyncTest, enter "-RsyncTest". Do not add quotes, do not add a space after the -R, SyncToy command line(or maybe Windows 7) is case sensative so SyncTest does not equal synctest!
  • Next, Finish

You can run the task right from Task Scheduler to verify it works. Now the only other problem I had was running my laptop on batteries, in Task Manager under the conditions tab, uncheck "Start the task only if the computer is on AC power", otherwise task will only run when AC is plugged in.

Also, as USB polls and disconnects/reconnects, this task will run every couple of minutes, actually kinda cool, it's auto-syncing to the USB HDD all the time :)

Solution 4

Edit: it turns out SyncBack SE has a trigger action:

Open Profile, go to “When” tab, then “Insert”. It lets you specify by drive letter, label, or serial number.

However the SE version is not free and Windows only (I think)

Or you could try adding an Autorun event for your syncing program (example for SyncToy) using TweakUI

  • Open TweakUI
  • Go to my computer –> autorun–> handlers
  • Click create
  • Find where Synctoy is located (program files as default)
  • Double click the program launcher logo
  • Select all the media radio buttons on the list below.
  • Click ok
  • Click apply.

  • Now plug in your pen drive.

  • In my computer right click the drive and select properties.
  • Click the autoplay tab
  • Select music from the drop down menu.
  • Click the radio button “select action to perform”
  • Now select the sync with SyncToy logo
  • Repeat for the other options given by the drop down menu
  • Click apply then ok.
  • Remove and reinsert your drive to see if it has worked

I can't seem to find any (other) program that will start automatically when you connect your USB device.

They all rely on scheduling to start syncing. You could decide to have it scheduled every our, it will simply fail if the USB device is not connected and run if it is.

But too be honest it would be easier if you simply clicked on the sync button, you have to plug in your USB device manually as well.

Anyway I also found a synchronization tool that runs on both Linux and Windows: DirSync Pro which is completely free, runs on Java and has a nice GUI:

*  Synchronization
      o Powerful synchronization algorithm.
      o Bidirectional (Two way) and Unidirectional (One way) synchronization mode.
      o Option for various behavior of conflict resolution for Bidirectional Synchronization.
      o Synchronizes unlimited number of folders.
      o Large number of options to change the synchronization behavior.
      o Option to synchonise subdirectories recursively.
      o Synchronizes files/folders any file system (FAT, FAT16, FAT32, NTFS, WinFS, UDF, Ext2, Ext3, ...).
      o Synchronizes files from/to network drives
      o Synchronizes files from/to any mounted devices (Harddisks, USB-Sticks, Memory cards, External drives, CD/DVD's, ...).
      o Synchronization could be used for making incremental backups.
      o Option to create up to 50 backups from the modified/changed files before synchronization.
      o Option to define a backup folder.
      o Option for handling symbolic links.
      o Option for handling time-stamps.
* General
      o Easy, clear and user-friendly graphical user interface, no unnecessary gadget you never use.
      o Runs on every modern operating system including Windows™, Linux™ and Macintosh™
      o It is Portable! It does not need any installation. Just run the application!
      o Open source, it is 100% free of charge, 100% free of commercial text, 100% free of advertisements and 100% free of spyware.
      o No time/function limitations
      o Uses no local database, so no overhead
      o Does not need any installation. Just download and run it. You can put it on you USB-stick en you can run it on any computer/any platform.
* Logging
      o Advanced logging/reporting facilities. Just select a log level and define where to write the log.
      o Option to log on application level (default log)
      o Option to log on each directory level (dir log)
      o Option to define the log leven (how much to log)

Solution 5

Under Linux, instead of having a program running continuously to listen for events, you can use the already running ones. You can add some hooks to udev that mounts the device to a temporary location and then launches rsync to synchronize a bunch of directories.

By the way you can define specific actions according to your device signature: synchronize your work documents when a specific key is inserted, or your music if a USB mass storage MP3 player is inserted, or your books when plugging a Kindle there.

Share:
94,712

Related videos on Youtube

daphshez
Author by

daphshez

Updated on September 17, 2022

Comments

  • daphshez
    daphshez almost 2 years

    I am looking for a solution for copying all the files from a specific directory on the hard drive, to a specific directory on a USB memory device, once this device is connected.

    I have a program that downloads podcast episodes for me.

    I would like these files to be automatically moved (or at least copied) to my mp3 player once I connect it to the computer.

    I have both windows xp and linux machines, so a solution for any of them will work for me.

    • Ivo Flipse
      Ivo Flipse almost 15 years
      I assume your not satisfied with a scheduled synchronization?
  • Paxxi
    Paxxi almost 15 years
    you could possibly combine this with a schduled task that's using the new trigger events in Vista and Windows 7 to have it run when a usb device is connected.
  • Ivo Flipse
    Ivo Flipse almost 15 years
    I think the autorun solution mentioned in the other answer could do the trick
  • Ian G
    Ian G almost 15 years
    awesome tip!!!! +10
  • daphshez
    daphshez almost 15 years
    Thank for the suggestion. The autorun.inf should be: [autorun] open=getpodcasts.bat action=copy podcasts to player At least winxp sp2, this will only open the AutoPlayer, with the new "copy podcasts to player" at the top. I don't think there's a way to override this and force it to run the script silently. Also obviously you have to have AutoPlay turned on. Having the command I need pop on the window is actually a great imporvement, but it still isn't exactly what I was looking for.
  • daphshez
    daphshez almost 15 years
    Just as a note, I believe the "on insert" features is new to SyncBack SE 5.
  • Admin
    Admin almost 15 years
    nice thinking! :) +1
  • daphshez
    daphshez almost 15 years
    thanks; but my problem isn't the copy itself (it's just bunch of file residing in one directory), but making this copy happen at the right time. A scheduled task is nice, but not quite what I was looking for.
  • Ivo Flipse
    Ivo Flipse over 14 years
    I can't verify if this is a good answer, but you deserve an upvote for the trouble alone! Anyhow, I would try and make it a little easier on the non-programmers here ;-) like me!
  • ale
    ale over 13 years
    Didn't Microsoft just remove the ability to use autorun on a thumb drive?