Secure use of passwords in batch files?


Recommended Posts

I have a series of batch files that run a robocopy backup to a TrueCrypt container on a remote machine.

1. backups.bat on local machine uses psexec to start backup_share.bat on the remote machine.

2. backup_share.bat mounts the TrueCrypt container and shares folders inside.

3. backups.bat runs robocopy.

4. backups.bat uses psexec to run backups_unmount.bat

5. backups_unmount.bat unmounts the TrueCrypt volume.

All of this requires my username and passwords in the batch files. Is there a more secure way to do this?

backups.bat

@echo off

D:\Programs\PsTools\psexec.exe -h \\DOWNSTAIRS -u username -p password D:\Locked\backups_share.bat

rem Run robocopy...
"D:\Programs\backups (robo).bat"

D:\Programs\PsTools\psexec.exe -h \\DOWNSTAIRS -u username -p password D:\Locked\backups_unmount.bat

PAUSE

backups_share.bat

@echo off

rem Mount True Crypt Volume
D:\TrueCrypt\TrueCrypt.exe /v D:\Locked\backups /l G /p password /q

rem Share folders
Net share share1$=G:\share1 /grant:username,FULL
Net share share2$=G:\share2 /grant:username,FULL

backups_unmount.bat

@echo off

rem Unmount Truecrypt volume
D:\TrueCrypt\TrueCrypt.exe /d /q

I found some info about encrypting passwords with PowerShell.

http://www.vistax64.com/powershell/104344-how-encrypt-paswd-file-used-batch.html

http://powershell.com/cs/media/p/248.aspx

PowerShell looks way more complicated than what I'm doing. I'm not sure how to begin.

There's always a chance someone will decode your complied exe, or sniff it out in memory.

They did this at work with VBS files and passwords inside, and people got the contents from extracting the exe's and using memory viewers.

I forgot to specify that you'd use encryption. Although I think by trying to have all this handled automatically he's biting off more than he can chew.

I just tested this program. The batch file doesn't appear to be visible in plain text, so your password should be "hidden".

http://www.battoexeconverter.com/

Encrypts batch file source to keep your code secret.

Users of your scripts cannot view/change your code after it is encrypted by the compiler. Any actions performed by the script can be kept secret.

If you want to take it a step further, this is a free EXE obfuscator which will make it more difficult to disassemble, although not impossible.

http://www.funradar.com/

I assume I need to change the lines in my batch files. Change .bat's to .exe's. Do I have to change anything else?

If you like ill work you up a basic autoit script, its format is similar to most scripting languages, easy to figure out

Let me know

I don't see any mention of security or encryption on the Autoit site.

Yeah well they spend more time developing it than they do on the web page :)

If you download AutoIT v3 and SciTE Editor also available on the AutoIT site, if you then compile a script with SciTe (Tools->Compile), you'll find the encryption stuff on the Obfuscate Tab....

post-282382-12797899386553.jpg

For example, heres a bare bones script ive hacked up in about 10 minutes (havent used AutoIT for a while), still adding error checking for the drive mapping, but ive tested the truecrypt mounting/unmounting

Also have no idea what your robocopy command line would be so thats blank, just a matter of the right RunAsWait line there...and error checking

Talking of error checking, TrueCrypt has pathetic exit code support, so it either fails on the command line or if you say try and mount an already mounted drive, you get a message box warning you of this, not a console exit code, so error checking is limited for TrueCrypt

Currently it runs at the command line and outputs errors or information to the console (command line), it can always pop up message boxes etc if you need. Ill post a finished version after i eat some dinner

If you go Tools->Compile on the first tab theres an option Create CUI instead of GUI.EXE, ticking this makes a console .exe, which is what i assumed you were looking for

Note: The opening section contains the compilation options (obfuscation etc already

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

Partial quick script:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****


;====TrueCrypt Settings =========
;$TC_Exe - path to truecrypt executable
$TC_Exe = "D:\TrueCrypt\TrueCrypt.exe"
;truecrypt container path
$TC_Path = "i:\test"
; truecrypt driveletter assign
$TC_DriveLetter = "x"
;truecrypt password
$TC_Password =  "test123"



;====Netowork Share Settings =========
;MapDriveMachineName - name of machine that has drive you wish to map, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$MapDriveMachineName = "computername"
;MapDrivePath1 - the 1st path on the machine you wish to share
$MapDrivePath1 = "\path"
;MapDrivePath2 - the 2nd path on the machine you wish to share
$MapDrivePath2 = "\path"
;NetworkDomain - name of domain that contains your user credentials, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$NetworkDomain = "domain"
;NetworkUsername - your network username
$NetworkUsername = "username"
;NetworkPassword - your network password
$NetworkPassword = "password"




;Mount True Crypt Volume
$TCMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /v " & $TC_Path & " /l" & $TC_DriveLetter & " /p " & $TC_Password)

If NOT @error Or $TCMount = 0 Then

	;write the success of truecrypt monting to the console
	ConsoleWrite(@CRLF & "Successfully mounted: "& $TC_Path & " to Drive: " & $TC_DriveLetter)

	; Map drives
	$Map1_Add = DriveMapAdd("y:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath1, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	$Map2_Add = DriveMapAdd("z:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath2, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)

	; Robocopy stuff


        ;UnMap Drives
	$Map1_Del = DriveMapDel("y:")
	$Map2_Del = DriveMapAdd("z:")

	;Un-Mount True Crypt Volume
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /d " & $TC_DriveLetter)
	If @error Or $TCUnMount > 0 Then
		ConsoleWrite(@CRLF & ""Failed to unmount: "& $TC_Path & " from Drive " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCUnMount)
	EndIf
	ConsoleWrite(@CRLF & "Successfully unmounted: "& $TC_Path & " from Drive: " & $TC_DriveLetter)
	Exit

Else
	;write the failure of truecrypt mounting to the console
	ConsoleWrite("Failed to mount: "& $TC_Path & " to Drive: " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCMount)
EndIf

This is the more complete version, as opposed to your 3 files method, this is all in one

Cleaned up some typos in the original post

Probably needs some testing and tweaking, but i dont have a network here to test one....

Like i said, its quick and dirty and the network mapping isnt tested on my end

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; variables

;====TrueCrypt Settings =========
;$TC_Exe - path to truecrypt executable
$TC_Exe = "D:\TrueCrypt\TrueCrypt.exe"
;truecrypt container path
$TC_Path = "i:\test"
; truecrypt driveletter assign
$TC_DriveLetter = "x"
;truecrypt password
$TC_Password =  "test123"

;====Netowork Share Settings =========
;MapDriveMachineName - name of machine that has drive you wish to map, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$MapDriveMachineName = "computername"
;MapDrivePath1 - the 1st path on the machine you wish to share
$MapDrivePath1 = "\path"
;MapDrivePath2 - the 2nd path on the machine you wish to share
$MapDrivePath2 = "\path"
;NetworkDomain - name of domain that contains your user credentials, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$NetworkDomain = "domain"
;NetworkUsername - your network username
$NetworkUsername = "username"
;NetworkPassword - your network password
$NetworkPassword = "password"

;====Robocopy Settings =========
;$RC_Path - path to robocopy
$RC_Path = "D:\Robocopy\robocopy.exe"
;$RC_Options - robocopy options
$RC_Options = "/e /copyall"
;$RC_Source - source path
$RC_Source = "D:\source"
;$RC_Destination - source path
$RC_Destination = "D:\destination"



; script start

;Mount True Crypt Volume
$TCMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /v " & $TC_Path & " /l" & $TC_DriveLetter & " /p " & $TC_Password)

If NOT @error Or $TCMount == 0 Then

	;write the success of truecrypt monting to the console
	ConsoleWrite(@CRLF & "Successfully mounted: "& $TC_Path & " to Drive: " & $TC_DriveLetter)

	; Map drives
	$Map1_Add = DriveMapAdd("y:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath1, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map1_Add == 1 Then
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath1  & " the error returned is: " & @extended)
		Exit
	EndIf
	$Map2_Add = DriveMapAdd("z:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath2, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map2_Add == 1 Then
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath2  & " the error returned is: " & @extended)
		Exit
	EndIf

	;Robocopy stuff
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, $RC_Path & " " & $RC_Options & " " & $RC_Source & " " &$RC_Destination)
	If @error Then
		ConsoleWrite("Robocopy failed, the error returned is: " & @error)
		Exit
        Else
	EndIf

	;whack in a quick 2 second sleep
	Sleep(2000)

        ;UnMap Drives
	$Map1_Del = DriveMapDel("y:")
	$Map2_Del = DriveMapDel("z:")

	;Un-Mount True Crypt Volume
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /d " & $TC_DriveLetter)
	If @error Or $TCUnMount > 0 Then
		ConsoleWrite(@CRLF & "Failed to unmount: "& $TC_Path & " from Drive " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCUnMount)
	EndIf
	ConsoleWrite(@CRLF & "Successfully unmounted: "& $TC_Path & " from Drive: " & $TC_DriveLetter)
	Exit

Else
	;write the failure of truecrypt mounting to the console
	ConsoleWrite("Failed to mount: "& $TC_Path & " to Drive: " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCMount)
EndIf

Due to the fact i cant edit the above posts, heres an even more complete version with robocopy error checking enabled

Apparently there are different thoughts on what exactly the exit codes for robocopy are, ive used what MS says...

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; variables

;====TrueCrypt Settings =========
;$TC_Exe - path to truecrypt executable
$TC_Exe = "D:\TrueCrypt\TrueCrypt.exe"
;truecrypt container path
$TC_Path = "i:\test"
; truecrypt driveletter assign
$TC_DriveLetter = "x"
;truecrypt password
$TC_Password =  "test123"

;====Netowork Share Settings =========
;MapDriveMachineName - name of machine that has drive you wish to map, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$MapDriveMachineName = "computername"
;MapDrivePath1 - the 1st path on the machine you wish to share
$MapDrivePath1 = "\path"
;MapDrivePath2 - the 2nd path on the machine you wish to share
$MapDrivePath2 = "\path"
;NetworkDomain - name of domain that contains your user credentials, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$NetworkDomain = "domain"
;NetworkUsername - your network username
$NetworkUsername = "username"
;NetworkPassword - your network password
$NetworkPassword = "password"

;====Robocopy Settings =========
;$RC_Path - path to robocopy
$RC_Path = "D:\Robocopy\robocopy.exe"
;$RC_Options - robocopy options
$RC_Options = "/e /copyall"
;$RC_Source - source path
$RC_Source = "D:\source"
;$RC_Destination - source path
$RC_Destination = "D:\destination"



; script start

;Mount True Crypt Volume
$TCMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /v " & $TC_Path & " /l" & $TC_DriveLetter & " /p " & $TC_Password)

If NOT @error Or $TCMount == 0 Then

	;write the success of truecrypt monting to the console
	ConsoleWrite(@CRLF & "Successfully mounted: "& $TC_Path & " to Drive: " & $TC_DriveLetter)

	; Map drives
	$Map1_Add = DriveMapAdd("y:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath1, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map1_Add == 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath1)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath1  & " the error returned is: " & @extended)
		Exit
	EndIf

	$Map2_Add = DriveMapAdd("z:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath2, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map2_Add == 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath2)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath2  & " the error returned is: " & @extended)
		Exit
	EndIf

	;Robocopy stuff
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, $RC_Path & " " & $RC_Options & " " & $RC_Source & " " &$RC_Destination)
	;Write copy result to console
	Switch @error
		Case 0	
			ConsoleWrite("No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.")
		Case 1	
			ConsoleWrite("All files were copied successfully.")
		Case 2	
			ConsoleWrite("There are some additional files in the destination directory that are not present in the source directory. No files were copied.")
		Case 3	
			ConsoleWrite("Some files were copied. Additional files were present. No failure was encountered.")
		Case 5	
			ConsoleWrite("Some files were copied. Some files were mismatched. No failure was encountered.")
		Case 6	
			ConsoleWrite("Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory.")
		Case 7	
			ConsoleWrite("Files were copied, a file mismatch was present, and additional files were present.")
	EndSwitch		


	;According to MS any error code greater than 8 means a robocopy failure
	If @error >= 8 Then
		ConsoleWrite("Robocopy failed, the error returned is: " & @error)
		Exit
        Else
	EndIf

	;whack in a quick 2 second sleep
	Sleep(2000)

        ;UnMap Drives
	$Map1_Del = DriveMapDel("y:")
	$Map2_Del = DriveMapDel("z:")

	;Un-Mount True Crypt Volume
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /d " & $TC_DriveLetter)
	If @error Or $TCUnMount > 0 Then
		ConsoleWrite(@CRLF & "Failed to unmount: "& $TC_Path & " from Drive " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCUnMount)
	EndIf
	ConsoleWrite(@CRLF & "Successfully unmounted: "& $TC_Path & " from Drive: " & $TC_DriveLetter)
	Exit

Else
	;write the failure of truecrypt mounting to the console
	ConsoleWrite("Failed to mount: "& $TC_Path & " to Drive: " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCMount)
EndIf

Thanks. I don't understand all of that, but it should be a great learning experience and get me started with autoit.

I don't get the robocopy settings section. It seems like there is just one set of source and destination variables. Also, how would I go about adding more robocopy jobs?

Currently, in my robocopy.bat, I have lines like this:

C:\windows\system32\robocopy.exe "G:\Folder1" \\DOWNSTAIRS\Folder1$ /mir /zb /dcopy:T /copyall /xa:h > "D:\Locked\backups_log.txt"

I use the same options for each job. And I have each one append the log file.

And just to clarify, I'm not on a domain, so I put the name of my local machine for the $NetworkDomain, correct?

Thanks. I don't understand all of that, but it should be a great learning experience and get me started with autoit.

I don't get the robocopy settings section. It seems like there is just one set of source and destination variables. Also, how would I go about adding more robocopy jobs?

Currently, in my robocopy.bat, I have lines like this:

C:\windows\system32\robocopy.exe "G:\Folder1" \\DOWNSTAIRS\Folder1$ /mir /zb /dcopy:T /copyall /xa:h > "D:\Locked\backups_log.txt"

I use the same options for each job. And I have each one append the log file.

And just to clarify, I'm not on a domain, so I put the name of my local machine for the $NetworkDomain, correct?

If youre not on a domain, under AutoIT you can use @ComputerName instead of "domain" just remember to not enclose it in " "

Okay the quickest and most painless way to run multiple copies, as you say you have the same copy options for each job, would be to use an .ini file

Ini files, you may have seen, have a section heading, and then key abd value pairs

i.e.

[section heading]
key=value

So you could just use an .ini file i.e. robocopy.ini, use a section heading [copy] store the source as the key and the destination as the value

Then you just loop through the key/value pairs using the autoit command IniReadSection and apply those key(source) and value(destination) pairs which come out as a 2 dimensional array to the robocopy command line

This is how it is done in my example script:

New variable declared in robocopy section, this just sets the path to the ini file

$RC_Ini = "D:\TrueCrypt\Robocopy.ini"

Next we loop through the key/value pairs and send them through the previous robocopy routine i posted earlier, with modifications

	;Robocopy stuff
	$CopyLines = IniReadSection($RC_Ini, "Copy")
	If @error Then
		MsgBox(4096, "", "Error occurred, probably no INI file.")
	Else
		For $i = 1 To $CopyLines[0][0]
		$RoboCopy = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, $RC_Path & " " & $RC_Options & " " & $CopyLines[$i][0] & " " & $CopyLines[$i][1])
		;Write copy result to console
		Switch @error
			Case 0
				ConsoleWrite("No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.")
			Case 1
				ConsoleWrite("All files were copied successfully.")
			Case 2
				ConsoleWrite("There are some additional files in the destination directory that are not present in the source directory. No files were copied.")
			Case 3
				ConsoleWrite("Some files were copied. Additional files were present. No failure was encountered.")
			Case 5
				ConsoleWrite("Some files were copied. Some files were mismatched. No failure was encountered.")
			Case 6
				ConsoleWrite("Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory.")
			Case 7
				ConsoleWrite("Files were copied, a file mismatch was present, and additional files were present.")
		EndSwitch
		;According to MS any error code greater than 8 means a robocopy failure
		If @error >= 8 Then
			ConsoleWrite("Robocopy failed, the error returned is: " & @error)
		Exit
		Else
		EndIf
		Next
	EndIf

The loop part:

For $i = 1 To $CopyLines[0][0]

$CopyLines as mentioned is a 2 dimensional array thats what the [0] [0] part is, in autoit array element 0, or [0] always the maximum number of array elements.

So if we have 4 key value pairs, the true value of $CopyFiles is [4][4]

And For $i = 1 To $CopyLines[0][0] will run 4 times, with $I increasing by 1 each time until it hits 4 and the robocopy command will execute using each new key/value pair...$CopyLines[$i][0] is the key, $CopyLines[$i][1] is the value

To help you understand the loop better,

Create a file named robocopy.ini and paste the following in it:

[Copy]
c:\temp=d:\temp
c:\windows=e:\windows
d:\programs=f:\programs
f:\test=g:\test2

Then you can run the following script snippet (changing the path to the ini file you just created of course) from within SciTE (Tools->Go):

Note: this is almost verbatim form the autoit help file, i just modified it for my purposes within the longer and above example scripts

$IniFile = "D:\TrueCrypt\Robocopy.ini"

$CopyLines = IniReadSection($IniFile, "Copy")
If @error Then
    MsgBox(4096, "", "Error occurred, probably no INI file.")
Else
    For $i = 1 To $CopyLines[0][0]

        MsgBox(0, "Test", @CRLF & "CopyLine number: " & $i & "   Source: " & $CopyLines[$i][0] & "   Destination: " & $CopyLines[$i][1])
    Next
EndIf

Now the full revised script:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; variables

;====TrueCrypt Settings =========
;$TC_Exe - path to truecrypt executable
$TC_Exe = "D:\TrueCrypt\TrueCrypt.exe"
;truecrypt container path
$TC_Path = "i:\test"
; truecrypt driveletter assign
$TC_DriveLetter = "x"
;truecrypt password
$TC_Password =  "test123"

;====Netowork Share Settings =========
;MapDriveMachineName - name of machine that has drive you wish to map, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$MapDriveMachineName = "computername"
;MapDrivePath1 - the 1st path on the machine you wish to share
$MapDrivePath1 = "\path"
;MapDrivePath2 - the 2nd path on the machine you wish to share
$MapDrivePath2 = "\path"
;NetworkDomain - name of domain that contains your user credentials, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$NetworkDomain = "domain"
;NetworkUsername - your network username
$NetworkUsername = "username"
;NetworkPassword - your network password
$NetworkPassword = "password"

;====Robocopy Settings =========
;$RC_Path - path to robocopy
$RC_Path = "D:\Robocopy\robocopy.exe"
;$RC_Options - robocopy options
$RC_Options = "/e /copyall"
;$RC_Source - source path
$RC_Source = "D:\source"
;$RC_Destination - source path
$RC_Destination = "D:\destination"
;$RC_Ini -  a file containing multiple source and destination folders
; this file will have a heading of [Copy]
; then under heading a separate source=destination on its onw line for each copy job
; i.e.:
;
;[Copy]
;c:\temp=d:\temp
;c:\windows=e:\windows
;d:\programs=f:\programs
$RC_Ini = "D:\TrueCrypt\Robocopy.ini"




; script start

;Mount True Crypt Volume
$TCMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /v " & $TC_Path & " /l" & $TC_DriveLetter & " /p " & $TC_Password)

If NOT @error Or $TCMount == 0 Then

	;write the success of truecrypt monting to the console
	ConsoleWrite(@CRLF & "Successfully mounted: "& $TC_Path & " to Drive: " & $TC_DriveLetter)

	; Map drives
	$Map1_Add = DriveMapAdd("y:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath1, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map1_Add == 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath1)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath1  & " the error returned is: " & @extended)
		Exit
	EndIf

	$Map2_Add = DriveMapAdd("z:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath2, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map2_Add == 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath2)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath2  & " the error returned is: " & @extended)
		Exit
	EndIf

	;Robocopy stuff
	$CopyLines = IniReadSection($RC_Ini, "Copy")
	If @error Then
		MsgBox(4096, "", "Error occurred, probably no INI file.")
	Else
		For $i = 1 To $CopyLines[0][0]
		$RoboCopy = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, $RC_Path & " " & $RC_Options & " " & $CopyLines[$i][0] & " " & $CopyLines[$i][1])
		;Write copy result to console
		Switch @error
			Case 0
				ConsoleWrite("No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.")
			Case 1
				ConsoleWrite("All files were copied successfully.")
			Case 2
				ConsoleWrite("There are some additional files in the destination directory that are not present in the source directory. No files were copied.")
			Case 3
				ConsoleWrite("Some files were copied. Additional files were present. No failure was encountered.")
			Case 5
				ConsoleWrite("Some files were copied. Some files were mismatched. No failure was encountered.")
			Case 6
				ConsoleWrite("Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory.")
			Case 7
				ConsoleWrite("Files were copied, a file mismatch was present, and additional files were present.")
		EndSwitch
		;According to MS any error code greater than 8 means a robocopy failure
		If @error >= 8 Then
			ConsoleWrite("Robocopy failed, the error returned is: " & @error)
		Exit
		Else
		EndIf
		Next
	EndIf

	;whack in a quick 2 second sleep
	Sleep(2000)

        ;UnMap Drives
	$Map1_Del = DriveMapDel("y:")
	$Map2_Del = DriveMapDel("z:")

	;Un-Mount True Crypt Volume
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /d " & $TC_DriveLetter)
	If @error Or $TCUnMount > 0 Then
		ConsoleWrite(@CRLF & "Failed to unmount: "& $TC_Path & " from Drive " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCUnMount)
	EndIf
	ConsoleWrite(@CRLF & "Successfully unmounted: "& $TC_Path & " from Drive: " & $TC_DriveLetter)
	Exit

Else
	;write the failure of truecrypt mounting to the console
	ConsoleWrite("Failed to mount: "& $TC_Path & " to Drive: " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCMount)
EndIf

As before, this is a BASIC script, and there may be errors i havent seen with my tired eyes (eagle eyed viewers will note that each revision clears up typos in particular) and there may be ways in which functionality can be improved upon (This is a stripped down wham bam example of functions and program flow), im just too tired after a big day to give it any more attention tonight. Any questions, PM me, ill be back tomorrow.

Corrected 3 errors that i missed last night (in DriveMapAdd section, using == operators for numerics doesnt work, been a while since i programmed anything)

Fixed, sorry folks

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/cs=1 /cn=1 /cf=1 /cv=1 /sf=1 /sv=1
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; variables

;====TrueCrypt Settings =========
;$TC_Exe - path to truecrypt executable
$TC_Exe = "D:\TrueCrypt\TrueCrypt.exe"
;truecrypt container path
$TC_Path = "i:\test"
; truecrypt driveletter assign
$TC_DriveLetter = "x"
;truecrypt password
$TC_Password =  "test123"

;====Netowork Share Settings =========
;MapDriveMachineName - name of machine that has drive you wish to map, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$MapDriveMachineName = "computername"
;MapDrivePath1 - the 1st path on the machine you wish to share
$MapDrivePath1 = "\path"
;MapDrivePath2 - the 2nd path on the machine you wish to share
$MapDrivePath2 = "\path"
;NetworkDomain - name of domain that contains your user credentials, if on same machine, then you can use @ComputerName , no quotations marks around this, its an autoit macro.
$NetworkDomain = "domain"
;NetworkUsername - your network username
$NetworkUsername = "username"
;NetworkPassword - your network password
$NetworkPassword = "password"

;====Robocopy Settings =========
;$RC_Path - path to robocopy
$RC_Path = "D:\Robocopy\robocopy.exe"
;$RC_Options - robocopy options
$RC_Options = "/e /copyall"
;$RC_Source - source path
$RC_Source = "D:\source"
;$RC_Destination - source path
$RC_Destination = "D:\destination"
;$RC_Ini -  a file containing multiple source and destination folders
; this file will have a heading of [Copy]
; then under heading a separate source=destination on its onw line for each copy job
; i.e.:
;
;[Copy]
;c:\temp=d:\temp
;c:\windows=e:\windows
;d:\programs=f:\programs
$RC_Ini = "D:\TrueCrypt\Robocopy.ini"




; script start

;Mount True Crypt Volume
$TCMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /v " & $TC_Path & " /l" & $TC_DriveLetter & " /p " & $TC_Password)

If NOT @error Or $TCMount = 0 Then

	;write the success of truecrypt monting to the console
	ConsoleWrite(@CRLF & "Successfully mounted: "& $TC_Path & " to Drive: " & $TC_DriveLetter)

	; Map drives
	$Map1_Add = DriveMapAdd("y:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath1, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map1_Add = 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath1)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath1  & " the error returned is: " & @extended)
		Exit
	EndIf

	$Map2_Add = DriveMapAdd("z:", "\\" & $MapDriveMachineName & "\" & $MapDrivePath2, 0, $NetworkDomain & "\" & $NetworkUsername, $NetworkPassword)
	If $Map2_Add = 1 Then
		ConsoleWrite("Successfully mapped network drive: " & $MapDrivePath2)
		SetError(0)
	Else
		ConsoleWrite("Failed to map network drive: " & $MapDrivePath2  & " the error returned is: " & @extended)
		Exit
	EndIf

	;Robocopy stuff
	$CopyLines = IniReadSection($RC_Ini, "Copy")
	If @error Then
		MsgBox(4096, "", "Error occurred, probably no INI file.")
	Else
		For $i = 1 To $CopyLines[0][0]
		$RoboCopy = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, $RC_Path & " " & $RC_Options & " " & $CopyLines[$i][0] & " " & $CopyLines[$i][1])
		;Write copy result to console
		Switch @error
			Case 0
				ConsoleWrite("No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.")
			Case 1
				ConsoleWrite("All files were copied successfully.")
			Case 2
				ConsoleWrite("There are some additional files in the destination directory that are not present in the source directory. No files were copied.")
			Case 3
				ConsoleWrite("Some files were copied. Additional files were present. No failure was encountered.")
			Case 5
				ConsoleWrite("Some files were copied. Some files were mismatched. No failure was encountered.")
			Case 6
				ConsoleWrite("Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory.")
			Case 7
				ConsoleWrite("Files were copied, a file mismatch was present, and additional files were present.")
		EndSwitch
		;According to MS any error code greater than 8 means a robocopy failure
		If @error >= 8 Then
			ConsoleWrite("Robocopy failed, the error returned is: " & @error)
		Exit
		Else
		EndIf
		Next
	EndIf

	;whack in a quick 2 second sleep
	Sleep(2000)

        ;UnMap Drives
	$Map1_Del = DriveMapDel("y:")
	$Map2_Del = DriveMapDel("z:")

	;Un-Mount True Crypt Volume
	$TCUnMount = RunAsWait($NetworkUsername, $NetworkDomain, $NetworkPassword, 0, "D:\TrueCrypt\TrueCrypt.exe /q /d " & $TC_DriveLetter)
	If @error Or $TCUnMount > 0 Then
		ConsoleWrite(@CRLF & "Failed to unmount: "& $TC_Path & " from Drive " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCUnMount)
	EndIf
	ConsoleWrite(@CRLF & "Successfully unmounted: "& $TC_Path & " from Drive: " & $TC_DriveLetter)
	Exit

Else
	;write the failure of truecrypt mounting to the console
	ConsoleWrite("Failed to mount: "& $TC_Path & " to Drive: " & $TC_DriveLetter & @CRLF  & "ExitCode: " & @error & "TrueCrypt returned error: " & $TCMount)
EndIf

That's looking great. Thank you.

Is here a way to exclude folders in a job? Also, I think it would be better to have the robocopy options in the INI file so that when more jobs are added they can have different options.

Also, there's two lines that have "D:\TrueCrypt\TrueCrypt.exe" . Should that be in the script?

That's looking great. Thank you.

Is here a way to exclude folders in a job? Also, I think it would be better to have the robocopy options in the INI file so that when more jobs are added they can have different options.

Also, there's two lines that have "D:\TrueCrypt\TrueCrypt.exe" . Should that be in the script?

Well spotted, very tired here lol

I forgot to substitute those lines with $TC_Exe, ill post the (yet again) fixed script when i have answered your second question...

As for adding the ability to have different options for each job, well thats going to involve a bit of a rewrite....since you originally were going to keep the same options i did it the quick easy way, now we get to play with some more array functions, StringSplit time methinks...

Gimme a little while....

There's a robocopy option for excluding folders. /xd

robocopy.exe D:\Folder \\computername\Folder /mir /zb /dcopy:T /copyall /xd "D:\Folder\Downloads" /xa:h

I think it would be easier to make changes later if the robocopy options where stored in the INI file.

Heres how to do the robocopy options via ini file method in a quick test:

1) Change the format of the ini file

- Will use key as numerical increment so you can troubleshoot by line if theres an error, the script will tell you which line to look at

- Will add all 3 options (robocopy options, source, destination) as a value, split by commas ","

demo ini file (robocopy.ini for purpose of test):

[Copy]
1=/e /copyall,c:\temp,d:\temp
2=/mir,c:\windows,e:\windows
3=/e,d:\programs,f:\programs
4=/mir /e,f:\test,g:\test2

2) quick test script to show this in use, again can run without being compiled, just use Tools->Go in SciTe:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#include <Array.au3>

$IniFile = "D:\TrueCrypt\Robocopy.ini"
;read iniffile section [Copy] and return the key/value pairs underneath into 2 dimensional array [0][0]
$CopyLines = IniReadSection($IniFile, "Copy")
If @error Then
	;if no ini file found or other error, show mesagebox
        MsgBox(4096, "", "Error occurred, probably no INI file.")
Else
	;otherwise if no error, continue on
	;set loop to run as many times as there are key/value pairs
        For $i = 1 To $CopyLines[0][0]
		;split value (containing ROBOCOPYOPTIONS,SOURCE,DESTINATION) into 3 seperate variables at the comma
		$CopyLinesSplit = StringSplit($CopyLines[$i][1], ",")
		;if there are not 3 values split by a comma then show error and move to the next value
		If $CopyLinesSplit[0] < 3 Then
		         MsgBox(0, "Test", "Missing value in Ini File, key number: " & $i & "   expecting Robocopy Options, Source, Destination. One is missing")
		Else
		         ;check for empty element in returned array, this would mean you had put a comma after say source but failed to put in a value destination
		         $CheckEmpty = _ArraySearch($CopyLinesSplit, "", 1)
		         ;if a blank value is NOT found, continue script, in this case @error is actually good :)
		         If @error Then
		                 ;set robocopy variable from the first element of $CopyLinesSplit array
		                 $RoboCopyOptions = $CopyLinesSplit[1]
		                 ;set source variable from the second element of $CopyLinesSplit array
		                 $CopySource = $CopyLinesSplit[2]
		                 ;set destination from the third element of $CopyLinesSplit array
		                 $CopyDestination = $CopyLinesSplit[3]
                                 MsgBox(0, "Test", "Ini file key number: " & $i &  "   RoboCopy Options: " & $RoboCopyOptions &  "   Source: " & $CopySource & "   Destination: " & $CopyDestination)
		        Else
			         ;if a blank value is found, display message box
			         MsgBox(0, "Test", "Missing value after comma in Ini File, key number: " & $i & "   expecting Robocopy Options, Source, Destination. One is missing after a comma")
		        EndIf
		EndIf
    Next
EndIf

There is also error checking in case you had an ini file line that went (missing a value after a comma):

2=/mir,c:\windows,

And also if you missed a comma totally, it will always check for 3 values, so the following would error:

3=/e,d:\programs

So try the following modified ini file contents with the script and youll see what i mean

[Copy]
1=/e /copyall,c:\temp,d:\temp
2=/mir,c:\windows,
3=/e,d:\programs
4=/mir /e,f:\test,g:\test2

Im adding this new stuff to the script and a bit of logging etc, and will post it soon...i should have started this today instead of last night after I'd had some sleep!

In case youre wondering what the delay is...im having a bit of a fight with robocopy on exit codes at the moment

All else is done, i have dug out a copy of robocopy and have the script doing multiple jobs with multiple options with errors/info output to both the console (commandline) and logging to a text file

The file copying is working fine on each job, just robocopy gives the wrong exit code at the moment, im having to find a definitive list of exit codes that work properly

should have this small hitch fixed soon

The only thing i cannot test in all this script is the drive mapping...

Heres a quick squiz at what you see both at the commandline and in the logfile....

Attempting to mount truecrypt volume:  D:\test  on drive letter:  z ....

Successfully mounted:  D:\test to Drive:  z

About to start Robocopy job number:  1
RoboCopy Options:  /e /copyall
Source Folder:  d:\temp
Destination Folder:  z:\test

No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.

About to start Robocopy job number:  2
RoboCopy Options:  /mir
Source Folder:  d:\temp
Destination Folder:  z:\test2

No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.

Successfully unmounted:  D:\test from Drive:  z

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.