elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  Programa que detecte cuando se introduce una unidad extraible
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Programa que detecte cuando se introduce una unidad extraible  (Leído 3,792 veces)
binario (grey hat lammer)

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Programa que detecte cuando se introduce una unidad extraible
« en: 6 Agosto 2017, 02:09 am »

Hola gente de el foro  :D.
quería preguntarles si existe alguna forma de hacer un programa en VBS o batch que detecte cuando se conecta una usb o disco a la computadora, tenia una idea muy básica pero no es la más efectiva :

Código
  1. @echo off
  2. :1
  3. if exist (cualquier letra):\ goto 2 else goto 3
  4.  
  5. :2
  6.  
  7. :3
  8. (el codigo que ocupes)




· Los códigos deben ir en etiquetas GeSHi
· Los temas van un su respectivo subforo
>aquí las reglas del foro
-Engel Lex


« Última modificación: 6 Agosto 2017, 02:17 am por engel lex » En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Programa que detecte cuando se introduce una unidad extraible
« Respuesta #1 en: 6 Agosto 2017, 02:16 am »

intentaste buscarlo en google?


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Programa que detecte cuando se introduce una unidad extraible
« Respuesta #2 en: 6 Agosto 2017, 12:13 pm »

Aquí tienes un ejemplo en Batch:

...Pero no vale la pena hacerlo en Batch ni tampoco en VBS. Si tu idea es no tener que depender de...herramientas externas, entonces existe otro lenguaje con soporte "nativo" en Windows llamado PowerShell, es el futuro en el scripting de Windows, además de poder utilizar la librería de clases de .NET Framework y compilar código/clases en VB.NET y C# que luego podremos utilizar desde el propio script.

Un ejemplo aleatorio de los resultados de Google de un script en PowerShell que realiza consultas directamente a las clases de WMI:

Y por último aquí te dejo otro ejemplo algo más avanzado que puedes adaptar a tus necesidades, en el que utilizo PowerShell para compilar un monitor de inserción y extracción de dispositivos que desarrollé en VB.NET:

USBMon.ps1
Código
  1. $vbCode = @'
  2. ' ***********************************************************************
  3. ' Author   : Elektro
  4. ' Modified : 16-December-2016
  5. ' ***********************************************************************
  6.  
  7. Imports Microsoft.VisualBasic
  8. Imports System
  9. Imports System.Collections
  10. Imports System.Collections.Generic
  11. Imports System.ComponentModel
  12. Imports System.Diagnostics
  13. Imports System.IO
  14. Imports System.Reflection
  15. Imports System.Runtime.InteropServices
  16. Imports System.Security
  17. Imports System.Text
  18. Imports System.Threading
  19. Imports System.Windows.Forms
  20.  
  21. Namespace VBNamespace
  22.  
  23. #Region " Drive Watcher "
  24.  
  25. ''' <summary>
  26. ''' A device insertion and removal monitor.
  27. ''' </summary>
  28. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  29.  
  30. #Region " Properties "
  31.  
  32.        ''' <summary>
  33.        ''' Gets the connected drives on this computer.
  34.        ''' </summary>
  35.        Public Overridable ReadOnly Property Drives As IEnumerable(Of DriveInfo)
  36.            <DebuggerStepThrough>
  37.            Get
  38.                Return DriveInfo.GetDrives
  39.            End Get
  40.        End Property
  41.  
  42.        ''' <summary>
  43.        ''' Gets a value that determines whether the monitor is running.
  44.        ''' </summary>
  45.        Public Overridable ReadOnly Property IsRunning As Boolean
  46.            <DebuggerStepThrough>
  47.            Get
  48.                Return Me.isRunningB
  49.            End Get
  50.        End Property
  51.        Protected isRunningB As Boolean
  52.  
  53.        ''' <summary>
  54.        ''' Gets the handle for the <see cref="NativeWindow"/> that owns this <see cref="DriveWatcher"/> instance.
  55.        ''' </summary>
  56.        ''' <value>
  57.        ''' The handle.
  58.        ''' </value>
  59.        Public Overridable Shadows ReadOnly Property Handle As IntPtr
  60.            Get
  61.                Return MyBase.Handle
  62.            End Get
  63.        End Property
  64.  
  65. #End Region
  66.  
  67. #Region " Enumerations "
  68.  
  69.        ''' <summary>
  70.        ''' Specifies a computer device type.
  71.        ''' </summary>
  72.        ''' <remarks>
  73.        ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363246%28v=vs.85%29.aspx"/>
  74.        ''' </remarks>
  75.        Private Enum DeviceType As Integer
  76.  
  77.            ' *****************************************************************************
  78.            '                            WARNING!, NEED TO KNOW...
  79.            '
  80.            '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS API
  81.            ' *****************************************************************************
  82.  
  83.            ''' <summary>
  84.            ''' Logical volume.
  85.            ''' </summary>
  86.            Logical = &H2
  87.  
  88.        End Enum
  89.  
  90. #End Region
  91.  
  92. #Region " Events "
  93.  
  94.        ''' <summary>
  95.        ''' A list of event delegates.
  96.        ''' </summary>
  97.        Private ReadOnly events As EventHandlerList
  98.  
  99.        ''' <summary>
  100.        ''' Occurs when a drive is inserted, removed, or changed.
  101.        ''' </summary>
  102.        Public Event DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)
  103.  
  104. #End Region
  105.  
  106. #Region " Event Invocators "
  107.  
  108.        ''' <summary>
  109.        ''' Raises <see cref="DriveStatusChanged"/> event.
  110.        ''' </summary>
  111.        ''' <param name="e">
  112.        ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
  113.        ''' </param>
  114.        <DebuggerStepThrough>
  115.        Protected Overridable Sub OnDriveStatusChanged(ByVal e As DriveStatusChangedEventArgs)
  116.  
  117.            RaiseEvent DriveStatusChanged(Me, e)
  118.  
  119.        End Sub
  120.  
  121. #End Region
  122.  
  123. #Region " Constructors "
  124.  
  125.        ''' <summary>
  126.        ''' Initializes a new instance of <see cref="DriveWatcher"/> class.
  127.        ''' </summary>
  128.        <DebuggerStepThrough>
  129.        Public Sub New()
  130.            Me.events = New EventHandlerList
  131.        End Sub
  132.  
  133. #End Region
  134.  
  135. #Region " Public Methods "
  136.  
  137.        ''' <summary>
  138.        ''' Starts monitoring.
  139.        ''' </summary>
  140.        <DebuggerStepThrough>
  141.        Public Overridable Sub Start()
  142.  
  143.            If (Me.Handle = IntPtr.Zero) Then
  144.                MyBase.CreateHandle(New CreateParams())
  145.                Me.isRunningB = True
  146.  
  147.            Else
  148.                Throw New Exception(message:="Monitor is already running.")
  149.  
  150.            End If
  151.  
  152.        End Sub
  153.  
  154.        ''' <summary>
  155.        ''' Stops monitoring.
  156.        ''' </summary>
  157.        <DebuggerStepThrough>
  158.        Public Overridable Sub [Stop]()
  159.  
  160.            If (Me.Handle <> IntPtr.Zero) Then
  161.                Me.isRunningB = False
  162.                MyBase.DestroyHandle()
  163.  
  164.            Else
  165.                Throw New Exception(message:="Monitor is already stopped.")
  166.  
  167.            End If
  168.  
  169.        End Sub
  170.  
  171. #End Region
  172.  
  173. #Region " Private Methods "
  174.  
  175.        ''' <summary>
  176.        ''' Gets the drive letter stored in a <see cref="DevBroadcastVolume"/> structure.
  177.        ''' </summary>
  178.        ''' <param name="device">
  179.        ''' The <see cref="DevBroadcastVolume"/> structure containing the device mask.
  180.        ''' </param>
  181.        ''' <returns>
  182.        ''' The drive letter.
  183.        ''' </returns>
  184.        <DebuggerStepThrough>
  185.        Protected Overridable Function GetDriveLetter(ByVal device As DevBroadcastVolume) As Char
  186.  
  187.            Dim driveLetters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
  188.  
  189.            Dim deviceID As New BitArray(BitConverter.GetBytes(device.Mask))
  190.  
  191.            For i As Integer = 0 To deviceID.Length
  192.  
  193.                If deviceID(i) Then
  194.                    Return driveLetters(i)
  195.                End If
  196.  
  197.            Next i
  198.  
  199.            Return Nothing
  200.  
  201.        End Function
  202.  
  203. #End Region
  204.  
  205. #Region " Window Procedure (WndProc) "
  206.  
  207.        ''' <summary>
  208.        ''' Invokes the default window procedure associated with this window to process windows messages.
  209.        ''' </summary>
  210.        <DebuggerStepThrough>
  211.        Protected Overrides Sub WndProc(ByRef m As Message)
  212.  
  213.            Select Case m.Msg
  214.  
  215.                Case DeviceEvents.Change ' The hardware has changed.
  216.  
  217.                    If (m.LParam = IntPtr.Zero) Then
  218.                        Exit Select
  219.                    End If
  220.  
  221.                    ' If it's an storage device then...
  222.                    If Marshal.ReadInt32(m.LParam, 4) = DeviceType.Logical Then
  223.  
  224.                        ' Transform the LParam pointer into the data structure.
  225.                        Dim currentWDrive As DevBroadcastVolume =
  226.                            DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DevBroadcastVolume)), DevBroadcastVolume)
  227.  
  228.                        Dim driveLetter As Char = Me.GetDriveLetter(currentWDrive)
  229.                        Dim deviceEvent As DeviceEvents = DirectCast(m.WParam.ToInt32, DeviceEvents)
  230.                        Dim driveInfo As New DriveInfo(driveLetter)
  231.  
  232.                        Me.OnDriveStatusChanged(New DriveStatusChangedEventArgs(deviceEvent, driveInfo))
  233.  
  234.                    End If
  235.  
  236.            End Select
  237.  
  238.            ' Return Message to base message handler.
  239.            MyBase.WndProc(m)
  240.  
  241.        End Sub
  242.  
  243. #End Region
  244.  
  245. #Region " IDisposable Implementation "
  246.  
  247.        ''' <summary>
  248.        ''' Flag to detect redundant calls when disposing.
  249.        ''' </summary>
  250.        Private isDisposed As Boolean
  251.  
  252.        ''' <summary>
  253.        ''' Releases all the resources used by this instance.
  254.        ''' </summary>
  255.        <DebuggerStepThrough>
  256.        Public Sub Dispose() Implements IDisposable.Dispose
  257.            Me.Dispose(isDisposing:=True)
  258.            GC.SuppressFinalize(obj:=Me)
  259.        End Sub
  260.  
  261.        ''' <summary>
  262.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  263.        ''' Releases unmanaged and, optionally, managed resources.
  264.        ''' </summary>
  265.        <DebuggerStepThrough>
  266.        Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  267.  
  268.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  269.                Me.events.Dispose()
  270.                If Me.isRunningB Then
  271.                    Me.Stop()
  272.                End If
  273.            End If
  274.  
  275.            Me.isDisposed = True
  276.  
  277.        End Sub
  278.  
  279. #End Region
  280.  
  281.    End Class
  282.  
  283. #End Region
  284.  
  285. #Region " DriveStatusChanged EventArgs "
  286.  
  287.    ''' <summary>
  288.    ''' Contains the event-data of a <see cref="DriveWatcher.DriveStatusChanged"/> event.
  289.    ''' </summary>
  290.    Public NotInheritable Class DriveStatusChangedEventArgs : Inherits System.EventArgs
  291.  
  292. #Region " Properties "
  293.  
  294.    ''' <summary>
  295.    ''' Gets the device event that occurred.
  296.    ''' </summary>
  297.    Public ReadOnly Property DeviceEvent As DeviceEvents
  298.        Get
  299.            Return Me.deviceEventB
  300.        End Get
  301.    End Property
  302.    Private ReadOnly deviceEventB As DeviceEvents
  303.  
  304.    ''' <summary>
  305.    ''' Gets the drive info.
  306.    ''' </summary>
  307.    Public ReadOnly Property DriveInfo As DriveInfo
  308.        Get
  309.            Return Me.driveInfoB
  310.        End Get
  311.    End Property
  312.    Private ReadOnly driveInfoB As DriveInfo
  313.  
  314. #End Region
  315.  
  316. #Region " Constructors "
  317.  
  318.    <DebuggerNonUserCode>
  319.    Private Sub New()
  320.    End Sub
  321.  
  322.    ''' <summary>
  323.    ''' Initializes a new instance of the <see cref="DriveStatusChangedEventArgs"/> class.
  324.    ''' </summary>
  325.    <DebuggerStepThrough>
  326.    Public Sub New(ByVal deviceEvent As DeviceEvents, ByVal driveInfo As DriveInfo)
  327.        Me.deviceEventB = deviceEvent
  328.        Me.driveInfoB = driveInfo
  329.    End Sub
  330.  
  331. #End Region
  332.  
  333.    End Class
  334.  
  335. #End Region
  336.  
  337. #Region " Device Events "
  338.  
  339.  
  340. ''' <summary>
  341. ''' Specifies a change to the hardware configuration of a device.
  342. ''' </summary>
  343. ''' <remarks>
  344. ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx"/>
  345. ''' <para></para>
  346. ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx"/>
  347. ''' </remarks>
  348. Public Enum DeviceEvents As Integer
  349.  
  350.        ' *****************************************************************************
  351.        '                            WARNING!, NEED TO KNOW...
  352.        '
  353.        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS API
  354.        ' *****************************************************************************
  355.  
  356.        ''' <summary>
  357.        ''' The current configuration has changed, due to a dock or undock.
  358.        ''' </summary>
  359.        Change = &H219
  360.  
  361.        ''' <summary>
  362.        ''' A device or piece of media has been inserted and becomes available.
  363.        ''' </summary>
  364.        Arrival = &H8000
  365.  
  366.        ''' <summary>
  367.        ''' Request permission to remove a device or piece of media.
  368.        ''' <para></para>
  369.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  370.        ''' However, any application can deny this request and cancel the operation.
  371.        ''' </summary>
  372.        QueryRemove = &H8001
  373.  
  374.        ''' <summary>
  375.        ''' A request to remove a device or piece of media has been canceled.
  376.        ''' </summary>
  377.        QueryRemoveFailed = &H8002
  378.  
  379.        ''' <summary>
  380.        ''' A device or piece of media is being removed and is no longer available for use.
  381.        ''' </summary>
  382.        RemovePending = &H8003
  383.  
  384.        ''' <summary>
  385.        ''' A device or piece of media has been removed.
  386.        ''' </summary>
  387.        RemoveComplete = &H8004
  388.  
  389.    End Enum
  390.  
  391. #End Region
  392.  
  393. #Region " DevBroadcast Volume "
  394.  
  395.    ''' <summary>
  396.    ''' Contains information about a logical volume.
  397.    ''' </summary>
  398.    ''' <remarks>
  399.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx"/>
  400.    ''' </remarks>
  401.    <DebuggerStepThrough>
  402.    <StructLayout(LayoutKind.Sequential)>
  403.    Public Structure DevBroadcastVolume
  404.  
  405.        ''' <summary>
  406.        ''' The size of this structure, in bytes.
  407.        ''' </summary>
  408.        Public Size As UInteger
  409.  
  410.        ''' <summary>
  411.        ''' Set to DBT_DEVTYP_VOLUME (2).
  412.        ''' </summary>
  413.        Public Type As UInteger
  414.  
  415.        ''' <summary>
  416.        ''' Reserved parameter; do not use this.
  417.        ''' </summary>
  418.        Public Reserved As UInteger
  419.  
  420.        ''' <summary>
  421.        ''' The logical unit mask identifying one or more logical units.
  422.        ''' Each bit in the mask corresponds to one logical drive.
  423.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  424.        ''' </summary>
  425.        Public Mask As UInteger
  426.  
  427.        ''' <summary>
  428.        ''' This parameter can be one of the following values:
  429.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  430.        ''' '0x0002': Indicated logical volume is a network volume.
  431.        ''' </summary>
  432.        Public Flags As UShort
  433.  
  434.    End Structure
  435.  
  436. #End Region
  437.  
  438. Public NotInheritable Class VBClass
  439.  
  440.    Friend WithEvents DriveMon As DriveWatcher
  441.    Private waitHandle As ManualResetEvent
  442.  
  443.    Public Sub New()
  444.        Me.DriveMon = New DriveWatcher()
  445.        Me.waitHandle = New ManualResetEvent(initialState:=False)
  446.    End Sub
  447.  
  448.    Public Sub StartMon()
  449.        Me.DriveMon.Start()
  450.        Me.waitHandle.WaitOne()
  451.    End Sub
  452.  
  453.    Public Sub StopMon()
  454.        Me.DriveMon.Stop()
  455.        Me.waitHandle.Set()
  456.    End Sub
  457.  
  458.    ''' <summary>
  459.    ''' Handles the <see cref="DriveWatcher.DriveStatusChanged"/> event of the <see cref="DriveMon"/> instance.
  460.    ''' </summary>
  461.    Private Sub DriveMon_DriveStatusChanged(sender As Object, e As DriveStatusChangedEventArgs) _
  462.    Handles DriveMon.DriveStatusChanged
  463.  
  464.        Select Case e.DeviceEvent
  465.  
  466.            Case DeviceEvents.Arrival
  467.                ' Descartar cualquier dispositivo no extraible.
  468.                If (e.DriveInfo.DriveType <> DriveType.Removable) Then
  469.                    Exit Sub
  470.                End If
  471.                Dim sb As New StringBuilder
  472.                With sb
  473.                    .AppendLine("New drive connected...'")
  474.                    .AppendLine(String.Format("Type......: {0}", e.DriveInfo.DriveType.ToString()))
  475.                    .AppendLine(String.Format("Label.....: {0}", e.DriveInfo.VolumeLabel))
  476.                    .AppendLine(String.Format("Name......: {0}", e.DriveInfo.Name))
  477.                    .AppendLine(String.Format("Root......: {0}", e.DriveInfo.RootDirectory))
  478.                    .AppendLine(String.Format("FileSystem: {0}", e.DriveInfo.DriveFormat))
  479.                    .AppendLine(String.Format("Size......: {0} GB", (e.DriveInfo.TotalSize / (1024 ^ 3)).ToString("n1")))
  480.                    .AppendLine(String.Format("Free space: {0} GB", (e.DriveInfo.AvailableFreeSpace / (1024 ^ 3)).ToString("n1")))
  481.                End With
  482.                Console.WriteLine(sb.ToString())
  483.  
  484.            Case DeviceEvents.RemoveComplete
  485.                Dim sb As New StringBuilder
  486.                With sb
  487.                    .AppendLine("Drive disconnected...'")
  488.                    .AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
  489.                    .AppendLine(String.Format("Root: {0}", e.DriveInfo.RootDirectory))
  490.                End With
  491.                Console.WriteLine(sb.ToString())
  492.  
  493.        End Select
  494.  
  495.    End Sub
  496.  
  497. End Class
  498.  
  499. End Namespace
  500. '@
  501. $vbType = Add-Type -TypeDefinition $vbCode `
  502.                   -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
  503.                   -PassThru `
  504.                   -ReferencedAssemblies "Microsoft.VisualBasic.dll", `
  505.                                         "System.dll", `
  506.                                         "System.Collections.dll", `
  507.                                         "System.ComponentModel.dll", `
  508.                                         "System.IO.dll", `
  509.                                         "System.Reflection.dll", `
  510.                                         "System.Runtime.InteropServices.dll", `
  511.                                         "System.Security.dll", `
  512.                                         "System.Threading.dll", `
  513.                                         "System.Windows.Forms.dll" | where { $_.IsPublic }
  514.  
  515. Write-Host "USB monitoring..."
  516. $instance = (New-Object VBNamespace.VBClass)
  517. $instance.StartMon()
  518. Exit(0)

Resultado de ejecución:
« Última modificación: 6 Agosto 2017, 12:20 pm por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Guardar vista de carpetas de una unidad usb extraible
Windows
hunter18 1 2,063 Último mensaje 29 Octubre 2012, 20:21 pm
por adgellida
Obtener letra de unidad extraible BATCH
Scripting
daniel.r.23 4 8,520 Último mensaje 22 Marzo 2013, 09:43 am
por Eleкtro
API Para desconectar unidad extraible?
Ingeniería Inversa
.:UND3R:. 3 2,762 Último mensaje 31 Mayo 2014, 00:47 am
por tincopasan
Menu contextual detectar unidad extraible
Windows
urlick 6 3,706 Último mensaje 8 Septiembre 2014, 17:04 pm
por urlick
Cambiar una letra de unidad extraible en batch
Scripting
Zzz01Breikoft 3 5,636 Último mensaje 27 Septiembre 2014, 05:25 am
por Eleкtro
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines