IIS Scripts

If you have to view the Php version. Use the following script to view it:

<?
phpinfo();
?>

————————————————————————————————————————————————-

This script will be helpful in restarting the services in the IIS  through Scripts

  • Save the following text as a batch file.  Copy the script in notepad and save it as .bat file (EG)   Restart.bat
  • To execute the batch file, Just double click it.

————————————————————————–

iisreset /stop

net stop “ColdFusion MX 8 Application Server”
net stop “ColdFusion MX 8 ODBC Agent”
net stop “ColdFusion MX 8 ODBC Server”
net stop “ColdFusion MX 8 Search Server”

kill -f swagent.exe
kill -f swstrtr.exe
kill -f jrun.exe
kill -f jrunsvc.exe
kill -f swsoc.exe
kill -f java.exe

net start “ColdFusion MX 8 Application Server”
net start “ColdFusion MX 8 ODBC Agent”
net start “ColdFusion MX 8 ODBC Server”
net start “ColdFusion MX 8 Search Server”

iisreset /start

———————————————————————

If the problem still persists. Restart the services directly in ‘services.msc’

In coldfusion8. Need to kill the jrun.exe in the task manager  and restart the services to bring

back.

————————————————————————————————————————————————-

Test script for CDOSYS mail:

<%
Set objMessage = CreateObject(“CDO.Message”)
objMessage.Subject = “Example CDO Message”
objMessage.From = “testsimp@gmail.com”
objMessage.To = “testsimp@gmail.com”
objMessage.TextBody = “cdo message”

‘==This section provides the configuration information for the remote SMTP server.
‘==Normally you will only change the server name or IP.
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusing&#8221;) = 2

‘Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserver&#8221;) = “127.0.0.1”

‘Server port (typically 25)
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserverport&#8221;) = 25

objMessage.Configuration.Fields.Update

‘==End remote SMTP server configuration section==

objMessage.Send
If Err <> 0 Then
Response.Write “An error occurred: ” & Err.Description
else
Response.Write “Successfully Sent”
End If
%>

————————————————————————————————————————————————-

Aspx Test page:

<html>
<body bgcolor=”Pink”>
<center>
<h1>Test Page – Asp.Net</h1><BR></BR>
<h2>Today is <%Response.write(DateTime.Now.ToLongDateString()) %></h2>
</center>
</body>
</html>

————————————————————————————————————————————————–

Jmail:

<% smtp_server_address = “win16.mail.uk”
On Error Resume Next
Response.Buffer = True
Set Jmail = Server.CreateOBject( “JMail.Message” )
Jmail.Logging = true
Jmail.Silent = true
JMail.From = “test@yahoo.com”
Jmail.AddRecipient “testsimp@yahoo.com”
JMail.Subject = “Form Response”
‘Doing things this way helps retain the form field order
‘For i = 1 to (Request.Form.Count)

‘   body = body & Request.Form.Key(i) & “: ” & Request.Form.Item(i) & vbcrlf

‘Next
JMail.Body = “Test Jmail Mail”
JMail.Priority = 1
If Not Jmail.Send(smtp_server_address) then
‘ There was an error – print the error log
Response.write (“Error:<br>” & Jmail.log)
Else
‘ The message has been sent – redirect to confirmation page
Set JMail = Nothing
Response.write (“Mail Successfully send”)
End If
Set JMail = Nothing
%>

————————————————————————————————————————————————-

ASP Script Mail:

<%
Set Mailer = Server.CreateObject(“SMTPsvg.Mailer”)
Mailer.FromName   = “Testmail”
Mailer.FromAddress= “mail@yahoo.com”
Mailer.RemoteHost = “Localhost:25”
Mailer.AddRecipient “Test”,”testsimplyy@yahoo.com”
Mailer.Subject    = “Great SMTP Product!”
Mailer.BodyText   = “Dear Test” & VbCrLf & “Your widgets order has been processed!”
if Mailer.SendMail then
Response.Write “Mail sent…”
else
Response.Write “Mail send failure. Error was ” & Mailer.Response
end if
%>

————————————————————————————————————————————————–

Cdonts Mail Script:

<%
Dim objMail
Set objMail = Server.CreateObject(“CDONTS.NewMail”)
objMail.From = “test@yahoo.com”
objMail.Subject = “CDONTS Samples”
objMail.To = “testsimplyy@yahoo.com”
objMail.Body = “This is a sample message sent using CDONTS.”
objMail.Send
Response.write(“Mail was Sent”)
‘You must always do this with CDONTS.
set objMail = nothing
%>

————————————————————————————————————————————————–

Coldfusion Mail Script:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
</head>
<body>
<cftry>
<cfmail
to=”testsimplyy@yahoo.com”
from=”test123@yahoo.com”
subject=”This is a test mail for checking ColdFusion”
SERVER=”localhost”
USERNAME=”test123@yahoo.com”
PASSWORD=”omega123″
debug=”yes”
type=”HTML”>
test email
</cfmail>
<cfcatch type=”any”>
Did not send
</cfcatch>
</cftry>
</body>
</html>

————————————————————————————————————————————————-

PHP Mail Script:

<?php
$to = “testsimple@hotmail.com”;
$subject = “Test mail”;
$message = “Hello! This is a simple email message.”;
$from = “myname@ourdomain.com”;
$headers = “From: $from”;
mail($to,$subject,$message,$headers);
echo “Mail Sent.”;
?>

————————————————————————————————————————————————-

Backup Scripts:

Bat file for MSSQL: ‘backup_mssql.bat’

The following script is used to create a directory and backuping up the mssql databases. Finally it’s calling the bat file IISbackup.bat

mkdir E:\backup
mkdir E:\backup\mssql
cscript backup_mssql.vbs
cscript zip-dir-r.vbs E:\backup\mssql
call IISbackup.bat

————————————————————————————————————————-

The script to backup the MSSQL: ‘backup_mssql.vbs’

on error resume next
Dim oServer
Dim oDatabase
Dim oBackup
Dim sBAKFilePath
Dim oShell

‘change this to where ever you want to place your backup files, no trailing backslash, we add it below

sBAKFilePath = “E:\backup\mssql”

‘we need a backup object in addition to the sqlserver one

Set oServer = CreateObject(“SQLDmo.SqlServer”)
Set oBackup = CreateObject(“SQLDmo.Backup”)
oServer.LoginSecure = True
oServer.Connect “(local)”
set oShell = CreateObject(“WScript.shell”)

‘this will do a full backup of every database except TempDB to a file (not a device )

For Each oDatabase In oServer.Databases

‘TRUNCATE LOG

oShell.run “cmd /C osql -E -S  -Q “”USE ” & oDatabase.Name & “; DBCC SHRINKFILE (2, 2);BACKUP LOG ” & oDatabase.Name & ” WITH TRUNCATE_ONLY;DBCC SHRINKFILE (2, 2);”””, 0, true

If UCase(oDatabase.Name) <> “TEMPDB” Then
oBackup.Database = oDatabase.Name

‘remove any previous backup – same as using T-SQL with init

oBackup.Initialize = True

‘dynamically create the name of the backup file

oBackup.Files = sBAKFilePath & “\” & oDatabase.Name & “_” & Year(Now()) &  Month(Now()) & Day(Now()) & Hour(Now()) & Minute(Now())  & “.bak”
oBackup.BackupSetName = oDatabase.Name
oBackup.BackupSetDescription = oDatabase.Name

‘set the action property as needed
‘0 = Full backup
‘1 = Differential
‘2 = Specified files only
‘3 = Log backup

oBackup.Action = 0
oBackup.SQLBackup oServer
End If
Next

‘clean up
Set oBackup = Nothing
oServer.DisConnect
Set oServer = Nothing

—————————————————————————————————————–

The script to zip the MSSQL:  zip-dir-r.vbs
‘ VB Script Document
set fso = createobject(“scripting.filesystemobject”)

EnumerateDirectory WScript.Arguments.Item(0)

sub EnumerateDirectory(sPath)

wscript.echo sPath

ZipFiles sPath

set folder = fso.getfolder(sPath)
for each fldr in folder.subfolders
EnumerateDirectory fldr.path

next

end sub

function ZIPFiles(path)
on error goto 0
dim fso
dim textstream
dim folder
dim zipfile

set zipfso = CreateObject(“Scripting.FileSystemObject”)
set zipfolder = zipfso.getfolder(path)

‘wscript.echo zipfolder.Path

‘wscript.echo Path
s = “”
for each file in zipfolder.files
‘wscript.echo “Blah 2”
dtcreated = null
on error resume next
dtcreated = file.DateLastModified
‘wscript.echo dtcreated
‘ on error goto 0

if Right(file.path,3) <> “zip”   then
if Right(file.path,2) <> “gz” then

zipfile = Replace(file.path,StripFileExt(file.path),”.zip”)

‘wscript.echo zipfile

AddToZIP zipfile, file.path, 1
end if

end if
next

set zipfolder = nothing
set zipfso = nothing

End Function

‘DELETE / ZIP LOG FILES

function AddToZip(zipfile,filetozip, delete)

‘First check to see if ZIP File Exists
dim ObjFSO
dim ZIPObj
dim objFile
Dim mode, oShell, objCab
set ObjFSO = CreateObject(“Scripting.FileSystemObject”)
‘wscript.echo zipfile

set objFile = objFSO.GetFile(filetozip)

‘wscript.echo objFile.Size

if objFile.Size < 3900000000 then
mode = 1
else
mode = 2
end if

‘wscript.echo mode

if mode = 1 then

if objFSO.FileExists(zipfile) = TRUE then

‘open exist ZIP File, Add file to ZIP

‘set ZIPObj = CreateObject(“BSZip.BSZipX”)
‘ZIPObj.OpenZIP zipfile

‘ZIPObj.OrderFile filetozip
‘ZIPObj.CompressFiles
‘ZIPObj.CloseZip
‘set ZipObj = nothing

set zip = CreateObject(“ChilkatZip2.ChilkatZip2”)
zip.UnlockComponent “Zipping_ZpToxBFwnR0W”

success = zip.OpenZip(zipFile)

saveExtraPath = 0
success = zip.AppendOneFileOrDir(filetozip,saveExtraPath)

success = zip.WriteZipAndClose

set zip = nothing

else

‘Create ZIP File

‘set ZIPObj = CreateObject(“BSZip.BSZipX”)
‘ZIPObj.CreateZIP zipfile

‘ZIPObj.OrderFile filetozip
‘ZIPObj.CompressFiles
‘ZIPObj.CloseZip
‘set ZipObj = nothing

set zip = CreateObject(“ChilkatZip2.ChilkatZip2”)
zip.UnlockComponent “ZIPPING_ZpToxBFwnR0W”

zip.NewZip zipFile

saveExtraPath = 0
zip.AppendOneFileOrDir filetozip,saveExtraPath

zip.WriteZipAndClose
set zip = nothing

end if
end if

if mode = 2 then

set oShell = CreateObject(“WScript.shell”)
oShell.run “cmd /C c:\jobs\gzip.exe “”” & filetozip & “”””, 0, true
Set oShell = nothing

‘Set objCab = CreateObject( “MakeCab.MakeCab.1” )
‘objCab.CreateCab CStr( filetozip & “.cab” ), False, False, False
‘objCab.AddFile CStr(filetozip), CStr(objFSO.GetFileName(filetozip))
‘objCab.CloseCab
‘set objCab = Nothing

end if

if delete = 1 then
if objFSO.FileExists(filetozip) = TRUE then
objFSO.DeleteFile filetozip
end if
end if

set objFSO = nothing
end function

function StripFileExt(sFileName)
if sFileName = “” Then Exit function
if InStr(1, sFileName, “.”) = 0 Then Exit function
StripFileExt = Right(sFileName, Len(sFileName) – InStrRev(sFileName, “.”) + 1)
End function

————————————————————————————————————————–

Script to backup the IIS:

call metabase.bat
cscript backup_ssl.vbs
cscript zip-dir-r.vbs E:\backup\IIS\metabase
cscript zip_logs.vbs
cscript delete_old_stuff.vbs
call fpfix.bat

————————————————————————————————————————-

Script to backup the metabase:

@ echo off
iisback /backup /b win12_iis_%date:~-4%_%date:~4,2%_%date:~7,2%
set folder=%date:~-4%_%date:~4,2%_%date:~7,2%
echo %folder%
mkdir E:\Backup\IIS\Metabase\%folder%
move C:\WINDOWS\system32\inetsrv\MetaBack\win12_iis_%date:~-4%_%date:~4,2%_%date:~7,2%.* E:\Backup\IIS\Metabase\%folder%\

————————————————————————————————————————–

Backing up SSL: backup_ssl.vbs

‘ ————————————————————-
‘ Export IS Certificates
‘ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘ Exports all the available certificates, used in IIS.
‘ ———————————————————
‘ ————————————————————
‘ Usage: Save this script as a VBS file and run like this:
‘        cscript.exe “c:\path\to\file.vbs”
‘ ————————————————————

‘————————————————————-
‘ Configuration variables
‘————————————————————-
‘ Export Folder – The folder must exist
Const ExportFolder = “E:\Backup\SSL”

‘ Export Password – Required on re-import
Const ExportPassword = “sslexport”

‘ IIS Server – The IIS Server to exports certificates of
Const IISServer = “LocalHost”

‘————————————————————-
‘ DO NOT edit below here
‘————————————————————-
Dim oIIS, oWeb, oCert
Dim iCount

Set oIIS = GetObject(“IIS://” & IISServer & “/W3SVC”)

For Each oWeb in oIIS
If LCase(oWeb.Class) = “iiswebserver” Then
Set oCert = CreateObject(“IIS.CertObj”)

oCert.InstanceName = “W3SVC/” & oWeb.Name

On Error Resume Next
oCert.Export ExportFolder & “\” & oWeb.ServerComment & “.pfx”, ExportPassword, True, True, False

If Err.Number = 0 Then
iCount = iCount + 1
WriteLogLine “Exporting SSL Certificate”, oWeb.ServerComment
End If

Err.Clear
On Error Goto 0

Set oCert = nothing
End If
Next

Set oIIS = Nothing
WriteLogLine “Total Certificates Exported”, iCount

Sub WriteLogLine(ByVal LogLineLabel, ByVal LogLineContent)
If (Len(LogLineLabel) = 0) And (Len(LogLineContent) = 0) Then
WScript.Echo “”
Else
LogLineLabel = Trim(Left(LogLineLabel, 30))
LogLineLabel = LogLineLabel & Replace(Space(30 – Len(LogLineLabel)), ” “, “.”)
WScript.Echo “> ” & LogLineLabel & “: ” & LogLineContent
End If
End Sub

————————————————————————————————————————–

Command to ZIP the logs: zip_logs.vbs

Const WinDir = “%WinDir%”
Const DeleteZip = 1

‘QUERY THE METABSE TO GET LOG FILE PATHS

Sub DoWork(Service, ServiceClass)
‘wscript.echo “Start Do Work”
Dim Key, IISOBJ, Entry

Key = “IIS://” & Servername &”/” & Service
on error resume next
Set IISOBJ = GetObject(Key)
if (Err <> 0) then
‘ WScript.Echo “Error unable to open IIS Metabase key : ” & Key & “, Err = ” & Err & _
‘     “, Desc = ” & Err.Description
exit sub
end if
‘WScript.Echo
ShowLogFolderStatus true, Service, IISOBJ
for each Entry in IISOBJ
‘wscript.echo Entry.Class
if (Entry.Class = ServiceClass) then
‘wscript.echo “Show Status” & Service & Entry.LogFileDirectory
ShowLogFolderStatus false, Service, Entry
end if
next
end sub

Servername = “LocalHost”

‘DETERMINE IF LOG FOLDER IS A VALID PATH

Sub ShowLogFolderStatus(Parent, Service, Entry)

on error goto 0
Dim FSO, Exists, LogDir, Name

Set FSO = CreateObject(“Scripting.FileSystemObject”)
if (Parent = true) then
Logdir = Entry.LogfileDirectory
else
Logdir = Entry.LogfileDirectory & “\” & Service & Entry.Name
‘wscript.echo LogDir
end if
LogDir = ExpandPath(LogDir)
‘wscript.echo LogDir
if (FSO.FolderExists(LogDir) = true) then
Exists = “Valid Path”
‘wscript.echo “valid path”
ZIPLogFiles LogDir, Entry.ServerComment
else
Exists = “** INVALID Path ***”
‘wscript.echo “invalid path”
end if
if (Parent = true) then
Name = Service
else
Name = Service & “\” & Entry.Name
end if
‘WScript.Echo FormatValue(Name, 11, true) & ” ” & FormatValue(Entry.ServerComment, 25, true) & _
‘    ” ” & FormatValue(LogDir, 40, true) & ” ” & Exists
Set FSo=Nothing
end Sub

‘DETERMEINE IF LOG FILE IS IN USE OR NOT'”

function ZIPLogFiles(path,domain)
on error goto 0
‘wscript.echo “ZIPing files at ” & path & ” for site ” & domain
dim fso
dim textstream
dim folder
dim zipfile

set TextSteam = CreateObject(“Scripting.FileSystemObject”)
set fso = CreateObject(“Scripting.FileSystemObject”)
set folder = fso.getfolder(path)

DACL “Add”, “FILE://” & folder.path,    “users:R”
wscript.echo folder.Path

‘wscript.echo Path
s = “”
for each file in folder.files
‘wscript.echo “Blah 2”
dtcreated = null
on error resume next
dtcreated = file.DateLastModified
‘wscript.echo dtcreated
‘ on error goto 0

if Right(file.path,3) <> “zip” then
zipfile = Path & “\” & Domain & “_” & Month(dtcreated) & Year(dtcreated) & “.zip” ‘”

‘wscript.echo “Trying to open ” & file.path

set TextFile = file.OpenAsTextStream(8, False)

if Err.Number = 0 then
‘wscript.echo “File is open”
‘file is not in use
TextFile.Close

AddToZIP zipfile, file.path, DeleteZIP
else
‘wscript.echo err.description
textFile.close
end if
end if
next

set folder = nothing
set TextStream = nothing
set fso = nothing

End Function

‘DELETE / ZIP LOG FILES

function AddToZip(zipfile,filetozip, delete)

‘First check to see if ZIP File Exists
dim ObjFSO
dim ZIPObj
set ObjFSO = CreateObject(“Scripting.FileSystemObject”)
‘wscript.echo zipfile

if objFSO.FileExists(zipfile) = TRUE then

‘open exist ZIP File, Add file to ZIP

set ZIPObj = CreateObject(“BSZip.BSZipX”)
ZIPObj.OpenZIP zipfile
‘ZIPObj.BasePath “c:\” ‘”
ZIPObj.OrderFile filetozip
ZIPObj.CompressFiles
ZIPObj.CloseZip
set ZipObj = nothing

else

‘Create ZIP File

set ZIPObj = CreateObject(“BSZip.BSZipX”)
ZIPObj.CreateZIP zipfile
‘ZIPObj.BasePath “c:\” ‘”
ZIPObj.OrderFile filetozip
ZIPObj.CompressFiles
ZIPObj.CloseZip
set ZipObj = nothing

end if

if delete = 1 then
if objFSO.FileExists(filetozip) = TRUE then
objFSO.DeleteFile filetozip
end if
end if

‘Set permissions on ZIP File
‘wscript.echo “Add permissions to ” & zipfile
DACL “Add”, “FILE://” & zipfile,    “users:R”

set objFSO = nothing
end function

‘EXPAND PATH FUNCTION

function ExpandPath(Path)
Dim key, ShellObject

if (left(Path, 8) = WinDir) then
Set ShellObject = WScript.CreateObject(“WScript.Shell”)
Key = “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PathName”
ExpandPath = ShellObject.RegRead(Key) & mid(Path,9)
Set ShellObject = Nothing
else
ExpandPath = Path
end if
end function

DoWork “W3SVC”, “IIsWebServer”
DoWork “MSFTPSVC”, “IIsFtpServer”
DoWork “SMTPSVC”, “IIsSmtpServer”

‘AddToZIP “c:\test\test.zip”,”c:\boot.ini”
‘AddToZIP “c:\test\test.zip”,”c:\sonicwall.exp”, 1
‘AddToZIP “c:\test\new.zip”,”c:\handynew.zip”, 0
‘AddToZip “c:\test\new.zip”,”c:\firstline.exe”, 1

‘#######################################################################
‘#######################################################################
‘                     START PERMISSIONS FUNCTIONS
‘#######################################################################
‘#######################################################################

‘ Set Filesystem and Registry ACL
‘ ===============================

‘ Author: Tobias Oetiker <oetiker@ee.ethz.ch>
‘         based on code by Nick Pearce, Craig Paterson and Rich Ellis

‘ Version: 1.1 — 2001/03/01

‘ Changes: 1.1 Handle non-existing registry keys gracefully.

‘ The purpose of this script is to allow ACL maniputlations
‘ to be performed by Microsoft Installer Packages (.msi)

‘ Add your ACL modification instructions to this script
‘ and integrate it as a Custom Action into the MSI.

‘ SETUP
‘ =====

‘ Note aclfix needs ADsSecurity.dll and RegObj.dll to work.
‘ You can get ADsSecurity from ADSI SDK 2.5 under (/ResourceKit/ADsSecurity.dll)

‘ Get the sdk from
http://msdownload.microsoft.com:80/msdownload/adsi/2.5/sdk/x86/en/Sdk.zip
‘ copy the dll to a place in your path and run

‘ RegObj.dll is included in Office 2000 SR2 or also available directly from
‘ MS for registered VB users.

‘ regsvr32 regobj.dll
‘ regsvr32 adssecurity.dll

‘ Usage with WISE for Windows Installer
‘ =====================================
‘ * add a copy of the two dlls to the package and install them somewhere
‘   below the INSTALLDIR of the package. Make sure you click Self register in
‘   the file property dialog

‘ * customize the dacl.vbs according to the needs of the application and add it
‘   to the msi somewhere below INSTALLDIR. Maybe next to the dlls

‘ * Add a custom action: Type:    Call Exe File
‘                        Source:  File on destination machine
‘                        Name:    DACL
‘                        InstDir: SystemFolder
‘                        Exe Cmd: wscript.exe “[!dacl.vbs]”
‘                        Sequenc: Install Execute Sequence (Before InstallFinalize)’
‘             Condition: NOT REMOVE~=”ALL”
‘                        I-S Opt: System Context
‘                        Process: Asynch, Wait at end of sequence

‘ TODO
‘ ====
‘ Using Add with the Registry creates working results, but somehow the ACEs are
‘ not in the proper order, and regedt32 complains when you look at them …
‘ it also seems that maybe I am not adding all the reg entries necessary …
‘ lack of docu … sorry … help appreciated. I guess it has something todo
‘ with inheritance …

‘ USAGE
‘ —–

‘ DACL function, url, “ace, ace, …”

‘ function — Add, Rm, Set

‘ url — FILE://….       change this File/Folder
‘        FILE://c:\home\   change this Folder and everything below
‘        FILE://c:\home\\  change this Folder and Folders below
‘        RGY://\HKEY_LOCAL_MACHINE\SOFTWARE    change this property
‘        RGY://…\  and RGY://\…\\ are the same as indiviual
‘                    registry values have no acls assigned

‘ ace — account:rights

‘ account — user or group

‘ rights (file) —  F – Full, C – Change, R – Read + Execute,
‘                   S – Read + Write + Execute, L – List

‘ rights (registry) —  F – Full, R – Read

‘ EXAMPLES
‘ ——–
‘ DACL “Add”, “FILE://w:\hello.txt”, “users:F,moetiker:F”
‘ DACL “Add”, “FILE://w:\hello\”,    “users:R,oetiker:F,moetiker:F”
‘ DACL “Rm”,  “FILE://w:\oops.txt”,  “everyone”
‘ DACL “Add”, “RGY://\HKEY_CURRENT_USER\SOFTWARE\ipswitch\ws_ftp\”, “users:F”
‘=============================================================================

‘=============================================================================
‘ Implementation
‘ ————–
Const ADS_ACEFLAG_INHERITED_ACE = &h10
Const ADS_ACETYPE_ACCESS_DENIED = &h1
Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &h5
Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &h6

Sub DumpAcl (url)
Dim sd, dacl, ace, sec
Print url
Set sec = CreateObject(“ADsSecurity”)
Set sd = sec.GetSecurityDescriptor( CStr(url) )
Set dacl = sd.DiscretionaryAcl
For Each ace In dacl
Print ”   ” & ace.trustee & _
”   Type: ” & ace.AceType & _
”   Mask: ” & ace.AccessMask & _
”   Flags: ” & ace.AceFlags
Next
End Sub

Sub AclEdit( action, url, acl, UType )
Dim acls, dacl, dummy, sec, ace, acea, usera, user, perm, acsplit, odacl
Dim sd

‘Const ADS_ACETYPE_ACCESS_ALLOWED = 0
‘Const ADS_ACETYPE_ACCESS_DENIED = 1
Const ADS_ACEFLAG_INHERIT_ACE = 2
Const ADS_ACEFLAG_SUB_NEW = 9

Print “Edit: ” & action & ” ” & url & ” ” & acl & ” ” & utype
acls = split(acl,”,”)

Set sec = CreateObject(“ADsSecurity”)
‘on error resume Next

‘ without cstr this will break … !!!
Set sd = sec.GetSecurityDescriptor( CStr(url) )

If ErrHandler(“Get SD for ” & url ) Then
On Error GoTo 0
Exit Sub
End If

Set dacl = sd.DiscretionaryAcl
dummy = dacl.AceCount ‘ this will throw an error if there is no DACL
If ErrHandler(“Get DACL for ” & url ) Then
On Error GoTo 0
Exit Sub
End If

‘ DumpAcl url

If action = “Rm” Or action = “Add” Then
‘ for Add we remove the ACEs for the folks which need new ones
For Each ace In dacl
acea = split (LCase(ace.trustee & “\” & ace.trustee),”\”)
If acea(0) <> “nt authority” Then
For Each user In acls
usera = split (LCase(user),”:”)
If acea(1) = usera(0) Then
Print “Remove ACE: ” & ace.trustee
dacl.RemoveACE ace
ErrHandler(“Remove ACE for ” & ace.trustee & _
” from ” & url)
End If
Next
End if
Next

ElseIf action = “Set” Then
For Each ace In dacl
acea = split (LCase(ace.trustee & “\” & ace.trustee),”\”)
If acea(0) <> “nt authority” Then
dacl.RemoveACE ace
ErrHandler(“Remove ACE for ” & ace.Trustee & ” from ” & url)
Print “Remove ACE: ” & ace.trustee
End if
Next
Else
Wscript.Echo “Unknown Action: ” & action
End If

If action = “Set” Or action = “Add” Then
For Each dummy In acls
acsplit = split (dummy,”:”)
user = acsplit(0)
perm = acsplit(1)
Print action & ” ” & utype & ” ” & user & ” ” & perm
Select Case UType
Case “DIRECTORY”
‘ folders require 2 aces for user (to do with inheritance)
AddFileAce url, dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_SUB_NEW
AddFileAce url, dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_INHERIT_ACE
‘sd.DiscretionaryAcl = odacl
‘ReorderDacl( Dacl )

case “FILE”
AddFileAce url, dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED,0
case “REGISTRY”
AddRegAce url, dacl, user, perm, _
ADS_ACETYPE_ACCESS_ALLOWED, _
ADS_ACEFLAG_INHERIT_ACE
End Select
Next

End If

sd.DiscretionaryAcl = dacl
If ErrHandler(“Get SD for ” & url ) Then
On Error GoTo 0
Exit Sub
End If

sec.SetSecurityDescriptor sd
If ErrHandler(“Get SD for ” & url ) Then
On Error GoTo 0
Exit Sub
End If

‘Set sd = Nothing
‘Set dacl = Nothing
‘Set sec = Nothing

‘ DumpAcl url

On Error GoTo 0
End Sub

Sub AddRegACE(dacl, user, perm , acetype, aceflags)
‘ Add registry ACE
Dim ace

Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const RIGHT_REG_READ = &H20019
Const RIGHT_REG_FULL = &HF003F

Set ace = CreateObject(“AccessControlEntry”)
ace.Trustee = user

Select Case UCase(perm)
‘ specified rights so far only include FC & R. Could be expanded though
Case “F”
ace.AccessMask = RIGHT_REG_FULL
Case “R”
ace.AccessMask = RIGHT_REG_READ
End Select

ace.AceType = acetype
ace.AceFlags = aceflags
dacl.AddAce ace
ErrHandler(“Add Ace for ” & user )

set ace=Nothing

End Sub

Sub AddFileAce(url, dacl,user, perm, acetype, aceflags)
‘ add ace to the specified dacl
Dim ace
Dim newdacl ‘As New AccessControlList
Dim ImpDenyDacl ‘As New AccessControlList
Dim ImpDenyObjectDacl ‘As New AccessControlList
Dim InheritedDacl ‘As New AccessControlList
Dim ImpAllowDacl ‘As New AccessControlList
Dim impAllowObjectDacl ‘As New AccessControlList
Dim inhAllowDacl
dim NewAce
dim sd
Dim sec ‘As New ADsSecurity

Set sec = CreateObject(“ADsSecurity”)
Set sd = sec.GetSecurityDescriptor( CStr(url) )

‘response.write fuck

set newAce = CreateObject(“AccessControlEntry”)
set newdacl = CreateObject(“AccessControlList”)
Set InheritedDacl = CreateObject(“AccessControlList”)
Set ImpAllowDacl = CreateObject(“AccessControlList”)
Set InhAllowDacl = CreateObject(“AccessControlList”)
Set ImpDenyObjectDacl = CreateObject(“AccessControlList”)
Set ImpAllowObjectDacl = CreateObject(“AccessControlList”)

Const RIGHT_LIST = &H4
Const RIGHT_READ = &H80000000
Const RIGHT_EXECUTE = &H20000000
Const RIGHT_WRITE = &H40000000
Const RIGHT_DELETE = &H10000
Const RIGHT_FULL = &H10000000
Const RIGHT_CHANGE_PERMS = &H40000
Const RIGHT_TAKE_OWNERSHIP = &H80000

Set ace = CreateObject(“AccessControlEntry”)
ace.Trustee = user

select case ucase(perm)
‘ specified rights so far only include FC & R. Could be expanded though
case “F”
ace.AccessMask = RIGHT_FULL
case “C”
ace.AccessMask = RIGHT_READ or RIGHT_WRITE Or _
RIGHT_EXECUTE or RIGHT_DELETE
case “R”
ace.AccessMask = RIGHT_READ or RIGHT_EXECUTE
case “S” ‘Special
ace.AccessMask = RIGHT_READ or RIGHT_WRITE or RIGHT_EXECUTE
case “L” ‘List
ace.AccessMask = RIGHT_LIST
end select

ace.AceType = acetype
ace.AceFlags = aceflags
dacl.AddAce ace


‘ Sift the DACL into 5 bins:
‘ Inherited Aces
‘ Implicit Deny Aces
‘ Implicit Deny Object Aces
‘ Implicit Allow Aces
‘ Implicit Allow object aces

‘response.write “Outputing old ACLls…<br>”

For Each ace In dacl

‘response.write ace.AccessMask
‘response.write ace.AceType
‘response.write ace.AceFlags
‘response.write ace.Flags & “<br>”


‘ Sort the original ACEs into their appropriate
‘ ACLs

‘Debug.Print ace.Trustee
dim ADS_ACETYPE_ACCESS_ALLOWED_count, ADS_ACETYPE_ACCESS_DENIED_count
dim ADS_ACETYPE_ACCESS_ALLOWED_OBJECT_count, ADS_ACETYPE_ACCESS_DENIED_OBJECT_count
dim ADS_ACEFLAG_INHERITED_ACE_count

If ((ace.AceFlags And ADS_ACEFLAG_INHERITED_ACE) = ADS_ACEFLAG_INHERITED_ACE) Then

‘ Don’t really care about the order of inherited aces.  Since we are
‘ adding them to the top of a new list, when they are added back
‘ to the Dacl for the object, they will be in the same order as
‘ they were originally.  Just a positive side affect of adding items
‘ of a LIFO ( Last In First Out) type list.

InheritedDacl.AddAce ace
ADS_ACEFLAG_INHERITED_ACE_count = ADS_ACEFLAG_INHERITED_ACE_count + 1
Else

‘ We have an Implicit ACE, lets put it the proper pool

Select Case ace.AceType
Case ADS_ACETYPE_ACCESS_ALLOWED

‘ We have an implicit allow ace

ImpAllowDacl.AddAce ace
ADS_ACETYPE_ACCESS_ALLOWED_count = ADS_ACETYPE_ACCESS_ALLOWED_count + 1

Case ADS_ACETYPE_ACCESS_DENIED

‘ We have a implicit Deny ACE

ImpDenyDacl.AddAce ace
ADS_ACETYPE_ACCESS_DENIED_count = ADS_ACETYPE_ACCESS_DENIED_count + 1

Case ADS_ACETYPE_ACCESS_ALLOWED_OBJECT

‘ We have an object allowed ace
‘ Does it apply to a property? or an Object?

impAllowObjectDacl.AddAce ace
ADS_ACETYPE_ACCESS_ALLOWED_OBJECT_count = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT_count + 1

Case ADS_ACETYPE_ACCESS_DENIED_OBJECT

‘ We have a object Deny ace

ImpDenyObjectDacl.AddAce ace
ADS_ACETYPE_ACCESS_DENIED_OBJECT_count = ADS_ACETYPE_ACCESS_DENIED_OBJECT_count+1
Case Else

End Select
End If
Next


if ADS_ACETYPE_ACCESS_DENIED_count > 0 then
For Each ace In ImpDenyDacl
newdacl.AddAce ace
Next
end if

‘ Implicit Deny Object

if ADS_ACETYPE_ACCESS_DENIED_OBJECT_count > 0 then
For Each ace In ImpDenyObjectDacl
newdacl.AddAce ace
Next
end if

‘ Implicit Allow

if ADS_ACETYPE_ACCESS_ALLOWED_count > 0 then
For Each ace In ImpAllowDacl
newdacl.AddAce ace
Next
end if

‘ Implicit Allow Object

if ADS_ACETYPE_ACCESS_ALLOWED_OBJECT_count > 0 then
For Each ace In impAllowObjectDacl
newdacl.AddAce ace
Next
end if

‘ Inherited Aces

if ADS_ACEFLAG_INHERITED_ACE_count > 0 then
For Each ace In InheritedDacl
newdacl.AddAce ace
Next
end if

sd.DiscretionaryAcl = newdacl

‘response.write “Outputing new ACLls…<br>”
For Each ace In newdacl

‘ response.write ace.AccessMask
‘response.write ace.AceType
‘response.write ace.AceFlags
‘response.write ace.Flags & “<br>”
Next
‘Debug.Print Date


‘ Set the appropriate revision level
‘ for the DACL

newdacl.AclRevision = dacl.AclRevision

‘ Replace the Security Descriptor

sec.SetSecurityDescriptor sd

ErrHandler(“Add Ace for ” & user )

set ace=Nothing

End Sub

Sub DACL(action,url,acl)
Dim argarry, utype, upath, walk, ftype, fs, rfldr, file, sfldr
Dim ro, rk, regval,skey
argarry = split(url,”://”)
utype = argarry(0)
upath = argarry(1)

Print “Action: ” & action & ” ” & utype & “–” & upath & ” ” & acl

If Right(upath,2) = “\\” Then
walk = “\\” ‘ folders only
upath = Left(upath, Len(upath)-2)
ElseIf Right(upath,1) = “\” Then
walk = “\” ‘ files and folders
upath = left(upath, len(upath)-1)
End If

If utype = “FILE” Then

Set fs=CreateObject(“Scripting.FileSystemObject”)
Print “—” & upath
If fs.FileExists(upath) Then
Set rfldr=fs.GetFile(upath)
ftype = “FILE” ‘directory
ElseIf fs.FolderExists(upath) Then
Set rfldr=fs.GetFolder(upath)
ftype = “DIRECTORY” ‘file
Else
‘ its neither file nor folder … maybe it does not exist …
wscript.echo “Can’t find ” & upath
Exit Sub
End If

AclEdit action, “FILE://” & rfldr.path, acl, ftype

If ftype = “FILE” Then ‘if this is a file our work is done
Exit Sub
End If

If walk = “\” then
For Each file In rfldr.files
AclEdit action, “FILE://” & file , acl, “FILE”
Next
End If

if walk = “\” or walk = “\\” then
for each sfldr in rfldr.subfolders
DACL action, “FILE://” & sfldr & walk, acl
next
end if

elseif utype = “RGY” Then

Set ro = CreateObject(“RegObj.Registry”)
on error resume Next
Set rk = ro.RegKeyFromString( upath )
If ErrHandler(“Get Registry Key ” & upath ) Then
On Error GoTo 0
Exit Sub
End If

AclEdit action, “RGY://” & rk.FullName, acl,”REGISTRY”

if walk = “\” or walk = “\\” then
for each skey in rk.Subkeys
DACL action,”RGY://” &  skey.FullName & walk, acl
next
end If

else
Wscript.Echo “Unsupported URL Type: ” & utype
end If
On Error GoTo 0

End Sub

Function ErrHandler(what)
If Err.Number > 0 Then
‘Response.Write what & ” Error ” & Err.Number & “: ” & Err.Description
Err.Clear
‘Return True
End If
ErrHandler = False
End Function

Sub Print(Str)
‘strip when debugging
‘wscript.echo Str
End Sub

‘#######################################################################
‘#######################################################################
‘                      END PERMISSIONS FUNCTIONS
‘#######################################################################
‘#######################################################################

————————————————————————————————————————-

Deleting the old logs: delete_old_stuff.vbs

‘ VB Script Document

arFiles = Array()
set fso = createobject(“scripting.filesystemobject”)

on error resume next
‘DeleteFiles “C:\windows\system32\inetsrv\metaback”, 7, TRUE
DeleteFiles “c:\windows\logfiles\HTTPERR”,7, TRUE
DeleteFiles “C:\ColdFusion8\Mail”,1, TRUE
DeleteFiles “C:\temp”,3, TRUE
DeleteFiles “C:\windows\temp”,3, TRUE
DeleteFiles “E:\backup\mssql”,30, TRUE

nDeleted = 0

for n = 0 to ubound(arFiles)
‘=================================================
‘ Files deleted via FSO methods do *NOT* go to the recycle bin!!!
‘=================================================
on error resume next ‘in case of ‘in use’ files…
‘wscript.echo arFiles(n).path
arFiles(n).delete true
if err.number <> 0 then
wscript.echo “Unable to delete: ” & arFiles(n).path
else
nDeleted = nDeleted + 1
end if
on error goto 0
next

WScript.Echo nDeleted & ” of ” & ubound(arFiles)+1 _
& ” eligible files were deleted”

‘ Don’t do the delete while you still are looping through a
‘ file collection returned from the File System Object (FSO).
‘ The collection may get mixed up.
‘ Create an array of the file objects to avoid this.

sub DeleteFiles(sPath,vKillDays,bIncludeSubFolders)

wscript.echo sPath
vkilldate = now() – vKillDays

on error resume next
‘select files to delete and add to array…

set folder = fso.getfolder(sPath)
set files = folder.files

for each file in files
‘ uses error trapping around access to the
‘ Date property just to be safe

dtlastmodified = null
on error resume Next
dtlastmodified = file.datelastmodified
on error goto 0
if not isnull(dtlastmodified) Then
if dtlastmodified < vKillDate then
count = ubound(arFiles) + 1
redim preserve arFiles(count)
set arFiles(count) = file
end if
end if
next

if bIncludeSubFolders then
for each fldr in folder.subfolders
DeleteFiles fldr.path,vKillDays,bIncludeSubFolders
next
end if

end sub

————————————————————————————————————————–

Scripts to change the MSSQL logical servers in Hsphere panel:

java -Xms64M -Xmx256M psoft.hsphere.tools.ChangeLServerId -a 5128585 –from 147 –to 71

java -Xms64M -Xmx256M psoft.hsphere.tools.PhysicalCreator -rg mysql -co -lid 71 -accs 5128585

————————————————————————————————————————–

Isapi rewrite Test Script:

In this script the domain is pointing to WWW of the domain.

RewriteCond %{HTTP:Host} ^domaint\.com$
RewriteRule (.*) http\://www\.domain\.com$1 [NC,R=301]

————————————————————————————————————————–

Script to Connect the MYSQL Database:

<?php
$link = mysql_connect(‘<server>’, ‘<username>’, ‘<password>’);
if (!$link) {
die(‘Could not connect: ‘ . mysql_error());
}
echo ‘Connected successfully’;
mysql_select_db(<database>);
?>

————————————————————————————————————————-

ASP Treeview test script:

<html>
<head><title>ASP TreeView Demos</title>
</head>
<body>
<b>ASP TreeView Demos</b>
<ul>
<li>
Load TreeNodes from a folder (like windows explorer)
<ul>
<li><a href=”explorer.asp”>View</a></li>
<li><a href=”source.asp?file=explorer.asp”>Source Code</a></li>
</ul>
</li>
<li>
Load TreeNodes from a database table
<ul>
<li><a href=”demoDB.asp”>View</a></li>
<li><a href=”source.asp?file=demodb.asp”>Source Code</a></li>
</ul>

</li>
<li>
Adding TreeNodes dynamically
<ul>
<li><a href=”demo2.asp”>Simple Demo</a></li>
<li><a href=”demo.asp”>Advanced Demo</a></li>
</ul>
</li>

</ul>
</body>
</html>

————————————————————————————————————————

Comments
  1. Thanks to my father who informed me on the topic of this weblog, this weblog is genuinely amazing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s