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.

  On 22/07/2010 at 05:30, Raa said:

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".

  Quote
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/

  On 22/07/2010 at 06:26, unknownsoldierX said:

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

  On 22/07/2010 at 07:27, unknownsoldierX said:

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?

  On 22/07/2010 at 11:33, unknownsoldierX said:

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?

  On 23/07/2010 at 01:37, unknownsoldierX said:

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.
  • Posts

    • Nothing surprising there. Anyone expecting privacy on ANY social media platform is delusional at best. Let alone one controlled by the same creep that owns Tesla (a.k.a. facecrook on wheels), which blatantly violates user privacy with Tesla vehicles as reported by Louis Rossman. This action of his is just another prime example of why ANYTHING from him is trust-worthy as the same from Zuckerberg...i.e. not at all.
    • 007 First Light's first trailer shows off an action-packed James Bond game by Pulasthi Ariyasinghe IO Interactive has been teasing its next project outside of Hitman for some time now, and even before its first-ever showcase that's happening soon, the James Bond game showed up during the PlayStation State of Play event today. Dubbed 007 First Light, the third-person action-adventure title received a trailer showing off the new face of Bond, some of his gadgets, and plenty of action. Catch it above. While inspired by novels of Ian Fleming as well as the movie franchise, First Light will follow Bond to reveal just how he earned his MI6 007 role in an all-original story by IO Interactive. James Bond will be just 26 years old in this iteration. While not the smooth and tactical agent with a martini that we've seen in the movies just yet, this Bond is described as a man with "sharp instincts, sometimes reckless, who is still learning when to fight, when to bluff, and when to disappear into the shadows." As expected from the Hitman developer, missions in 007 First Light will offer both stealth and loud options, depending on the player's actions. A variety of futuristic gadgets will be available for use as well, while driving portions are also confirmed for the title. "In 007 First Light, Bond starts as a NAVY air crewman, when against all odds, an audacious act of bravery propels him on MI6’s most challenging training program," says the studio, regarding Bond's beginnings. "This training coupled with his natural instinct, wits, and heart will see him grow into a fully-fledged spy. It’s a completely original standalone story, developed in collaboration with Amazon MGM Studios." The studio says that the game will take players across the world, from snow-drenched mountains to sun-soaked beaches, while interacting with some of the most iconic characters in the franchise, including M, Q, and Moneypenny. There are original faces in the story too, such as Bond's mentor Greenway. 007 First Light is coming to PC (Steam and Epic Games Store, Xbox Series X|S, PlayStation 5, and the Nintendo Switch 2 sometime in 2026.
    • That sharp cold toothache you dread? Its origins trace back to ancient, unexpected purpose by Sayan Sen Image by Pavel Danilyuk via Pexels Scientists at the University of Chicago have discovered that the sensitive tissue inside our teeth first evolved as part of the armored skin of ancient fish. Their new study, published in Nature, confirms that dentine—a key part of teeth—was originally used by early vertebrates to sense their surroundings. This research supports the idea that dentine wasn’t always used for chewing. Instead, millions of years ago, it helped fish detect changes in the water. The study also clears up confusion about Anatolepis heintzi, a fossil once thought to be the earliest known vertebrate because of its dentine-like structures. For years, scientists debated whether Anatolepis was really an early vertebrate. The fossil had tiny tubules that some researchers believed were odontodes—small structures considered to be the ancestors of teeth. However, there wasn’t enough evidence to be sure. To settle the debate, scientists used synchrotron scanning, a powerful imaging technique, to study different fossils and modern creatures. The scans revealed that Anatolepis didn’t have dentine. Instead, its tubules were sensory structures similar to those found in arthropods like crabs and shrimp. These structures, called sensilla, help animals detect their surroundings. “This shows us that ‘teeth’ can also be sensory even when they’re not in the mouth,” said lead researcher Yara Haridy, PhD. “There’s sensitive armor in these fish. There’s sensitive armor in these arthropods. This explains the confusion with these early Cambrian animals.” Although Anatolepis turned out to be an arthropod, researchers did find real dentine in another ancient fish. The Ordovician vertebrate Eriptychius, which lived about 465 million years ago, had large dentine-filled tubules in its armor. This confirms that dentine first evolved in vertebrates as a sensory tissue. Further tests showed that modern fish, such as sharks and teleosts, still have nerve connections in their external dentine structures. This means early vertebrates may have used dentine to sense their environment before it became part of teeth. Scientists have two main ideas about how teeth came to be. The “inside-out” theory suggests teeth evolved first and were later adapted for exoskeletons. The new research supports the “outside-in” theory, which argues that sensory structures appeared first in exoskeletons and later evolved into teeth. While the team didn’t find the oldest vertebrate fish, study co-author Neil Shubin, PhD, believes the discovery is still important. “We didn’t find the earliest one, but in some ways, we found something way cooler,” he said. Source: University of Chicago, Nature This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • "How dare you profit off our user's data without compensating them. That's our job!"
  • Recent Achievements

    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
    • Apprentice
      DarkShrunken went up a rank
      Apprentice
    • Dedicated
      CHUNWEI earned a badge
      Dedicated
    • Collaborator
      DarkShrunken earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      347
    2. 2
      snowy owl
      167
    3. 3
      +FloatingFatMan
      164
    4. 4
      ATLien_0
      161
    5. 5
      Xenon
      128
  • Tell a friend

    Love Neowin? Tell a friend!