18

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.

1
  • 2
    I assume your not satisfied with a scheduled synchronization?
    – Ivo Flipse
    Aug 14, 2009 at 11:53

11 Answers 11

23

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 :)

4
  • awesome tip!!!! +10
    – Ian G
    Aug 14, 2009 at 13:23
  • 1
    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
    Aug 14, 2009 at 15:43
  • nice thinking! :) +1
    – Molly7244
    Sep 8, 2009 at 23:40
  • 3
    Didn't Microsoft just remove the ability to use autorun on a thumb drive?
    – ale
    Feb 11, 2011 at 21:05
10

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.

1
  • 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!
    – Ivo Flipse
    Oct 29, 2009 at 12:13
9

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 :)

2

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)
3
  • 1
    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.
    – Paxxi
    Aug 14, 2009 at 12:16
  • 1
    I think the autorun solution mentioned in the other answer could do the trick
    – Ivo Flipse
    Aug 14, 2009 at 12:19
  • Just as a note, I believe the "on insert" features is new to SyncBack SE 5.
    – daphshez
    Aug 16, 2009 at 6:29
1

I tried Steven's method, but the USB event wasn't showing up in "Event Viewer/Windows Logs/System" (I'm using Windows 7). I poked around a bit, and found out the USB insertion events are located in "Event Viewer/Applications and Services Logs/Microsoft/Windows/DriverFrameworks-UserMode/Operational". Try clearing the log first (just to make it easier to find the event you want), then insert the USB flash drive. Refresh the log, and a bunch of events should show up. I picked the top most event (i.e. the most recent), and assigned the task to that (make sure the event description looks like it has something specific to the particular USB drive you inserted).

I used the free SyncBack program to do the actual syncing. Works great!

1

I just use a AUTORUN.INF with a few batches to sync key folders. Very simple very effective.

Also, if you have a read only,archived autorun.inf file its hard contract usb-stick virus's

1

You are simply just forgetting to "" and end ".\dectory\" ← That end \ slash as well.

The original batch formula works, It is just now days, There are a lot of spaces in directories, batch files and command prompt HATE those.

How mine looks:

xcopy "F:\Web Stuff\Web Dev\Dev_FactorY Designs\*.*" ".\HTML_PROJ\Web Stuff\Web Dev\Dev_FactorY Designs\" /e /y
1

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.

1

When I was setting up little surveillance system with Raspberry Pi, which ran on Raspbian Wheezy, I needed to constantly move all files from FTP folder which was uploaded by IP camera. So, i wrote script in home directory (~) and called it once a minute with cron

crontab -e
*/1 * * * * sudo ~/move_images_to_usb

move_images_to_usb is ordinary bash script, I wasn't scripting before on bash, but...

#!/bin/bash

if df | grep "sda1"
then
    mkdir /media/usb0/ipcam1
    cp -r /var/ftp /media/usb0/ipcam1
    rm /var/ftp/*
fi

When usb drive inserted, its named sda1 (another drive will be sdb1, so it will not work)

0

I use a replicator program from Karenware. She's the author of a lot of small useful programs for Windows (think PowerToys from the early W98/W2K/XP days).

Here's the link. http://www.karenware.com/powertools/ptreplicator.asp

Set it up on a nightly schedule. If the USB drive is plugged in, it will sync the download folder with the USB contents.

It's free!

1
  • 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.
    – daphshez
    Sep 11, 2009 at 7:09
0

This is an old thread, but I thought I would pu this here for anyone who wants it. Change the relevant information to suit your needs then it'll do it all for you. Credit to https://superuser.com/users/232313/tyler who made the first iteration of this.

@echo off
cls
echo waiting
goto check

Change the STUFF TO COPY location to the folder that you want 
everything inside to be send to the usb's, and change the 3 instances of 
G: to whatever drive letter that the USB uses.
Good Luck!

:start
set choice=
robocopy "C:\STUFFTOCOPY" "G:" /E
echo Waiting for removal
goto wait

:check
timeout /t 1 /nobreak >nul
if exist "G:" (goto start) else goto check

:wait
timeout /t 1 /nobreak >nul
if exist "G:" (goto wait) else (
echo removed
echo waiting
goto check
)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .