Page 1 of 2

USB Device Shut Down\Dispositivo USB Apagar

Posted: Mon Nov 02, 2015 12:05 pm
by vagblad
Hello all,

I wonder if anyone knows if it is possible to control through our programs the on/off state of a USB device. More specific i am talking about an external USB HDD.
For example to help you understand more easily what i want to do:
I schedule a task for a backup operation from my C: drive to my external Z: usb drive.
When the task is done i would like to disconnect the external drive so no one could have access to it. And on the next day i would have to unplug and plug again the HDD to have access.

Thanks a lot in advance

Best Regards

Google translate
----------------------------------------------------------------------
Hola a todos,

Me pregunto si alguien sabe si es posible controlar a través de nuestros programas el estado de encendido / apagado de un dispositivo USB . Más específico que estoy hablando de un disco duro USB externo .
Por ejemplo, para ayudar a entender más fácilmente lo que quiero hacer :
Puedo programar una tarea para una operación de copia de seguridad de mi unidad C: a mi Z externa : unidad USB .
Cuando se lleva a cabo la tarea que me gustaría desconectar la unidad externa para que nadie pueda tener acceso a ella. Y al día siguiente yo tendría que desconectar y conectar de nuevo el disco duro para tener acceso .

Muchas gracias desde ya

Atentamente

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Mon Nov 02, 2015 1:03 pm
by mol
Is it your way to avoid ransomware problems?

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Mon Nov 02, 2015 1:10 pm
by vagblad
mol wrote:Is it your way to avoid ransomware problems?
Yes definitely one more way to protect myself :)

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Mon Nov 02, 2015 3:56 pm
by andyglezl
Hola
en teoria se puede hacer manualmente, habria que buscar la forma
de hacerlo automaticamente.
--------------------------------------------------------------------------------
Hello
in theory it can be done manually, would have to find a way
to do so automatically.
DeshabUSB.jpg
DeshabUSB.jpg (258.21 KiB) Viewed 6522 times
desconectar la unidad externa para que nadie pueda tener acceso a ella
Tienes la unidad compartida ?, sino es cuestion de permisos.
---------------------------------------------------------------------------
You have the shared drive?, But it is a matter of permissions.


ó con el administrador de dispositivos...
------------------------------------------------
or the device manager ...
DeshabUSB2.jpg
DeshabUSB2.jpg (135.49 KiB) Viewed 6519 times

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Tue Nov 03, 2015 9:37 am
by Clip2Mania
You can do this on the command line via Devcon.exe, a utility which is part of the Windows Development Kit.. This is the command-line equivalent of Windows Device Manager.

First, query all USB DeviceID's:

Code: Select all

devcon findall =usb
Pick the corrrect one and you can "eject" it via the command

Code: Select all

devcon remove "USB\VID_9999&PID_9999"
You can use wildcards in the above DeviceID's.

You can also use an alternative of Devcon, such asRemoveDrive

Hope this helps a bit.

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Tue Nov 03, 2015 10:17 am
by Rathinagiri
I am sure we have to call this Win32 API function CM_Request_Device_EjectW()

Probably Claudio can help.

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Tue Nov 03, 2015 11:12 am
by vagblad
@Andy
Thanks Andy. Yeah it can be done manually, i am just trying to automate the whole process as much as possible, so that there is as less human involment as it can be to avoid errors like(forgot to take backup etc..).

Gracias Andy . Sí que se puede hacer manualmente , estoy tratando de automatizar todo el proceso tanto como sea posible , de modo que no es tan involment menos humano , ya que puede ser para evitar errores similares ( se olvidó de tener copia de seguridad , etc .. ) .
--------------------------------------------------------------------------------------------------------------------------------
Clip2Mania wrote:You can do this on the command line via Devcon.exe, a utility which is part of the Windows Development Kit.. This is the command-line equivalent of Windows Device Manager.

You can also use an alternative of Devcon, such asRemoveDrive

Hope this helps a bit.
Yes Devcon seems a great solution, i tried it yesterday but unfortunately i didn't manage to get it to work so far.
I get the message that the device is disabled but i can still access it through windows explorer.
I will do some more tries today and i will try RemoveDrive also.
Thanks a lot for the help!

Sí Devcon parece una gran solución , lo intenté ayer, pero por desgracia no me las arreglo para conseguir que funcione hasta el momento.
Me sale el mensaje de que el dispositivo está deshabilitado , pero yo todavía puedo acceder a ella a través de Windows Explorer .
Voy a hacer algunas más tries hoy y voy a tratar RemoveDrive también .
¡Muchas gracias por la ayuda!
--------------------------------------------------------------------------------------------------------------------------------
@Rathi

Yeah Rathi that seems to be the one.

Sí Rathi que parece ser la única.

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Tue Nov 03, 2015 3:48 pm
by PeteWG
Hi,

try the code below to see if it serves your purpose:

Code: Select all

// test program
request hb_gt_win_default
PROC MAIN( cDriveLetter )

	hb_Default( @cDriveLetter, "G:" )

	IF EjectRemovable( cDriveLetter )
		? "The drive " + cDriveLetter + " can be safely removed."
	ELSE
		? "Failed to safely remove/eject drive " + cDriveLetter
	ENDIF
	WAIT
	RETURN
// end test program

***************************************************************
#pragma begindump

#include <windows.h>
#include <winioctl.h>
#include <tchar.h>
#include <stdio.h>

// Prototypes
BOOL EjectVolume(TCHAR cDriveLetter);
HANDLE OpenVolume(TCHAR cDriveLetter);
BOOL LockVolume(HANDLE hVolume);
BOOL DismountVolume(HANDLE hVolume);
BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPrevent);
BOOL AutoEjectVolume(HANDLE hVolume);
BOOL CloseVolume(HANDLE hVolume);

LPTSTR szVolumeFormat = TEXT("\\\\.\\%c:");
LPTSTR szRootFormat = TEXT("%c:\\");

HANDLE OpenVolume(TCHAR cDriveLetter)
{
	HANDLE hVolume;
	UINT uDriveType;
	TCHAR szVolumeName[8];
	TCHAR szRootName[5];
	DWORD dwAccessFlags;

	wsprintf(szRootName, szRootFormat, cDriveLetter);
	uDriveType = GetDriveType(szRootName);

	switch(uDriveType) 
	{
	case DRIVE_REMOVABLE:
	  dwAccessFlags = GENERIC_READ | GENERIC_WRITE;
	  break;
	case DRIVE_CDROM:
	  dwAccessFlags = GENERIC_READ;
	  break;
	default:
	  return INVALID_HANDLE_VALUE;
	}

	wsprintf(szVolumeName, szVolumeFormat, cDriveLetter);

	hVolume = CreateFile(   szVolumeName,
								 dwAccessFlags,
								 FILE_SHARE_READ | FILE_SHARE_WRITE,
								 NULL,
								 OPEN_EXISTING,
								 0,
								 NULL );
	return hVolume;
}

BOOL CloseVolume(HANDLE hVolume)
{
	return CloseHandle(hVolume);
}

#define LOCK_TIMEOUT        10000       // 10 Seconds
#define LOCK_RETRIES        20

BOOL LockVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	DWORD dwSleepAmount;
	int nTryCount;

	dwSleepAmount = LOCK_TIMEOUT / LOCK_RETRIES;

	for( nTryCount = 0; nTryCount < LOCK_RETRIES; nTryCount++ ) 
	{
	  if( DeviceIoControl( hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0,
								  &dwBytesReturned, NULL ) )
			return TRUE;

	  Sleep( dwSleepAmount );
	}

	return FALSE;
}

BOOL DismountVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	return DeviceIoControl( hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0,
								   &dwBytesReturned, NULL );
}

BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPreventRemoval)
{
	DWORD dwBytesReturned;
	PREVENT_MEDIA_REMOVAL PMRBuffer;
	PMRBuffer.PreventMediaRemoval = fPreventRemoval;
	return DeviceIoControl( hVolume, IOCTL_STORAGE_MEDIA_REMOVAL,
								   &PMRBuffer, sizeof(PREVENT_MEDIA_REMOVAL),
								   NULL, 0, &dwBytesReturned, NULL );
}

AutoEjectVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	return DeviceIoControl( hVolume, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0,
								 &dwBytesReturned,
								 NULL );
}

BOOL EjectVolume( TCHAR cDriveLetter )
{
	HANDLE hVolume;

	BOOL fRemoveSafely = FALSE;
	BOOL fAutoEject = FALSE;

	hVolume = OpenVolume(cDriveLetter);
	if( hVolume == INVALID_HANDLE_VALUE )
	  return FALSE;

	if( LockVolume(hVolume) && DismountVolume(hVolume) )
	{
	  fRemoveSafely = TRUE;

	  if (PreventRemovalOfVolume(hVolume, FALSE) && AutoEjectVolume(hVolume))
			fAutoEject = TRUE;
	}

	if( ! CloseVolume(hVolume) )
	  return FALSE;

	return TRUE;
}

#include "hbapi.h"
#include "hbapifs.h"
HB_FUNC( EJECTREMOVABLE )
{ 
	char * szDrive = hb_parc( 1 );
	hb_retl( EjectVolume( *szDrive ) ); 
	return;
}

#pragma enddump

regards,
Pete

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Tue Nov 03, 2015 10:12 pm
by danielmaximiliano
Soluciones perfectas, gracias por compa

Re: USB Device Shut Down\Dispositivo USB Apagar

Posted: Wed Nov 04, 2015 12:37 am
by quartz565
Hi Pete, this works perfectly !
Τhank you !