Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3444708
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T08:56:59+00:00 2026-05-18T08:56:59+00:00

I am currently writing a security tool in python that runs as a daemon

  • 0

I am currently writing a security tool in python that runs as a daemon on a host computer. Whenever a usb storage device is detected, it will copy all of the files from the usb to some dir on the host computer. Is there any easy way to do this sort of usb detection / interface? Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T08:56:59+00:00Added an answer on May 18, 2026 at 8:56 am

    Yes, you need to use the RegisterDeviceNotification Windows API call. As far as I know, there is no Python module that wraps this functionality, so you have to use ctypes to call this function.

    Fortunately, you are not the first person who has wanted to do this, so there are some code samples floating around the web. WxPython provides a code sample, but as you are writing a daemon this may not interest you. You might want to try the following code sample, which relies on both ctypes and pywin32, lifted shameless from Tim Golden:

    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
    
    import win32gui
    import win32gui_struct
    struct = win32gui_struct.struct
    pywintypes = win32gui_struct.pywintypes
    import win32con
    
    GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
    DBT_DEVICEARRIVAL = 0x8000
    DBT_DEVICEREMOVECOMPLETE = 0x8004
    
    import ctypes
    
    #
    # Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be
    # used for monkey-patching said module with correct handling
    # of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE
    #
    def _UnpackDEV_BROADCAST (lparam):
      if lparam == 0: return None
      hdr_format = "iii"
      hdr_size = struct.calcsize (hdr_format)
      hdr_buf = win32gui.PyGetMemory (lparam, hdr_size)
      size, devtype, reserved = struct.unpack ("iii", hdr_buf)
      # Due to x64 alignment issues, we need to use the full format string over
      # the entire buffer.  ie, on x64:
      # calcsize('iiiP') != calcsize('iii')+calcsize('P')
      buf = win32gui.PyGetMemory (lparam, size)
    
      extra = {}
      if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
        fmt = hdr_format + "16s"
        _, _, _, guid_bytes = struct.unpack (fmt, buf[:struct.calcsize(fmt)])
        extra['classguid'] = pywintypes.IID (guid_bytes, True)
        extra['name'] = ctypes.wstring_at (lparam + struct.calcsize(fmt))
      else:
        raise NotImplementedError("unknown device type %d" % (devtype,))
      return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
    win32gui_struct.UnpackDEV_BROADCAST = _UnpackDEV_BROADCAST
    
    class DeviceEventService (win32serviceutil.ServiceFramework):
    
      _svc_name_ = "DevEventHandler"
      _svc_display_name_ = "Device Event Handler"
      _svc_description_ = "Handle device notification events"
    
      def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__ (self, args)
        self.hWaitStop = win32event.CreateEvent (None, 0, 0, None)
        #
        # Specify that we're interested in device interface
        # events for USB devices
        #
        filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE (
          GUID_DEVINTERFACE_USB_DEVICE
        )
        self.hDevNotify = win32gui.RegisterDeviceNotification (
          self.ssh, # copy of the service status handle
          filter,
          win32con.DEVICE_NOTIFY_SERVICE_HANDLE
        )
    
      #
      # Add to the list of controls already handled by the underlying
      # ServiceFramework class. We're only interested in device events
      #
      def GetAcceptedControls(self):
        rc = win32serviceutil.ServiceFramework.GetAcceptedControls (self)
        rc |= win32service.SERVICE_CONTROL_DEVICEEVENT
        return rc
    
      #
      # Handle non-standard service events (including our device broadcasts)
      # by logging to the Application event log
      #
      def SvcOtherEx(self, control, event_type, data):
        if control == win32service.SERVICE_CONTROL_DEVICEEVENT:
          info = win32gui_struct.UnpackDEV_BROADCAST(data)
          #
          # This is the key bit here where you'll presumably
          # do something other than log the event. Perhaps pulse
          # a named event or write to a secure pipe etc. etc.
          #
          if event_type == DBT_DEVICEARRIVAL:
            servicemanager.LogMsg (
              servicemanager.EVENTLOG_INFORMATION_TYPE,
              0xF000,
              ("Device %s arrived" % info.name, '')
            )
          elif event_type == DBT_DEVICEREMOVECOMPLETE:
            servicemanager.LogMsg (
              servicemanager.EVENTLOG_INFORMATION_TYPE,
              0xF000,
              ("Device %s removed" % info.name, '')
            )
    
      #
      # Standard stuff for stopping and running service; nothing
      # specific to device notifications
      #
      def SvcStop(self):
        self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent (self.hWaitStop)
    
      def SvcDoRun(self):
        win32event.WaitForSingleObject (self.hWaitStop, win32event.INFINITE)
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          servicemanager.PYS_SERVICE_STOPPED,
          (self._svc_name_, '')
        )
    
    if __name__=='__main__':
      win32serviceutil.HandleCommandLine (DeviceEventService)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to have generalised email templates. Currently I have multiple email templates with
We manage a site for a medical charity. They have a number of links
IE is giving me an undefined NAN when i try to view the calender...
I am using a 3rd-party rotator object, which is providing a smooth, random rotation

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.