How to Detect Usb Drive Insertion in Linux

How do I detect usb drive insertion in Linux?

The section "libudev - Monitoring Interface" of this document http://www.signal11.us/oss/udev/
should get you started.

Instead of a while(1) loop and a sleep, just make a function with that stuff and then set up a periodic Qt timer to call it every half second or whatever.

How can i detect USB is inserted or not for linux in C

Set up a hotplug event handler: You will get a hotplug block event when a block device appears or goes away, which you can use to mount/umount and run your handler scripts and apps.

C program to detect USB drive in Linux

One naive approach is the following:

  • execute mount | grep /dev/sda1
  • parse the output: if there is no output, that means that sda1 is not mounted

You may have to adapt the code to your specific platform.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
/* launch a command and gets its output */
FILE *f = popen("mount | grep /dev/sda1", "r");
if (NULL != f)
{
/* test if something has been outputed by
the command */
if (EOF == fgetc(f))
{
puts("/dev/sda1 is NOT mounted");
}
else
{
puts("/dev/sda1 is mounted");
}
/* close the command file */
pclose(f);
}
return 0;
}

UDEV - Run program on USB flash drive insert

First you need your rule to detect usb storage devices

/etc/udev/rules.d/10-usbmount.rules:

KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/usbdevinserted"

This runs our custom executable shell script /usr/bin/usbdevinserted:

#!/bin/bash

set 2>&1 >> /tmp/usbdevinfo

This sample script dumps the environment variables which you will need to know which device was found, eg:

DEVLINKS='/dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0 /dev/disk/by-path/pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0'
DEVNAME=/dev/sdk
DEVPATH=/devices/pci0000:00/0000:00:13.2/usb2/2-2/2-2:1.0/host29/target29:0:0/29:0:0:0/block/sdk
DEVTYPE=disk
ID_BUS=usb
ID_FS_TYPE=
ID_INSTANCE=0:0
ID_MODEL=USB_Flash_Disk
ID_MODEL_ENC='USB\x20Flash\x20Disk\x20\x20'
ID_MODEL_ID=9380
ID_PART_TABLE_TYPE=dos
ID_PART_TABLE_UUID=61d1df0b
ID_PATH=pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0
ID_PATH_TAG=pci-0000_00_13_2-usb-0_2_1_0-scsi-0_0_0_0
ID_REVISION=7.76
ID_SERIAL=Generic_USB_Flash_Disk-0:0
ID_TYPE=disk
ID_USB_DRIVER=usb-storage
ID_USB_INTERFACES=:080650:
ID_USB_INTERFACE_NUM=00
ID_VENDOR=Generic
ID_VENDOR_ENC='Generic\x20'
ID_VENDOR_ID=058f
MAJOR=8
MINOR=160
SUBSYSTEM=block

Script that detect usb when it is inserted and copy files from usb to computer

I posted before a vbscript here to do what you want just take a look and try it !

Vbscript to copy files with specific extension from usb when plugged in

Edit on 19/07/2016 @10:42 :

I improved this vbsript to run as admin, and to let executing just one insctance of this script.

AutoSave_USB_SDCARD.vbs to copy into My Documents folder

Option Explicit
' Run as Admin
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
' To let executing just one insctance of this script
If AppPrevInstance() Then
MsgBox "There is an existing proceeding !" & VbCrLF &_
CommandLineLike(WScript.ScriptName),VbExclamation,"There is an existing proceeding !"
WScript.Quit
Else
Do
Call AutoSave_USB_SDCARD()
Pause(30)
Loop
End If
'**************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE "_
& CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'**************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'*************************AutoSave_USB_SDCARD()****************************
Sub AutoSave_USB_SDCARD()
Dim Ws,WshNetwork,NomMachine,MyDoc,strComputer,objWMIService,objDisk,colDisks
Dim fso,Drive,NumSerie,volume,cible,Amovible,Dossier,chemin,Command,Result
Set Ws = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
NomMachine = WshNetwork.ComputerName
MyDoc = Ws.SpecialFolders("Mydocuments")
cible = MyDoc & "\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk")

For Each objDisk in colDisks
If objDisk.DriveType = 2 Then
Set fso = CreateObject("Scripting.FileSystemObject")
For Each Drive In fso.Drives
If Drive.IsReady Then
If Drive.DriveType = 1 Then
NumSerie=fso.Drives(Drive + "\").SerialNumber
Amovible=fso.Drives(Drive + "\")
Numserie=ABS(INT(Numserie))
volume=fso.Drives(Drive + "\").VolumeName
Dossier=NomMachine & "_" & volume &"_"& NumSerie
chemin=cible & Dossier
Command = "cmd /c Xcopy.exe " & Amovible &" "& chemin &" /I /D /Y /S /J /C"
Result = Ws.Run(Command,0,True)
end if
End If
Next
End If
Next
End Sub
'**************************End of AutoSave_USB_SDCARD()*******************
Sub Pause(Sec)
Wscript.Sleep(Sec*1000)
End Sub
'************************************************************************

Kernel Module which opens a script when inserting an USB-Stick

Consider adding a Udev rule. Writing a kernel module is not good option as its not a good idea to run scripts in Kernel mode, Kernel mode is not intended to do that.

There is an answered question How to do I detect USB drive

How to insert my driver automatically on the insertion of USB mouse in Linux System?

Thanks all for your help.

I follow the udev approach to load module automatically on the USB insertion

Below is the procedure to load your Driver automatically on the Insertion of Hot plug-gable device (I experiment with the USB mouse and below procedure is working fine for it)

  1. Run Following command

    cmd > udevadm info -a -p $(udevadm info -q path -n /dev/input/mouse)

    In place of ?? in the above command user need to add the device ID based on its entry in /dev (e.g.for USB flash drive: sdb1 or sda1 etc. based on the device identity)

  2. Get the Value of the below parameters from the output of above command
    KERNEL, ATTRS{idVendor}, ATTRS{idProduct}, ATTRS{serial}

  3. Go to /etc/dev/rule.d directory and Add your rule

    cmd > sudo vim 40-usbmouse.rules
    ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd?1", ATTRS{idVendor}=="058f", ATTRS{idProduct}=="6387", ATTRS{serial} =="4EPLXAXE", SYMLINK+="usbpd", RUN+="/usr/local/bin/InsertModule.sh"

    Save this file.
    Above rule is defined for the USB Mouse.
    Parameter SYMLINK creates a link of your device in the /dev directory and In RUN+ you can give your script location which is going to execute on your device insertion.

    For more info on How to write a rule refer below link

    http://hackaday.com/2009/09/18/how-to-write-udev-rules/

  4. Now after you define your rule user need to restart the udev to take your rule in notice by kernel.
    cmd > sudo stop udev

    cmd > sudo start udev

  5. Insert your USB and validate that your script which you define in your rule shows its effact.
    For Mouse user can use below command

    cmd > udevadm info -a -p $(udevadm info -q path -n /dev/input/mouse)

P.S.: cmd stands for the command shell (Terminal).The above procedure is working with any USB device.



Related Topics



Leave a reply



Submit