Is there a program or a script for Windows (powershell maybe, or cmd) that can detect when a USB drive is plugged in and copy its contents in the hard drive of the PC?
It should be able to act autonomously without asking permission or opening confirmation or status windows.
I need it to create a backup of the drive every time that I connect it to the machine.
This vbscript is used to automatically copy each and every newly inserted USB key or sdcard.
For each USB key or every sdcard, it creates a folder of this form "MachineName_VolumeUSB_NumSerie" in the% AppData% folder and it makes a total copy for the first time and then incrementally, ie, it just copy the new files and files changed every 30 seconds.
'Sauvegarde automatique des clés USB et SDCARD dés leurs insertion.
'Ce Programme sert à copier automatiquement chaque clé USB nouvellement insérée ou bien une SDCard.
'Il sert à faire des Sauvegardes incrémentielles de vos clés USB.
'Pour chaque clé USB, il crée un dossier de cette forme "NomMachine_NomVolumeUSB_NumSerie" dans le dossier %AppData% et
'il fait une copie totale pour la première fois, puis incrémentielle , càd ,il copie juste les nouveaux fichiers et les fichiers modifiés.
'Crée le 23/09/2014 © Hackoo
Option Explicit
Do
Call AutoSave_USB_SDCARD()
Pause(30)
Loop
'********************************************AutoSave_USB_SDCARD()************************************************
Sub AutoSave_USB_SDCARD()
Dim Ws,WshNetwork,NomMachine,AppData,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
AppData= ws.ExpandEnvironmentStrings("%AppData%")
cible = AppData & "\"
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
'***************************************Fin du AutoSave_USB_SDCARD()*********************************************
'****************************************************************************************************************
Sub Pause(Sec)
Wscript.Sleep(Sec*1000)
End Sub
'****************************************************************************************************************
step 1: get yourself an usb drive.
step 2: download a list of tools. for more results. download every single tool from: http://www.nirsoft.net/utils/index.html#password_utils
step 2: create an batch file containing line's start filename /stext filename.txt
example: start mspass.exe /stext mspass.txt
for each program.
step3: test your "program" by plug the usb drive into a device. and click on the batch file you created.
"happy password recovering"
EDIT:
i found this on the internet too explaining very easily what I just wrote above + more
http://lifehacker.com/create-a-usb-password-stealer-to-see-how-secure-your-i-1650354166
Related
I am trying to create a script that will use the copy con to write a file
Set objNetwork = CreateObject("Wscript.Network")
CurrentUser = objNetwork.UserName
Set Wshell = CreateObject("WScript.Shell")
Wshell.Run "%COMSPEC% cd C:\Users\" & CurrentUser & _
"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup & copy con master.vbs & x = 1 & x=2^Z", 0, True
The problem here is that while using ^Z does simulate the output of Crtl+Z, CMD doesn't treat them the same.
As you can see, I wanted the console window to be hidden, so using something like SendKeys won't work here.
Any suggestions?
I am writing a piece of VBScript in which I want to Save a file (say, notepad) into my USB Stick.
To do so, I am using AppActive and SendKeys "^s" which will pop up a window asking for the path.
The problem is I don't know what letter will my USB have on certain computers. On mine, it's E, but on my friend's PC it is G (anyway, irrelevant). Is there a way to say the path without including the letter?
I named my usb "USB" and simply tried to write the path without the letter. It works for my computer, but it doesn't work on any other PCs. Any suggestions?
PS: I'm working on Windows (if the OS is needed)
As for my research, I got this link, which is closest to my need, but not what I want.
Getting USB Device path from USB port
UPDATE: Noodles' code was really good if you want to find the drive letter when you don't know it
UPDATE 2: I also found this
http://www.howtogeek.com/96298/assign-a-static-drive-letter-to-a-usb-drive-in-windows-7/
So I can basically assign a random letter for my USB (say, Z) and simply use this as drive letter (hope it also works on windows 10)
This code monitors volume changes and if it's a USB then copies the files to c:\test. Your interest is the Win32_Volume code.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
Wscript.Echo objitem.DriveType
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Wscript.Echo "Starting Copying"
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(objitem.driveletter)
Set DestFldr=objShell.NameSpace("c:\test\")
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Wscript.Echo "Finished Copying"
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop
You can't write to any storage device without knowing its assigned drive letter. You likely would want to instead open a file dialog allowing the user to choose the appropriate USB driver or other storage drive and then use the path selected.
See "How to open a file dialog in VBS".
I need to develop a script which compares the size of a folder from its previous size which is saved in text file. If the folder size has increased it should prompt folder size increased.
Monitoring directory with VBScript
Option Explicit
Dim fso,Message,Message2,Msg,intInterval,strDrive,strFolder,strComputer,objWMIService,strQuery
Dim colEvents,objEvent,objTargetInst,objPrevInst,objProperty,ws,LOG_FILE_PATH,LogFile,Chemin,MonTableau
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("WScript.Shell")
strComputer = "."
Chemin = Parcourir_Dossier()
MonTableau = Split(Chemin,"\")
LogFile = MonTableau(UBound(MonTableau)) & ".log"
LOG_FILE_Path = ws.ExpandEnvironmentStrings("%AppData%") & "\" & LogFile
intInterval = "2"
'****************************************************************************************************
Function Parcourir_Dossier()
Dim ws,objFolder,Copyright
Copyright = "[ © Hackoo © 2014 ]"
Set ws = CreateObject("Shell.Application")
Set objFolder = ws.BrowseForFolder(0,"Choose the folder to watch for "_
& Copyright,1,"c:\Programs")
If objFolder Is Nothing Then
Wscript.Quit
End If
Parcourir_Dossier = objFolder.self.path
end Function
'****************************************************************************************************
Chemin = Split(fso.GetAbsolutePathName(Chemin),":")
strDrive = Chemin(0) & ":"
strFolder = Replace(Chemin(1), "\", "\\")
If Right(strFolder, 2) <> "\\" Then strFolder = strFolder & "\\"
'Connexion au WMI
Set objWMIService = GetObject( "winmgmts:" &_
"{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\cimv2" )
'La chaîne de la requête
strQuery = _
"Select * From __InstanceOperationEvent" _
& " Within " & intInterval _
& " Where Targetinstance Isa 'CIM_DataFile'" _
& " And TargetInstance.Drive='" & strDrive & "'"_
& " And TargetInstance.path='" & strFolder & "'"
'Exécutez la requête
Set colEvents = _
objWMIService.ExecNotificationQuery(strQuery)
Do
Set objEvent = colEvents.NextEvent()
Set objTargetInst = objEvent.TargetInstance
Select Case objEvent.path_.Class
'Si c'est le cas de la création de fichier ou d'un événement de suppression et afficher
'juste le nom du fichier
Case "__InstanceCreationEvent"
Message = DblQuote(objTargetInst.Name) & " is created !"
Message2 = String(10,"*") & Now & String(10,"*") & vbCrLf & Message & vbCrLf & String(70,"*")
Call Log(LOG_FILE_Path,Message2)
MsgBox Message,VbInformation,Message
Case "__InstanceDeletionEvent"
Message = DblQuote(objTargetInst.Name) & " is deleted !"
Message2 = String(10,"*") & Now & String(10,"*") & vbCrLf & Message & vbCrLf & String(70,"*")
Call Log(LOG_FILE_Path,Message2)
MsgBox Message,VbInformation,Message
'Si c'est le cas de la modification du fichier,comparer les valeurs de propriété de la cible et de l'instance précédente
'et afficher les propriétés qui ont été changé comme la taille et LastModified
Case "__InstanceModificationEvent"
Set objPrevInst = objEvent.PreviousInstance
For Each objProperty In objTargetInst.Properties_
If objProperty.Value <> _
objPrevInst.Properties_(objProperty.Name) Then
Message = "modified file : " & vbCrLf &_
objTargetInst.Name & vbCrLf &_
"Property : "_
& objProperty.Name & vbCrLf &_
"Last Value : "_
& objPrevInst.Properties_(objProperty.Name) & vbCrLf &_
"New value : " _
& objProperty.Value
Message2 = String(10,"*") & Now & String(10,"*") & vbCrLf & Message & vbCrLf & String(70,"*")
Call Log(LOG_FILE_Path,Message2)
MsgBox Message,64,DblQuote(objTargetInst.Name)
End If
Next
End Select
Loop
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub Log(strLogFileChemin,strLogContent)
Const APPEND = 8
Dim objFso,objLogFile
Set objFso = CreateObject("Scripting.FileSystemObject")
If Not objFso.FileExists(strLogFileChemin) Then objFso.CreateTextFile(strLogFileChemin, True).Close
Set objLogFile = objFso.OpenTextFile(strLogFileChemin,APPEND)
objLogFile.WriteLine strLogContent
objLogFile.Close
End Sub
'**********************************************************************************************
Try like this :
Folder = "c:\your\path\tata"
File = "c:\your\file\containing\the\value.txt"
set objFSO = CreateObject("Scripting.FileSystemObject")
set fileRead = objfso.OpenTextFile(file, 1)
content = fileRead.Readline
FileRead.close
set objFolder = objFSO.GetFolder(Folder)
if objFolder.Size > Clng(content) Then Wscript.Echo "The Folder size [" & ObjFolder.size & "] is bigger then [" & content & "]"
If you need to update the value in your text file.
Folder = "c:\your\path\tata"
File = "c:\your\file\containing\the\value.txt"
set objFSO = CreateObject("Scripting.FileSystemObject")
set fileRead = objfso.OpenTextFile(file, 1)
content = fileRead.Readline
FileRead.close
set objFolder = objFSO.GetFolder(Folder)
set fileWrite = objfso.OpenTextFile(file, 2)
FileWrite.writeline(ObjFolder.size)
FileWrite.close
if objFolder.Size > Clng(content) Then Wscript.Echo "The Folder size [" & ObjFolder.size & "] is bigger then [" & content & "]"
I am very good using GNU/Linux, however on Windows I suck.
Making a dump of the local DB with mysqldump, compress the result, give it an incremental name and make it a cron task it's a very easy task for me.
But on Windows, I don't have a clue. I want to make a .bat script, or a windows script, with the task tool. Compress the result and give it a name wit the date in the PC. I using Wamp as server and I can't use GNU/Linux because my boss don't want it.
Google don't give me any good answer.
How can I do a good automated task for baking up with my desire characteristics on Windows 7 with Wamp?
Here is what i do.
I first run mysqldump to get .sql file using current date.
Next i run this script to compress it and move it into another folder. You can combine these two steps but i am posting here as a separate script to illustrate:
#echo off
set sourceDir=C:\mysql\mysqldump
set targetDir="C:\Users\Admin\Google Drive\mysql-backup"
#echo on
7z a %targetDir%\backup-%date:~-7,2%.7z %sourceDir%\backup-%date:~-7,2%.sql
#echo off
Be sure to have 7z program installed on your Windows computer.
At the end I do it myself in VBS:
Rem Plan de trabajo:
Rem 1. Dumpear la base de datos en un archivo.
Rem 2. Renombrar el archivo a uno con la fecha del dia en el nombre.
Rem 3. Comprimir el archivo con Compact
Rem 4. Borrar el archivo no comprimido.
Rem 5. Mover el archivo comprimido a la carpeta c:\Users\jvalenzuela\Documents\backups
Rem Lo que hace el script
Rem Le decimos que es un shell
Dim WshShell, oExec
Set WshShell = WScript.CreateObject("WScript.Shell")
Rem Agarramos la fecha
CurrentDate = Date
Rem Le damos formato a la fecha
Fecha = FormatDateTime(CurrentDate, vbShortDate)
Rem le decimos cual es el directorio de backup
BackupDir = "C:\Users\jvalenzuela\Documents\backups"
Rem Le damos la ubicación de mysqldump
MySQLDump = "C:\wamp\bin\mysql\mysql5.6.12\bin\mysqldump.exe"
Rem formateamos el nombre del respaldo
NombreDump = BackupDir & "\backup." & Fecha & ".sql"
Rem y le damos argumentos
MySqlDumpArguments = "-uroot --result-file=""" & NombreDump & """ --all-databases"
Rem Armamos el comando
comandoFinal = MySqlDump & " " & MySqlDumpArguments
Rem Y lo ejecutamos
set oExec = WshShell.Exec(comandoFinal)
Rem vemos si resultó el respaldo
if oExec.Status = 0 Then
WshShell.Run "compact /c " & NombreDump
Rem y si no resultó, lo registramos como error en el visosr de sucesos
Else
WshShell.LogEvent 1, "No se relizó el respaldo de base de datos del día"
End If
Rem este script no tiene poderes de super vaca
And add it to the tasks scheduler. Have fun!
That's my first time posting on stackoverflow. I've been finding usefull answers on this site but this time, I can't find no help with this problem.
General context
I wrote a VBScript Toolkit script (S:\Universe_bo\prod\batch\BO\libs\PXI_Toolkit.vbs) included in scripts (S:\Universe_bo\prod\batch\BO*.wsf) that are executed by a scheduler software.
The system is a Windows Server 2003 server (this server is part of an active-passive Windows cluster and the S: drive is a resource of this cluster). The Windows user running the scripts has permission to write in the directory and is an Administrator.
In the scripts, I open a new file and write some text in it (it is the content of an e-mail).
The problem
Here is what happens (today, it crashed 7 out of 10 times):
(---) [24/03/2012 10:34:23] Ouverture du fichier [S:\universe_bo\prod\data\email_rad98038.tmp]
S:\universe_bo\prod\batch\BO\BOLANC_BOAPP500_TOP100.wsf(2451, 8) Erreur d'exécution Microsoft VBScript: Permission refusée
It means "Runtime error Microsoft VBScript: Permission denied".
The line 2451 from the script is the following:
Set objFichier = fso.OpenTextFile(_
pvstrNomFichierCorpsEmail, _
ForWriting, _
True)
We have been using them for two years without a problem on the test server (not a cluster) but now that it finally passed production, it doesn't work all the time.
I have no idea what the problem could be, I'm all ears and will take any suggestion.
Thanks in advance.
Guillaume
Source scripts
.wsf script
The .wsf scripts look like this:
(I removed the irrelevant parts, and comments are in French since we are)
'===============================================================================
' BOLANC_BOAPP500_TOP100.wsf (script)
'===============================================================================
<job><?job debug="true"?>
<script language="VBScript" src="libs/PXI_Toolkit.vbs"/>
<script language="VBScript">
Dim codeRetour ' Le code retour du script
codeRetour = 0 ' est initialisé à 0 (tout va bien)
' [...]
' Irrelevant stuff
' [...]
' Exécuter le rapport
codeRetour = rapport.Executer
LibererRessources
Wscript.Quit codeRetour
</script>
</job>
Toolkit script
And here are the involved parts of the PXI_Toolkit.vbs script:
Option Explicit
'===============================================================================
' PXI_Toolkit.vbs (script)
'===============================================================================
'*******************************************************************************
' fso (objet)
' Scripting.FileSystemObject
'*******************************************************************************
dim fso
set fso = CreateObject("Scripting.FileSystemObject")
'*******************************************************************************
' Constantes pour l'ouverture des fichiers
'*******************************************************************************
Private Const ForReading = 1 ' Ouvre un fichier en lecture seule.
Private Const ForWriting = 2 ' Ouvre un fichier en écriture.
Private Const ForAppending = 8 ' Ouvre un fichier et permet l'écriture à la fin
' du fichier.
'*******************************************************************************
' WshShell (objet)
' Objet Permettant d'accéder aux fonctionnalités systèmes Windows.
'*******************************************************************************
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
'*******************************************************************************
' WshSysEnv (tableau de chaînes)
' Tableau contenant les variables d'environnements. WshSysEnv est indexé
' par le nom des variables qu'il contient.
' Exemple : Ecrire "Utilisateur="& WshSysEnv("USERNAME")
'*******************************************************************************
Dim WshSysEnv
Set WshSysEnv = WshShell.Environment("Process")
' Lots of stuff
'*******************************************************************************
' EcrireErr (procédure)
' Affiche un message d'erreur.
'
' Paramètres :
' - pstrMessage (chaîne)
' Message d'erreur à afficher.
'*******************************************************************************
Sub EcrireErr(pstrMessage)
WScript.stdErr.WriteLine "(!!!) ["& Now &"] "& Cstr(pstrMessage)
End Sub ' EcrireErr
'*******************************************************************************
' EcrireLog (procédure)
' Journalise un message dans les logs.
'
' Paramètres :
' - pstrChaine (chaîne)
' Texte à journaliser.
'*******************************************************************************
Sub EcrireLog(pstrChaine)
Ecrire "(---) ["& Now &"] "& Cstr(pstrChaine)
End Sub ' EcrireLog
'*******************************************************************************
' LibererRessources (procédure)
' Libère les ressources potentiellement ouvertes au cours de l'exécution
' des fonctions de ce script.
'
' Paramètres : Aucun
'*******************************************************************************
Sub LibererRessources()
EcrireLog "LibererRessources"
' Libérer les variables système
Set WshArguments = Nothing
Set WshSysEnv = Nothing
Set WshShell = Nothing
Set fso = Nothing
End Sub ' LibererRessources
Class ClsRapportBO
Private pvarrstrMessageEmail pvstrNomFichierCorpsEmail
Public Function Executer()
' Ecriture du fichier contenant le corps du mail
If Not IsEmpty(pvarrstrMessageEmail) Then
Dim objFichier, strLigne
EcrireLog "Ouverture du fichier ["& pvstrNomFichierCorpsEmail &"]"
Set objFichier = fso.OpenTextFile(_
pvstrNomFichierCorpsEmail, _
ForWriting, _
True)
' Ecriture de l'en-tête du message
objFichier.WriteLine "Bonjour"
objFichier.WriteLine
' Lecture des éléments du tableau construire le fichier
For Each strLigne In pvarrstrMessageEmail
objFichier.WriteLine strLigne
Next
' Ecriture du pied de page
objFichier.WriteLine
objFichier.WriteLine "NB : Ce message est envoyé automatiquement. "&_
"Merci de ne pas y répondre."
objFichier.Close
End If
' More stuff
If Not IsEmpty(pvarrstrMessageEmail) And fso.FileExists(pvstrNomFichierCorpsEmail) Then
EcrireLog "Suppression du fichier ["& pvstrNomFichierCorpsEmail &"]"
fso.DeleteFile(pvstrNomFichierCorpsEmail)
End If
End Function ' Executer
End Class ' ClsRapportBO
Function CreerRapportBO(pstrChemin, parrstrInvites, pstrToken)
Dim objRapport
Set objRapport = new ClsRapportBO
' ...
Set CreerRapportBO = objRapport
End Function ' CreerRapportBO
' Tests de la boîte à outils
Sub TestsUnitaires()
' Unit tests...
End Sub ' TestsUnitaires
Is "S:\universe_bo\prod\data\email_rad98038.tmp" a file created by the script, or a file created by another process? A likely cause of this problem is that the file is in use. You can wrap the statement with:
On Error Resume Next
Set objFichier = fso.OpenTextFile(_
pvstrNomFichierCorpsEmail, _
ForWriting, _
True)
On Error GoTo 0
If Not IsObject(objFichier) Then
...
More Logic Here
...
End If