created folder structure

This commit is contained in:
Jonathan Branan 2022-09-13 11:37:49 -05:00
commit 251dbfb0eb
112 changed files with 16067 additions and 0 deletions

BIN
README.md Normal file

Binary file not shown.

View File

@ -0,0 +1,10 @@
@echo off
c:\
cd "C:\Users\jbranan\Desktop\Batch to call multiple things"
start wireshark.bat
start procdump.bat
start procmon.bat
timeout /T 135
start killwireshark.bat
start killprocmon.bat
exit

View File

@ -0,0 +1,3 @@
@echo off
taskkill /IM "Procmon64.exe" /F
exit

View File

@ -0,0 +1,3 @@
@echo off
taskkill /IM "Wireshark.exe" /F
exit

View File

@ -0,0 +1,6 @@
@echo off
c:\
cd "C:\Users\jbranan\Desktop\Batch to call multiple things\procdump"
procdump.exe -n 1 -ma cftpstes.exe "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps" -accepteula
timeout /T 15
exit

View File

@ -0,0 +1,75 @@
Sysinternals Software License Terms
These license terms are an agreement between Sysinternals (a wholly owned subsidiary of Microsoft Corporation) and you. Please read them. They apply to the software you are downloading from technet.microsoft.com/sysinternals, which includes the media on which you received it, if any. The terms also apply to any Sysinternals
* updates,
* supplements,
* Internet-based services,
* and support services
for this software, unless other terms accompany those items. If so, those terms apply.
BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE.
If you comply with these license terms, you have the rights below.
Installation and User Rights
You may install and use any number of copies of the software on your devices.
Scope of License
The software is licensed, not sold. This agreement only gives you some rights to use the software. Sysinternals reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not
* work around any technical limitations in the software;
* reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;
* make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;
* publish the software for others to copy;
* rent, lease or lend the software;
* transfer the software or this agreement to any third party; or
* use the software for commercial software hosting services.
Sensitive Information
Please be aware that, similar to other debug tools that capture “process state” information, files saved by Sysinternals tools may include personally identifiable or other sensitive information (such as usernames, passwords, paths to files accessed, and paths to registry accessed). By using this software, you acknowledge that you are aware of this and take sole responsibility for any personally identifiable or other sensitive information provided to Microsoft or any other party through your use of the software.
Documentation
Any person that has valid access to your computer or internal network may copy and use the documentation for your internal, reference purposes.
Export Restrictions
The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting .
Support Services
Because this software is "as is," we may not provide support services for it.
Entire Agreement
This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.
Applicable Law
United States . If you acquired the software in the United States , Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.
Outside the United States . If you acquired the software in any other country, the laws of that country apply.
Legal Effect
This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.
Disclaimer of Warranty
The software is licensed "as-is." You bear the risk of using it. Sysinternals gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, sysinternals excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
Limitation on and Exclusion of Remedies and Damages
You can recover from sysinternals and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages.
This limitation applies to
* anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and
* claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.
It also applies even if Sysinternals knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.
Please note: As this software is distributed in Quebec , Canada , some of the clauses in this agreement are provided below in French.
Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Sysinternals n'accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d'adéquation à un usage particulier et d'absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Sysinternals et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne :
tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d'une autre faute dans la limite autorisée par la loi en vigueur.
Elle s'applique également, même si Sysinternals connaissait ou devrait connaître l'éventualité d'un tel dommage. Si votre pays n'autorise pas l'exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l'exclusion ci-dessus ne s'appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d'autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.

View File

@ -0,0 +1,4 @@
@echo off
c:
cd "C:\Users\jbranan\Desktop\Batch to call multiple things\procmon"
procmon.exe /accepteula /Nofilter /Quiet /BackingFile "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps\log.PML" /Minimized

View File

@ -0,0 +1,75 @@
Sysinternals Software License Terms
These license terms are an agreement between Sysinternals (a wholly owned subsidiary of Microsoft Corporation) and you. Please read them. They apply to the software you are downloading from technet.microsoft.com/sysinternals, which includes the media on which you received it, if any. The terms also apply to any Sysinternals
* updates,
* supplements,
* Internet-based services,
* and support services
for this software, unless other terms accompany those items. If so, those terms apply.
BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE.
If you comply with these license terms, you have the rights below.
Installation and User Rights
You may install and use any number of copies of the software on your devices.
Scope of License
The software is licensed, not sold. This agreement only gives you some rights to use the software. Sysinternals reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not
* work around any technical limitations in the software;
* reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;
* make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;
* publish the software for others to copy;
* rent, lease or lend the software;
* transfer the software or this agreement to any third party; or
* use the software for commercial software hosting services.
Sensitive Information
Please be aware that, similar to other debug tools that capture “process state” information, files saved by Sysinternals tools may include personally identifiable or other sensitive information (such as usernames, passwords, paths to files accessed, and paths to registry accessed). By using this software, you acknowledge that you are aware of this and take sole responsibility for any personally identifiable or other sensitive information provided to Microsoft or any other party through your use of the software.
Documentation
Any person that has valid access to your computer or internal network may copy and use the documentation for your internal, reference purposes.
Export Restrictions
The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting .
Support Services
Because this software is "as is," we may not provide support services for it.
Entire Agreement
This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.
Applicable Law
United States . If you acquired the software in the United States , Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.
Outside the United States . If you acquired the software in any other country, the laws of that country apply.
Legal Effect
This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.
Disclaimer of Warranty
The software is licensed "as-is." You bear the risk of using it. Sysinternals gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, sysinternals excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
Limitation on and Exclusion of Remedies and Damages
You can recover from sysinternals and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages.
This limitation applies to
* anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and
* claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.
It also applies even if Sysinternals knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.
Please note: As this software is distributed in Quebec , Canada , some of the clauses in this agreement are provided below in French.
Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Sysinternals n'accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d'adéquation à un usage particulier et d'absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Sysinternals et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne :
tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d'une autre faute dans la limite autorisée par la loi en vigueur.
Elle s'applique également, même si Sysinternals connaissait ou devrait connaître l'éventualité d'un tel dommage. Si votre pays n'autorise pas l'exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l'exclusion ci-dessus ne s'appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d'autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.

Binary file not shown.

View File

@ -0,0 +1,4 @@
@echo off
c:
cd "C:\Program Files\Wireshark"
wireshark -k -i Ethernet0 -f "host 192.168.102.10" -a duration:120 -w "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps\capture.pcapng"

10
bat/call all.bat Normal file
View File

@ -0,0 +1,10 @@
@echo off
c:\
cd "C:\Users\jbranan\Desktop\Batch to call multiple things"
start wireshark.bat
start procdump.bat
start procmon.bat
timeout /T 135
start killwireshark.bat
start killprocmon.bat
exit

3
bat/dmz thread dupmp.bat Normal file
View File

@ -0,0 +1,3 @@
C:
cd “C:\Program Files\GlobalSCAPE\DMZ Gateway\bin”
DMZGatewayServerService.exe -d “C:\Program Files\GlobalSCAPE\DMZ Gateway\conf\DMZGatewayServerService.conf”

View File

@ -0,0 +1,4 @@
pushd "%~d0\"
pushd "%~dp0\"
"%~dp0procdump.exe" -n 3 -s 60 -ma -accepteula cftpsai.exe .\
pause

View File

@ -0,0 +1,4 @@
pushd "%~d0\"
pushd "%~dp0\"
"%~dp0procdump.exe" -n 3 -s 60 -ma -accepteula cftpstes.exe .\
pause

75
bat/dump-crash/Eula.txt Normal file
View File

@ -0,0 +1,75 @@
Sysinternals Software License Terms
These license terms are an agreement between Sysinternals (a wholly owned subsidiary of Microsoft Corporation) and you. Please read them. They apply to the software you are downloading from technet.microsoft.com/sysinternals, which includes the media on which you received it, if any. The terms also apply to any Sysinternals
* updates,
* supplements,
* Internet-based services,
* and support services
for this software, unless other terms accompany those items. If so, those terms apply.
BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE.
If you comply with these license terms, you have the rights below.
Installation and User Rights
You may install and use any number of copies of the software on your devices.
Scope of License
The software is licensed, not sold. This agreement only gives you some rights to use the software. Sysinternals reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not
* work around any technical limitations in the software;
* reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;
* make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;
* publish the software for others to copy;
* rent, lease or lend the software;
* transfer the software or this agreement to any third party; or
* use the software for commercial software hosting services.
Sensitive Information
Please be aware that, similar to other debug tools that capture “process state” information, files saved by Sysinternals tools may include personally identifiable or other sensitive information (such as usernames, passwords, paths to files accessed, and paths to registry accessed). By using this software, you acknowledge that you are aware of this and take sole responsibility for any personally identifiable or other sensitive information provided to Microsoft or any other party through your use of the software.
Documentation
Any person that has valid access to your computer or internal network may copy and use the documentation for your internal, reference purposes.
Export Restrictions
The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting .
Support Services
Because this software is "as is," we may not provide support services for it.
Entire Agreement
This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.
Applicable Law
United States . If you acquired the software in the United States , Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.
Outside the United States . If you acquired the software in any other country, the laws of that country apply.
Legal Effect
This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.
Disclaimer of Warranty
The software is licensed "as-is." You bear the risk of using it. Sysinternals gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, sysinternals excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
Limitation on and Exclusion of Remedies and Damages
You can recover from sysinternals and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages.
This limitation applies to
* anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and
* claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.
It also applies even if Sysinternals knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.
Please note: As this software is distributed in Quebec , Canada , some of the clauses in this agreement are provided below in French.
Remarque : Ce logiciel étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Sysinternals n'accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d'adéquation à un usage particulier et d'absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Sysinternals et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne :
tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d'une autre faute dans la limite autorisée par la loi en vigueur.
Elle s'applique également, même si Sysinternals connaissait ou devrait connaître l'éventualité d'un tel dommage. Si votre pays n'autorise pas l'exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l'exclusion ci-dessus ne s'appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d'autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.

View File

@ -0,0 +1,7 @@
How to capture Crash/Hang dumps:
Hang Dumps:
Use "Admin Console Hang Dump.bat" and "EFT Service Hang Dump.bat".
Crash Dump:
Merge the WER.reg registry key and make a folder at C:\dumps if you wish to capture crash dumps. You can edit the path of the dumps folder in the WER.reg file or edit directly in the registry after merging it. Make sure it is done for both services.

BIN
bat/dump-crash/WER.reg Normal file

Binary file not shown.

BIN
bat/dump-crash/procdump.exe Normal file

Binary file not shown.

3
bat/killprocmon.bat Normal file
View File

@ -0,0 +1,3 @@
@echo off
taskkill /IM "Procmon64.exe" /F
exit

3
bat/killwireshark.bat Normal file
View File

@ -0,0 +1,3 @@
@echo off
taskkill /IM "Wireshark.exe" /F
exit

6
bat/procdump.bat Normal file
View File

@ -0,0 +1,6 @@
@echo off
c:\
cd "C:\Users\jbranan\Desktop\Batch to call multiple things\procdump"
procdump.exe -n 1 -ma cftpstes.exe "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps" -accepteula
timeout /T 15
exit

4
bat/procmon.bat Normal file
View File

@ -0,0 +1,4 @@
@echo off
c:
cd "C:\Users\jbranan\Desktop\Batch to call multiple things\procmon"
procmon.exe /accepteula /Nofilter /Quiet /BackingFile "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps\log.PML" /Minimized

4
bat/wireshark.bat Normal file
View File

@ -0,0 +1,4 @@
@echo off
c:
cd "C:\Program Files\Wireshark"
wireshark -k -i Ethernet0 -f "host 192.168.102.10" -a duration:120 -w "C:\Users\jbranan\Desktop\Batch to call multiple things\dumps\capture.pcapng"

View File

@ -0,0 +1,59 @@
function rdgw {
Write-Host "Logging on to the Arcus Management Server..."
sft rdp --via rdgwbastion ArcusSupport
}
function list {
Write-Host "Listing servers..."
sft list-servers
}
function help {
write-host "rdgw - Use to connect to the Arcus domain management server."
write-host "list - List of all servers you have access to in the environment."
write-host "search - String search. I suggest using this with the clients 6 digit identifier to filter all servers in their environment."
write-host "legacy - Use to log into non arcus servers. There are not very many left..."
write-host "arcus - Use to log into arcus servers. There are too many..."
write-host "wfh - Use to log into arcus servers from home."
}
function search {
param(
[Parameter(Mandatory=$False)][string]$server
)
if ($server)
{
Write-Host "Listing servers..."
sft list-servers | findstr -i $server
}
else{
$server = Read-Host -Prompt "I need the client's 6 digit identifier. Example'Supp02'"
Write-Host "Listing servers..."
sft list-servers | findstr -i $server }
$Results = Read-Host -Prompt 'How do you want to connect? Use help if you are unsure.
arcus,legacy or wfh?'
invoke-expression $Results
}
function legacy {
Write-Host 'Connecting to legacy...'
$legacy = Read-Host -Prompt 'Server name?'
Write-Host "sft rdp $legacy"
sft rdp $legacy
}
function arcus {
Write-Host 'Connecting to Arcus...'
$bastion = Read-Host -Prompt 'Bastion name?'
$vm = Read-Host -Prompt 'Server name?'
Write-Host "sft rdp --via $bastion $vm"
sft rdp --via $bastion $vm
}
function wfh {
Write-Host 'Connecting from home...'
$bastion = Read-Host -Prompt 'Bastion name?'
$vm = Read-Host -Prompt 'Server name?'
Write-Host "sft rdp --via sft --via $bastion $vm"
sft rdp --via sft --via $bastion $vm
}

View File

@ -0,0 +1,76 @@
Why this is important:
Most of our on prem clients intend to keep their servers. Our company has more room to expand its clients in using our Arcus platform. There is generally alot of confustion on how to connect to our cloud servers and what the difference between legacy and Arcus servers. This will not be guide to setting up SFT but rather how to use it along with its caveats explained.
Notes:
-We have information of how to set up SFT here:
https://confluence.globalscape.com/display/PS/Import+EFT+to+Arcus
-Here is our RDG portal for our clients:
https://rdg.cloud.globalscape.com/RDWeb/Pages/en-US/login.aspx
-Here is my simple script with an evironment already set:
What we will go over:
-Setting the environment
-Looking for a server
-What a bastion is
-How to connect to Arcus from your vpn at home
-Where to put the script
-What commands are available in the script
-How to navigate the script
Setting the environment
In order to connect to the servers you normally will have to enter this command:
$env:HTTPS_PROXY = 'http://10.0.0.14:8080'
This will set the proxy so the traffic can actually be routed to the servers. This is automatically declared when you use my script so you will never manually have to do this.
Looking for a server
You are able to use the following command to list the servers:
sft list-servers
This will display a long list of servers. After you get used to it, you normally will be able to find what you are looking for pretty quickly. If you know what the host name of the server is, or you have an idea of what string of letters will return the server you are looking for, you can pipe the output of sft list-servers to find string. Like this:
sft list-servers | findstr -i <string>
The main problem with this is that most of the legacy servers have odd hostnames that have nothing to do with the company. this is where our Excel spread sheet might come in handy. This contains most of the legacy servers.
R:\jbranan\Cloud Servers.xlsx
What is a bastion?
A bastion allows our company to keep tract of the tasks completed on our clients servers. This provides some legal protection should something go wrong, and also provide accountablity. Logging into a server via a bastion is not optional for Arcus and it is not an option for legacy. When you do a SFT list servers, these servers normally have "bast" in the name.
Connection to Arcus servers via a VPN
When at home you will need to use the following format:
sft rdp --via sft --via (bastion) (server)
Note: This should only be used when you are WFH and need to log into an Arcus cloud server.
What location should I put the script?
You will want to put the WHOLE folder in your documents folder for powershell to reconize it. The path should be like this:
%userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
C:\Users\jbranan\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If you don't know where this is just hit WindowsKey + R, type %userprofile% and hit enter. This will show you where your home path is.
What commands are avaiable in the script?
list- Displays a list of the servers, legacy, MIX or Arcus.
search- Allows you to specify a string to search the list of servers. You may pass a string parameter. ex. 'search supp02'
rdgw- Connects to the RDGW server. This is normally used for password resets for clients.
legacy- Cloud servers that are not used in conjuction with a bastion. We are winding down support for them.
arcus- Our current cloud offering. Requires a bastion to login.
How to Navigate the script
You generally want to start with the search command and search for the name or a short string.
For expample, search com or one so that the command can return the host name. A search for "com" in this case will not return a server but a search for "one" will.:
Company one's cloud server hostname: cone0003
Company one's cloud server bastion hostname: conebast0001
In order to cancel a command hit ctrl + C. This will allow you to back out of a command and use a different one. For instance, say you connected the previous day to a cloud server and have hostname already. You can proceed with the legacy command and skip the list and search commands.

View File

@ -0,0 +1,28 @@
import requests
# Authentication
baseURL = "http://192.168.4.14:4450/admin"
user = "a"
password = "QjIlmT4H"
authURL = f"{baseURL}/v1/authentication"
body = {"userName": user, "password": password, "authType": "EFT"}
r1 = requests.post(authURL, json=body)
eftresp1 = r1.json()
# print(r1.status_code)
# print(eftresp1)
authheader ={"Authorization": f"EFTAdminAuthToken {eftresp1['authToken']}"}
# print(authheader)
# Get Server Info
getserverURL = f"{baseURL}/v2/server"
r2 = requests.get(getserverURL, headers=authheader)
eftresp2 = r2.json()
# print(r2.status_code)
print(eftresp2)
#Get Server Metrics
getservermetricsURL = f"{baseURL}/v2/server/metrics"
r3 = requests.get(getservermetricsURL, headers=authheader)
eftresp3 = r3.json()
# print(r3.status_code)
print(eftresp3)

View File

@ -0,0 +1,66 @@
import requests
import json
# Authentication
baseURL = "http://192.168.4.14:4450/admin"
user = "a"
password = "QjIlmT4H"
authURL = f"{baseURL}/v1/authentication"
body = {"userName": user, "password": password, "authType": "EFT"}
r1 = requests.post(authURL, json=body)
eftresp1 = r1.json()
authheader ={"Authorization": f"EFTAdminAuthToken {eftresp1['authToken']}"}
# Get Site ID
sitename = 'My Site'
getsiteURL = f"{baseURL}/v2/sites"
r2 = requests.get(getsiteURL, headers=authheader)
eftresp2 = r2.json()
# print(r2.status_code)
for index, site in enumerate(eftresp2["data"]):
if site["attributes"]["name"] == sitename:
print(f'Name: {eftresp2["data"][index]["attributes"]["name"]} Site ID: {eftresp2["data"][index]["id"]}')
siteid = eftresp2["data"][index]["id"]
break
#Get User ID
username = 'b'
getusersURL = f"{baseURL}/v2/sites/{siteid}/users"
r3 = requests.get(getusersURL, headers=authheader)
eftresp3 = r3.json()
for index, user in enumerate(eftresp3["data"]):
if user["attributes"]["loginName"] == username:
print(f'User ID: {eftresp3["data"][index]["id"]}')
userid = eftresp3["data"][index]["id"]
break
#Get Template id
desttemplate = 'Default Settings'
gettemplateURL = f"{baseURL}/v2/sites/{siteid}/users"
r4 = requests.get(gettemplateURL, headers=authheader)
eftresp4 = r4.json()
for index, user in enumerate(eftresp4["data"]):
if eftresp4["data"][index]["relationships"]["userTemplate"]["data"]["meta"]["name"] == desttemplate:
print(f'Template ID: {eftresp4["data"][index]["relationships"]["userTemplate"]["data"]["id"]}')
usertemplateid = eftresp4["data"][index]["relationships"]["userTemplate"]["data"]["id"]
break
# Data to change, usertemplateid is the destination template
payload = {
"data": {
"type": "userTemplate",
"relationships": {
"userTemplate": {
"data": {
"id": usertemplateid
}
}
}
}
}
#Push the change
patchuserURL = f"{baseURL}/v2/sites/{siteid}/users/{userid}"
r5 = requests.patch(patchuserURL, json.dumps(payload), headers=authheader)
eftresp5 = r5.json()
print(r5.status_code)

View File

@ -0,0 +1,37 @@
import requests
# Authentication
baseURL = "http://192.168.4.14:4450/admin"
user = "a"
password = "QjIlmT4H"
authURL = f"{baseURL}/v1/authentication"
body = {"userName": user, "password": password, "authType": "EFT"}
r1 = requests.post(authURL, json=body)
eftresp1 = r1.json()
# print(r1.status_code)
# print(eftresp1)
authheader ={"Authorization": f"EFTAdminAuthToken {eftresp1['authToken']}"}
# print(authheader)
# Get Site ID
sitename = 'test.jbranan.com'
getsiteURL = f"{baseURL}/v2/sites"
r2 = requests.get(getsiteURL, headers=authheader)
eftresp2 = r2.json()
# print(r2.status_code)
for index, site in enumerate(eftresp2["data"]):
if site["attributes"]["name"] == sitename:
print(f'Name: {eftresp2["data"][index]["attributes"]["name"]} ID: {eftresp2["data"][index]["id"]}')
siteid = eftresp2["data"][index]["id"]
print(eftresp2)
getsiteinfoURL = f"{baseURL}/v2/sites/{siteid}/users"
r3 = requests.get(getsiteinfoURL, headers=authheader)
eftresp3 = r3.json()
print(r3.status_code)
# for index, site in enumerate(eftresp2["data"]):
# if site["attributes"]["name"] == sitename:
# print(f'Name: {eftresp2["data"][index]["attributes"]["name"]} ID: {eftresp2["data"][index]["id"]}')
# siteid = eftresp2["data"][index]["id"]
print(eftresp3)

View File

@ -0,0 +1,11 @@
SELECT TOP 3 UserName, Count(*) As SuccessConnections
FROM tbl_Authentications
WHERE resultID = 0 AND protocol <> 'Administration' AND Time_stamp >= DATEADD(minute,-1440,GetDate())
GROUP BY UserName
ORDER BY SuccessConnections DESC
SELECT TOP 3 UserName, Count(*) As FailedConnections
FROM tbl_Authentications
WHERE resultID = 1 AND protocol <> 'Administration' AND Time_stamp >= DATEADD(minute,-1440,GetDate())
GROUP BY UserName
ORDER BY FailedConnections DESC

View File

@ -0,0 +1,278 @@
-- EFT Purging Script
-- Goal: Allow customers to purge data from EFT's ARM database
--USAGE
/*
1. Run recreate_foreign_keys.sql next, as it will fix any problems if present (see notes in that script)
2. Run index_foreign_keys_and_time_stamps.sql first, as that will improve purge performance
3. Modify the purge date if desired. -30 means purge all records older than 30 days
3a. To change: search for "SET @stopTime = DATEADD(DAY, -30, GETDATE())"
3b. A value of -0 means ALL records
3c. Alternatively, you can pass in an exact date range:
3ci. Search for EXEC sp_PurgeEFTTransactions NULL, NULL, 1000000, 1
3cii. Enter date and times in quotes as such: EXEC sp_PurgeEFTTransactions '2019-01-20 18:11:00', '2019-04-01 07:50:00', 1000000, 1
4. Modify "USE EFTDB" below if your database name is different
5. Make sure you database isn't actively recording data (disable ARM reporting in EFT temporarily)
6. Execute the script (it can take several hours for databases with hundreds of millions of records)
*/
-- Change Log:
-- 0.1: Set batch size at 100,000
-- Removed SELECT and extra PRINT statements.
-- 0.2: Changed to purge up to records greater than 30 days old
-- 0.3: Modified script to not assume cascading deletes and to
-- explicitly delete from all tables
-- Modified script to default 'purgesize' to 10,000
-- instead of 1,000
-- 0.4 Added AS2 and SAT purging
-- 0.5 Subset table wasn't being dropped.
-- 0.6 Changed to all static calls instead of dynamic.
-- 0.7 Changed purge size to 1,000,000
-- 0.8 Brought back cascade deletes to speed up performance
--USE EFTDB
-- Include minutes/seconds
PRINT 'Script started at: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109)
-- PRINT 'Script started at: ' + CAST(CURRENT_TIMESTAMP AS NVARCHAR)
-- USE EFTDB741315
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFTTransactionsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFTTransactionsVersion
GO
CREATE PROCEDURE sp_PurgeEFTTransactionsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Script Version 0.6'
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFTTransactions') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFTTransactions
END
GO
-- By default, this procedure will purge data from 1970 to 60 days ago.
CREATE PROCEDURE sp_PurgeEFTTransactions @startTime datetime = NULL,
@stopTime datetime = NULL,
@purgeSize int = NULL,
@debug bit = 0
AS
BEGIN
DECLARE @r INT;
DECLARE @ErrMsg nvarchar(4000);
DECLARE @ErrSeverity int;
DECLARE @deletedTransactions TABLE(ParentTransactionID numeric(18,0));
EXEC sp_PurgeEFTTransactionsVersion
-- Delete tblTransactions records and sub-tables
SET NOCOUNT ON
IF @startTime IS NULL BEGIN
set @startTime = '19700101 00:00:00'
END
IF @stopTime IS NULL BEGIN
SET @stopTime = DATEADD(DAY, -60, GETDATE())
END
IF @purgeSize IS NULL BEGIN
set @purgeSize = 1000000
END
-- Temporarily remove the ParentTransactionID -> TransactionID constraint
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
-- First, delete from tbl_Actions separately since potential circular cascade delete with tbl_EventRules
IF @debug=1 PRINT 'Deleting from tbl_Actions: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109);
BEGIN TRY
BEGIN TRANSACTION
-- Clear the temp table
DELETE @deletedTransactions
-- First, drop constraint
ALTER TABLE tbl_Actions DROP CONSTRAINT FK_tbl_Actions_TransID;
-- First delete the related transactions
DELETE FROM tbl_Transactions
OUTPUT deleted.ParentTransactionID INTO @deletedTransactions
WHERE transactionID IN
(SELECT transactionID FROM tbl_Actions WHERE Time_stamp BETWEEN @startTime AND @stopTime)
-- Now delete the Actions
DELETE FROM tbl_Actions WHERE Time_stamp BETWEEN @startTime AND @stopTime
-- Make sure no orphans remaining
DELETE FROM tbl_Actions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Actions ADD CONSTRAINT FK_tbl_Actions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;
-- Delete any parent transactions
DELETE FROM tbl_Transactions WHERE transactionID IN (SELECT ParentTransactionID FROM @deletedTransactions WHERE ParentTransactionID IS NOT NULL)
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
BEGIN TRY
SET @r = 1;
WHILE @r > 0
BEGIN
IF @debug=1 PRINT 'Deleting from tbl_Transactions: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109);
BEGIN TRANSACTION
-- Clear the temp table
DELETE @deletedTransactions
-- Delete from tbl_Transactions and cascade delete of multiple tables,
-- copy deleted transactions' ParentTransactionIDs so can delete any parents after
DELETE TOP (@purgeSize) FROM tbl_Transactions
OUTPUT deleted.ParentTransactionID INTO @deletedTransactions
WHERE
-- See code above to delete tbl_Actions separately
-- TransactionID IN (SELECT transactionID FROM tbl_Actions WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_AdminActions WHERE Timestamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_Authentications WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_ClientOperations WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_CustomCommands WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_EventRules WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
-- EventRuleTransfers do not contain a time_stamp, but will cascade delete from Transactions
-- TransactionID IN (SELECT transactionID FROM tbl_EventRuleTransfers WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_ProtocolCommands WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_SocketConnections WHERE Time_stamp BETWEEN @startTime AND @stopTime) OR
TransactionID IN (SELECT transactionID FROM tbl_WorkspaceActions WHERE Time_stamp BETWEEN @startTime AND @stopTime)
SET @r = @@ROWCOUNT
-- Now delete the parents
DELETE FROM tbl_Transactions WHERE transactionID IN (SELECT ParentTransactionID FROM @deletedTransactions WHERE ParentTransactionID IS NOT NULL)
COMMIT TRANSACTION;
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log after each iteration to its original creation size
END
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete SAT Transactions and sub-tables tbl_SAT_Files, tbl_SAT_Emails (Cascading Delete)
IF @debug=1 PRINT 'Deleting from tbl_SAT_Transactions: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109);
BEGIN TRY
BEGIN TRANSACTION
DELETE FROM tbl_SAT_Transactions
WHERE time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete AS2 Transactions and sub-tables tbl_AS2Actions, tbl_AS2Files (non-Cascading Delete)
IF @debug=1 PRINT 'Deleting from tbl_AS2Transactions: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109);
BEGIN TRY
BEGIN TRANSACTION
-- First delete records in sub-tables
-- tbl_AS2Actions
DELETE FROM tbl_AS2Actions WHERE transactionID IN
(SELECT transactionID FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime) OR
FileID IN (SELECT FileID FROM tbl_AS2Files WHERE transactionID IN
(SELECT transactionID FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime))
-- tbl_AS2Files
DELETE FROM tbl_AS2Files WHERE transactionID IN
(SELECT transactionID FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime)
-- tbl_AS2Transactions
DELETE FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete from remaining tables (stand-alone)
/*
IF @debug=1 PRINT 'Deleting from tbl_ScanDataActions, etc.: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109);
BEGIN TRY
BEGIN TRANSACTION
DELETE FROM tbl_ScanDataActions WHERE Time_stamp BETWEEN @startTime AND @stopTime
DELETE FROM tbl_PrivacyTermsEUStatus WHERE Setdate BETWEEN @startTime AND @stopTime
DELETE FROM tbl_PersonalDataActions WHERE Setdate BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
*/
-- Re-establish the ParentTransactionID -> TransactionID constraint
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log to its original creation size
END
GO
-- Using 1,000,000 batch for now. Creates larger log, but moves quicker.
SET STATISTICS TIME OFF
EXEC sp_PurgeEFTTransactions NULL, NULL, 10000000, 1
SET STATISTICS TIME OFF
PRINT ''
-- PRINT 'Script completed at: ' + CAST(CURRENT_TIMESTAMP AS NVARCHAR)
PRINT 'Script completed at: ' + CONVERT(varchar(30),CURRENT_TIMESTAMP,109)
GO

View File

@ -0,0 +1,20 @@
1. Run recreate_foreign_keys.sql first, as it will fix any problems with FK associations if present (see notes in that script)
2. Run index_foreign_keys_and_time_stamps.sql next, as that will signficantly improve purge performance.
3. Open PurgeSQLEFTData.sql
3. Modify the purge date if desired. -30 means purge all records older than 30 days
3a. To change: search for "SET @stopTime = DATEADD(DAY, -60, GETDATE())"
3b. A value of -0 means ALL records
3c. Alternatively, you can pass in an exact date range:
3ci. Search for EXEC sp_PurgeEFTTransactions NULL, NULL, 1000000, 1
3cii. Enter date and times in quotes as such: EXEC sp_PurgeEFTTransactions '2019-01-20 18:11:00', '2019-04-01 07:50:00', 1000000, 1
4. Modify "USE EFTDB" below if your database name is different
5. Make sure you database is NOT actively recording data (disable ARM reporting in EFT temporarily)
6. Execute the script (it may take several hours if your databases has hundreds of millions of records)

View File

@ -0,0 +1,12 @@
declare @count int
print 'Row counts before purge'
select @count = count(*) from [dbo].[tbl_AdminActions] print 'tbl_AdminActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ProtocolCommands print 'tbl_ProtocolCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Actions print 'tbl_Actions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ClientOperations print 'tbl_ClientOperations count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_SocketConnections print 'tbl_SocketConnections count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Authentications print 'tbl_Authentications count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_CustomCommands print 'tbl_CustomCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_EventRules print 'tbl_EventRules count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Transactions print 'tbl_Transactions count = ' +CAST(@count AS NVARCHAR)

View File

@ -0,0 +1,81 @@
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Actions_TransactionID' AND object_id = OBJECT_ID('tbl_Actions'))
CREATE NONCLUSTERED INDEX [IX_tbl_Actions_TransactionID] ON [tbl_Actions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AdminActions_TransactionID' AND object_id = OBJECT_ID('tbl_AdminActions'))
CREATE NONCLUSTERED INDEX [IX_tbl_AdminActions_TransactionID] ON [tbl_AdminActions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AS2Actions_FileID' AND object_id = OBJECT_ID('tbl_AS2Actions'))
CREATE NONCLUSTERED INDEX [IX_tbl_AS2Actions_FileID] ON [tbl_AS2Actions] ([FileID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AS2Actions_TransactionID' AND object_id = OBJECT_ID('tbl_AS2Actions'))
CREATE NONCLUSTERED INDEX [IX_tbl_AS2Actions_TransactionID] ON [tbl_AS2Actions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AS2Files_TransactionID' AND object_id = OBJECT_ID('tbl_AS2Files'))
CREATE NONCLUSTERED INDEX [IX_tbl_AS2Files_TransactionID] ON [tbl_AS2Files] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_CustomCommands_TransactionID' AND object_id = OBJECT_ID('tbl_CustomCommands'))
CREATE NONCLUSTERED INDEX [IX_tbl_CustomCommands_TransactionID] ON [tbl_CustomCommands] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Groups_AuthenticationID' AND object_id = OBJECT_ID('tbl_Groups'))
CREATE NONCLUSTERED INDEX [IX_tbl_Groups_AuthenticationID] ON [tbl_Groups] ([AuthenticationID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_TransactionID' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
CREATE NONCLUSTERED INDEX [IX_tbl_ProtocolCommands_TransactionID] ON [tbl_ProtocolCommands] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Emails_txid' AND object_id = OBJECT_ID('tbl_SAT_Emails'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Emails_txid] ON [tbl_SAT_Emails] ([txid] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Files_txid' AND object_id = OBJECT_ID('tbl_SAT_Files'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Files_txid] ON [tbl_SAT_Files] ([txid] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_TransactionID' AND object_id = OBJECT_ID('tbl_SocketConnections'))
CREATE NONCLUSTERED INDEX [IX_tbl_SocketConnections_TransactionID] ON [tbl_SocketConnections] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Transactions_ParentTransactionID' AND object_id = OBJECT_ID('tbl_Transactions'))
CREATE NONCLUSTERED INDEX [IX_tbl_Transactions_ParentTransactionID] ON [tbl_Transactions] ([ParentTransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_TransactionID' AND object_id = OBJECT_ID('tbl_WorkspaceActions'))
CREATE NONCLUSTERED INDEX [IX_tbl_WorkspaceActions_TransactionID] ON [tbl_WorkspaceActions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_TransactionID' AND object_id = OBJECT_ID('tbl_WorkspaceParticipants'))
CREATE NONCLUSTERED INDEX [IX_tbl_WorkspaceActions_TransactionID] ON [tbl_WorkspaceParticipants] ([WorkspaceActionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- Add indexes on time_stamps
-- tbl_SAT_Transactions
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Transactions_Time_Stamp' AND object_id = OBJECT_ID('tbl_SAT_Transactions'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Transactions_Time_Stamp] ON [tbl_SAT_Transactions] ([time_stamp] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_ProtocolCommands (index existed, but adding INCLUDE TransactionID)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Time_stamp' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX [IX_tbl_ProtocolCommands_Time_stamp] ON [tbl_ProtocolCommands]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_ProtocolCommands_Time_stamp] ON [tbl_ProtocolCommands] ([time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_SocketConnections (index existed, but adding INCLUDE TransactionID)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_Time_stamp' AND object_id = OBJECT_ID('tbl_SocketConnections'))
DROP INDEX [IX_tbl_SocketConnections_Time_stamp] ON [tbl_SocketConnections]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_SocketConnections_Time_stamp] ON [tbl_SocketConnections] ([Time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_Authentications (index existed, but adding Time_stamp)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_User_Name' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX [IX_tbl_Authentications_User_Name] ON [tbl_Authentications]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_Authentications_User_Name] ON [tbl_Authentications] ([UserName],[Time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_ScanDataActions
/*
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ScanDataActions_Time_Stamp' AND object_id = OBJECT_ID('tbl_ScanDataActions'))
DROP INDEX [IX_tbl_ScanDataActions_Time_Stamp] ON [tbl_ScanDataActions]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_ScanDataActions_Time_Stamp] ON [tbl_ScanDataActions] ([Time_stamp]) INCLUDE ([ActionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
*/

View File

@ -0,0 +1,275 @@
-- recreate_foreign_keys.sql
-- Delete orphan records for any cascade delete foreign key constraints
-- 1. Test to see if any orphan records in sub-tables
-- 2. If orphan records exist
-- a. Drop the constraint between the table and parent table
-- b. Delete the orphan records
-- c. Recreate the constraint with the cascade delete
-- ****************************
-- tbl_Transactions constraints
-- ****************************
-- tbl_AdminActions
-- IF EXISTS (SELECT * FROM tbl_AdminActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_AdminActions DROP CONSTRAINT FK_tbl_AdminActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_AdminActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_AdminActions ADD CONSTRAINT FK_tbl_AdminActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Authentications WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_Authentications DROP CONSTRAINT FK_tbl_Auth_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Authentications WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Authentications ADD CONSTRAINT FK_tbl_Auth_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_ClientOperations
-- IF EXISTS (SELECT * FROM tbl_ClientOperations WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_ClientOperations DROP CONSTRAINT FK_tbl_ClientOperations_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ClientOperations WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ClientOperations ADD CONSTRAINT FK_tbl_ClientOperations_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_CustomCommands
-- IF EXISTS (SELECT * FROM tbl_CustomCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_CustomCommands DROP CONSTRAINT FK_tbl_CustomCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_CustomCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_CustomCommands ADD CONSTRAINT FK_tbl_CustomCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_EventRules WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_EventRules DROP CONSTRAINT FK_tbl_EventRules_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRules WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRules ADD CONSTRAINT FK_tbl_EventRules_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRuleTransfers
/*
-- IF EXISTS (SELECT * FROM tbl_EventRuleTransfers WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_EventRuleTransfers DROP CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRuleTransfers WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRuleTransfers ADD CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- tbl_ProtocolCommands
-- IF EXISTS (SELECT * FROM tbl_ProtocolCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_ProtocolCommands DROP CONSTRAINT FK_tbl_ProtocolCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ProtocolCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ProtocolCommands ADD CONSTRAINT FK_tbl_ProtocolCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_SocketConnections
-- IF EXISTS (SELECT * FROM tbl_SocketConnections WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_SocketConnections DROP CONSTRAINT FK_tbl_SocketConnections_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_SocketConnections WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SocketConnections ADD CONSTRAINT FK_tbl_SocketConnections_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceActions
/*
-- IF EXISTS (SELECT * FROM tbl_WorkspaceActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_WorkspaceActions DROP CONSTRAINT FK_tbl_WorkspaceActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceActions ADD CONSTRAINT FK_tbl_WorkspaceActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- *****************
-- Other constraints
-- *****************
-- tbl_ScanDataActions -> tbl_Actions
/*
IF EXISTS (SELECT * FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_ScanDataActions DROP CONSTRAINT FK_tbl_ScanDataActions_ActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ScanDataActions ADD CONSTRAINT FK_tbl_ScanDataActions_ActionID
FOREIGN KEY (ActionID)
REFERENCES tbl_Actions (ActionID)
ON DELETE CASCADE;
END
*/
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_Actions -> tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_Actions WHERE EventID NOT IN (SELECT EventID FROM tbl_EventRules))
BEGIN
-- Drop constraint
ALTER TABLE tbl_Actions DROP CONSTRAINT FK_tbl_Actions_EventId;
-- Make sure no orphans remaining
DELETE FROM tbl_Actions WHERE EventID NOT IN
(SELECT EventID FROM tbl_EventRules);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Actions ADD CONSTRAINT FK_tbl_Actions_EventId
FOREIGN KEY (EventID)
REFERENCES tbl_EventRules (EventID)
ON DELETE CASCADE;
END
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_SAT_Emails -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Emails WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_SAT_Emails DROP CONSTRAINT FK_tbl_SAT_Emails_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Emails WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Emails ADD CONSTRAINT FK_tbl_SAT_Emails_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_SAT_Emails -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Emails WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_SAT_Emails DROP CONSTRAINT FK_tbl_SAT_Emails_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Emails WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Emails ADD CONSTRAINT FK_tbl_SAT_Emails_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_SAT_Files -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Files WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
ALTER TABLE tbl_SAT_Files DROP CONSTRAINT FK_tbl_SAT_Files_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Files WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Files ADD CONSTRAINT FK_tbl_SAT_Files_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceParticipants -> tbl_WorkspaceActions
-- IF EXISTS (SELECT * FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN (SELECT ID FROM tbl_WorkspaceActions))
/*
BEGIN
-- Drop constraint
ALTER TABLE tbl_WorkspaceParticipants DROP CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN
(SELECT ID FROM tbl_WorkspaceActions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceParticipants ADD CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID
FOREIGN KEY (WorkspaceActionID)
REFERENCES tbl_WorkspaceActions (ID)
ON DELETE CASCADE;
END
*/
-- Re-create FK constraint between ParentTransactionID and TransactionID
-- Drop constraint
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;

View File

@ -0,0 +1,295 @@
-- recreate_foreign_keys.sql
-- Delete orphan records for any cascade delete foreign key constraints
-- 1. Test to see if any orphan records in sub-tables
-- 2. If orphan records exist
-- a. Drop the constraint between the table and parent table
-- b. Delete the orphan records
-- c. Recreate the constraint with the cascade delete
-- ****************************
-- tbl_Transactions constraints
-- ****************************
-- tbl_AdminActions
-- IF EXISTS (SELECT * FROM tbl_AdminActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_AdminActions_TransID') AND parent_object_id = OBJECT_ID(N'tbl_AdminActions'))
ALTER TABLE tbl_AdminActions DROP CONSTRAINT FK_tbl_AdminActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_AdminActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_AdminActions ADD CONSTRAINT FK_tbl_AdminActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Authentications WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Auth_TransID') AND parent_object_id = OBJECT_ID(N'tbl_Authentications'))
ALTER TABLE tbl_Authentications DROP CONSTRAINT FK_tbl_Auth_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Authentications WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Authentications ADD CONSTRAINT FK_tbl_Auth_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_ClientOperations
-- IF EXISTS (SELECT * FROM tbl_ClientOperations WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ClientOperations_TransID') AND parent_object_id = OBJECT_ID(N'tbl_ClientOperations'))
ALTER TABLE tbl_ClientOperations DROP CONSTRAINT FK_tbl_ClientOperations_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ClientOperations WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ClientOperations ADD CONSTRAINT FK_tbl_ClientOperations_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_CustomCommands
-- IF EXISTS (SELECT * FROM tbl_CustomCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_CustomCommands_TransID') AND parent_object_id = OBJECT_ID(N'tbl_CustomCommands'))
ALTER TABLE tbl_CustomCommands DROP CONSTRAINT FK_tbl_CustomCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_CustomCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_CustomCommands ADD CONSTRAINT FK_tbl_CustomCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_EventRules WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_EventRules_TransID') AND parent_object_id = OBJECT_ID(N'tbl_EventRules'))
ALTER TABLE tbl_EventRules DROP CONSTRAINT FK_tbl_EventRules_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRules WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRules ADD CONSTRAINT FK_tbl_EventRules_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRuleTransfers
/*
-- IF EXISTS (SELECT * FROM tbl_EventRuleTransfers WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_EventRuleTransfers_TransactionID') AND parent_object_id = OBJECT_ID(N'tbl_EventRuleTransfers'))
ALTER TABLE tbl_EventRuleTransfers DROP CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRuleTransfers WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRuleTransfers ADD CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- tbl_ProtocolCommands
-- IF EXISTS (SELECT * FROM tbl_ProtocolCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ProtocolCommands_TransID') AND parent_object_id = OBJECT_ID(N'tbl_ProtocolCommands'))
ALTER TABLE tbl_ProtocolCommands DROP CONSTRAINT FK_tbl_ProtocolCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ProtocolCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ProtocolCommands ADD CONSTRAINT FK_tbl_ProtocolCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_SocketConnections
-- IF EXISTS (SELECT * FROM tbl_SocketConnections WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SocketConnections_TransID') AND parent_object_id = OBJECT_ID(N'tbl_SocketConnections'))
ALTER TABLE tbl_SocketConnections DROP CONSTRAINT FK_tbl_SocketConnections_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_SocketConnections WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SocketConnections ADD CONSTRAINT FK_tbl_SocketConnections_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceActions
/*
-- IF EXISTS (SELECT * FROM tbl_WorkspaceActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_WorkspaceActions_TransID') AND parent_object_id = OBJECT_ID(N'tbl_WorkspaceActions'))
ALTER TABLE tbl_WorkspaceActions DROP CONSTRAINT FK_tbl_WorkspaceActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceActions ADD CONSTRAINT FK_tbl_WorkspaceActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- *****************
-- Other constraints
-- *****************
-- tbl_ScanDataActions -> tbl_Actions
/*
IF EXISTS (SELECT * FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ScanDataActions_ActionID') AND parent_object_id = OBJECT_ID(N'tbl_ScanDataActions'))
ALTER TABLE tbl_ScanDataActions DROP CONSTRAINT FK_tbl_ScanDataActions_ActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ScanDataActions ADD CONSTRAINT FK_tbl_ScanDataActions_ActionID
FOREIGN KEY (ActionID)
REFERENCES tbl_Actions (ActionID)
ON DELETE CASCADE;
END
*/
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Groups_AuthID') AND parent_object_id = OBJECT_ID(N'tbl_Groups'))
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_Actions -> tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_Actions WHERE EventID NOT IN (SELECT EventID FROM tbl_EventRules))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Actions_EventId') AND parent_object_id = OBJECT_ID(N'tbl_Actions'))
ALTER TABLE tbl_Actions DROP CONSTRAINT FK_tbl_Actions_EventId;
-- Make sure no orphans remaining
DELETE FROM tbl_Actions WHERE EventID NOT IN
(SELECT EventID FROM tbl_EventRules);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Actions ADD CONSTRAINT FK_tbl_Actions_EventId
FOREIGN KEY (EventID)
REFERENCES tbl_EventRules (EventID)
ON DELETE CASCADE;
END
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Groups_AuthID') AND parent_object_id = OBJECT_ID(N'tbl_Groups'))
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_SAT_Emails -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Emails WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SAT_Emails_TxID') AND parent_object_id = OBJECT_ID(N'tbl_SAT_Emails'))
ALTER TABLE tbl_SAT_Emails DROP CONSTRAINT FK_tbl_SAT_Emails_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Emails WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Emails ADD CONSTRAINT FK_tbl_SAT_Emails_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_SAT_Files -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Files WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SAT_Files_TxID') AND parent_object_id = OBJECT_ID(N'tbl_SAT_Files'))
ALTER TABLE tbl_SAT_Files DROP CONSTRAINT FK_tbl_SAT_Files_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Files WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Files ADD CONSTRAINT FK_tbl_SAT_Files_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceParticipants -> tbl_WorkspaceActions
-- IF EXISTS (SELECT * FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN (SELECT ID FROM tbl_WorkspaceActions))
/*
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_WorkspaceParticipants_WorkspaceActionID') AND parent_object_id = OBJECT_ID(N'tbl_WorkspaceParticipants'))
ALTER TABLE tbl_WorkspaceParticipants DROP CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN
(SELECT ID FROM tbl_WorkspaceActions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceParticipants ADD CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID
FOREIGN KEY (WorkspaceActionID)
REFERENCES tbl_WorkspaceActions (ID)
ON DELETE CASCADE;
END
*/
-- Re-create FK constraint between ParentTransactionID and TransactionID
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Transactions_ParentTransID') AND parent_object_id = OBJECT_ID(N'tbl_Transactions'))
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;

View File

@ -0,0 +1,277 @@
-- EFT Purging Script
-- Goal: General script to purge data from EFT's ARM database by date
--USAGE
/*
1. Run index_foreign_keys_and_time_stamps.sql first, as that will improve purge performance
2. Run repair_foreign_keys.sql next, as it will fix any problems if present (see notes in that script)
3. Modify the purge date if desired. -30 means purge all records older than 30 days
3a. To change: search for "SET @stopTime = DATEADD(DAY, -30, GETDATE())"
3b. A value of -0 means ALL records
3c. Alternatively, you can pass in an exact date range:
3ci. Search for EXEC sp_PurgeEFTTransactions NULL, NULL, 1000000, 1
3cii. Enter date and times in quotes as such: EXEC sp_PurgeEFTTransactions '2019-01-20 18:11:00', '2019-04-01 07:50:00', 1000000, 1
4. Modify "USE EFTDB" below if your database name is different
5. Make sure you database isn't actively recording data (disable ARM reporting in EFT temporarily)
6. Execute the script (it can take several hours for databases with hundreds of millions of records)
*/
-- Change Log:
-- 0.1: Set batch size at 100,000
-- Removed SELECT and extra PRINT statements.
-- 0.2: Changed to purge up to records greater than 30 days old
-- 0.3: Modified script to not assume cascading deletes and to
-- explicitly delete from all tables
-- Modified script to default 'purgesize' to 10,000
-- instead of 1,000
-- 0.4 Added AS2 and SAT purging
-- 0.5 Subset table wasn't being dropped.
-- 0.6 Changed to all static calls instead of dynamic.
-- 0.7 Changed purge size to 1,000,000
-- 0.8 Brought back cascade deletes to speed up performance
-- USE EFTDB
PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Script started'
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFTTransactionsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFTTransactionsVersion
GO
CREATE PROCEDURE sp_PurgeEFTTransactionsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Script Version 0.8'
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFTTransactions') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFTTransactions
END
GO
-- By default, this procedure will purge data from 1970 to 60 days ago.
CREATE PROCEDURE sp_PurgeEFTTransactions @startTime datetime = NULL,
@stopTime datetime = NULL,
@purgeSize int = NULL,
@debug bit = 0
AS
BEGIN
DECLARE @r INT;
DECLARE @ErrMsg nvarchar(4000);
DECLARE @ErrSeverity int;
DECLARE @deletedTransactions TABLE(ParentTransactionID numeric(18,0));
EXEC sp_PurgeEFTTransactionsVersion
-- Delete tbl_Transactions records and sub-tables
SET NOCOUNT ON
IF @startTime IS NULL BEGIN
set @startTime = '1970-01-01'
END
IF @stopTime IS NULL BEGIN
SET @stopTime = DATEADD(DAY, -60, GETDATE())
END
IF @purgeSize IS NULL BEGIN
set @purgeSize = 1000000
END
-- Temporarily remove the ParentTransactionID -> TransactionID constraint
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
-- First, delete from tbl_Actions separately since potential circular cascade delete with tbl_EventRules
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_Actions';
BEGIN TRY
BEGIN TRANSACTION
-- Clear the temp table
DELETE @deletedTransactions
-- First delete the related transactions
DELETE FROM tbl_Transactions
OUTPUT deleted.ParentTransactionID INTO @deletedTransactions
WHERE transactionID IN
(SELECT transactionID FROM tbl_Actions WHERE Time_stamp BETWEEN @startTime AND @stopTime)
-- Now delete the Actions
DELETE FROM tbl_Actions WHERE Time_stamp BETWEEN @startTime AND @stopTime
-- Make sure no orphans remaining
DELETE FROM tbl_Actions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Delete any parent transactions
DELETE FROM tbl_Transactions WHERE transactionID IN (SELECT ParentTransactionID FROM @deletedTransactions WHERE ParentTransactionID IS NOT NULL)
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
BEGIN TRY
-- First, drop constraint
IF (OBJECT_ID('FK_tbl_OutlookReport_ParentTransID', 'F') IS NOT NULL)
BEGIN
ALTER TABLE tbl_OutlookReport DROP CONSTRAINT FK_tbl_OutlookReport_ParentTransID;
END
SET @r = 1;
WHILE @r > 0
BEGIN
IF @debug=1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_Transactions';
BEGIN TRANSACTION
-- Clear the temp table
DELETE @deletedTransactions
-- Delete from tbl_Transactions and cascade delete of multiple tables,
-- copy deleted transactions' ParentTransactionIDs so can delete any parents after
-- Tables cascade deleted are:
-- tbl_AdminActions, tbl_Authentications, tbl_ClientOperations, tbl_CustomCommands, tbl_EventRules,
-- tbl_EventRuleTransfers, tbl_ProtocolCommands, tbl_SocketConnections, tbl_WorkspaceActions
DELETE TOP (@purgeSize) FROM tbl_Transactions
OUTPUT deleted.ParentTransactionID INTO @deletedTransactions
WHERE Time_stamp BETWEEN @startTime AND @stopTime
SET @r = @@ROWCOUNT
-- Now delete the parents
DELETE FROM tbl_Transactions WHERE transactionID IN (SELECT ParentTransactionID FROM @deletedTransactions WHERE ParentTransactionID IS NOT NULL)
COMMIT TRANSACTION;
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log after each iteration to its original creation size
END
DELETE FROM dbo.tbl_OutlookReport WHERE TransactionID NOT IN (SELECT TransactionID FROM tbl_Transactions);
ALTER TABLE tbl_OutlookReport ADD CONSTRAINT FK_tbl_OutlookReport_ParentTransID
FOREIGN KEY(TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete SAT Transactions and sub-tables tbl_SAT_Files, tbl_SAT_Emails (Cascading Delete)
BEGIN TRY
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_SAT_Transactions';
BEGIN TRANSACTION
DELETE FROM tbl_SAT_Transactions
WHERE time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_AWESteps';
BEGIN TRANSACTION
DELETE FROM tbl_AWESteps
WHERE time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_PCIViolations';
BEGIN TRANSACTION
DELETE FROM tbl_PCIViolations
WHERE time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_ServerInternalEvents';
BEGIN TRANSACTION
DELETE FROM tbl_ServerInternalEvents
WHERE time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete AS2 Transactions and sub-table tbl_AS2Actions (non-Cascading Delete)
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_AS2Transactions';
BEGIN TRY
BEGIN TRANSACTION
-- First delete records in sub-tables
-- tbl_AS2Actions
DELETE FROM tbl_AS2Actions WHERE transactionID IN
(SELECT transactionID FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime)
-- tbl_AS2Transactions
DELETE FROM tbl_AS2Transactions
WHERE CompleteTime BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Delete from remaining tables (stand-alone)
/*
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_ScanDataActions, etc.';
BEGIN TRY
BEGIN TRANSACTION
DELETE FROM tbl_ScanDataActions WHERE Time_stamp BETWEEN @startTime AND @stopTime
DELETE FROM tbl_PrivacyTermsEUStatus WHERE Setdate BETWEEN @startTime AND @stopTime
DELETE FROM tbl_PersonalDataActions WHERE Setdate BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
*/
-- Re-establish the ParentTransactionID -> TransactionID constraint
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log to its original creation size
END
GO
-- Using 10,000,000 batch for now. Creates larger log, but moves quicker.
SET STATISTICS TIME OFF
EXEC sp_PurgeEFTTransactions NULL, NULL, 10000000, 1
--EXEC sp_PurgeEFTTransactions '2018-01-01', '2018-12-31', 10000000, 1
SET STATISTICS TIME OFF
PRINT ''
PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Script completed'
GO

View File

@ -0,0 +1,107 @@
-- EFT Purging script: tbl_Authentications
-- Goal: Purge tbl_Authentications table of garbage logon attempts using non-existing usernames.
-- USAGE
-- Config: By default, the script will search for user account authentications attempts using 'root' or 'administrator'
-- You can edit those terms or add your own by modifying the appropriate areas of this script (search for root or administrator)
-- You can also specify a start and end range or use NULL, NULL which will dafault to deleting records back 60 days
-- Change Log:
-- 0.1: Initial version
-- [NOTE: Added to upgrade_17.0.0.0-18.0.0.0 script to modify tbl_Authentications index IX_tbl_Authentications_User_Name to include Time_stamp]
PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Script started'
-- USE EFTDB
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFT_AuthenticationsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFT_AuthenticationsVersion
GO
CREATE PROCEDURE sp_PurgeEFT_AuthenticationsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Authentication Script Version 0.1'
GO
-- This procedure deletes Authentications based on username and date range
IF OBJECT_ID('dbo.sp_PurgeEFT_Authentications') IS NOT NULL
DROP PROC dbo.sp_PurgeEFT_Authentications
GO
CREATE PROCEDURE sp_PurgeEFT_Authentications
@startTime datetime = NULL,
@stopTime datetime = NULL,
@UserName nvarchar(50) = NULL,
@debug bit = 0
AS
EXEC dbo.sp_PurgeEFT_AuthenticationsVersion
SET NOCOUNT ON
IF @startTime IS NULL BEGIN
set @startTime = '19700101 00:00:00'
END
IF @stopTime IS NULL BEGIN
SET @stopTime = DATEADD(DAY, -60, GETDATE())
END
-- Temporarily remove the ParentTransactionID -> TransactionID constraint
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
BEGIN TRY
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting transactions for authentications';
-- Deleting the transactions should cascade delete to other tables if any associated transactions exist
IF @UserName IS NULL -- Use default usernames
DELETE FROM tbl_Transactions WHERE TransactionID IN
(SELECT transactionID FROM tbl_Authentications WHERE (UserName = 'Administrator' OR UserName = 'root') AND Time_stamp BETWEEN @startTime AND @stopTime)
ELSE
DELETE FROM tbl_Transactions WHERE TransactionID IN
(SELECT transactionID FROM tbl_Authentications WHERE UserName = @UserName AND Time_stamp BETWEEN @startTime AND @stopTime)
-- Should be zero transactions to purge here, since cascade delete above should have handled them
IF @debug = 1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting rows from tbl_Authentications with UserNames: ' + ISNULL(@UserName, 'Adminitrator, root');
IF @UserName IS NULL -- Use default usernames
DELETE FROM tbl_Authentications WHERE (UserName = 'Administrator' OR UserName = 'root') AND Time_stamp BETWEEN @startTime AND @stopTime
ELSE
DELETE FROM tbl_Authentications WHERE UserName = @UserName AND Time_stamp BETWEEN @startTime AND @stopTime
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- If error, roll back
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Re-establish the ParentTransactionID -> TransactionID constraint
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;
GO
EXEC sp_PurgeEFT_Authentications NULL, NULL, NULL, 1
-- EXEC sp_PurgeEFT_Authentications '2018-01-01', '2018-12-31', NULL, 1
PRINT ''
PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Script completed'

View File

@ -0,0 +1,93 @@
-- EFT Purging Script - tbl_ProtocolCommands
-- Goal: Special script to purge internal transaction data from tbl_ProtocolCommands
-- USAGE
-- 1. Configure (bottom of script) then run.
-- to purge all ProtocolCommands with IsInternal = 1:
-- EXEC sp_PurgeEFT_ProtocolCommands NULL, NULL
-- to purge date range ProtocolCommands with IsInternal = 1 - e.g.:
-- EXEC sp_PurgeEFT_ProtocolCommands '2019-01-01', '2019-05-18'
--
-- leaving begin date as NULL will default to earliest date
-- leaving end date as NULL will default to current date
-- Change Log:
-- 0.1: Original version
-- USE EFTDB
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFT_ProtocolCommandsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFT_ProtocolCommandsVersion
GO
CREATE PROCEDURE sp_PurgeEFT_ProtocolCommandsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Protocol Commands Script Version 0.1'
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFT_ProtocolCommands') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFT_ProtocolCommands
END
GO
-- By default, with no parameters, this procedure will purge all Protocol connections
CREATE PROCEDURE sp_PurgeEFT_ProtocolCommands
@startTime datetime = NULL,
@stopTime datetime = NULL,
@debug bit = 0
AS
BEGIN
DECLARE @ErrMsg nvarchar(4000);
DECLARE @ErrSeverity int;
EXEC dbo.sp_PurgeEFT_ProtocolCommandsVersion
SET NOCOUNT ON
IF @startTime IS NULL
BEGIN
SET @startTime = '1970-01-01 00:00:00'
END
IF @stopTime IS NULL
BEGIN
SET @stopTime = DATEADD(DAY, 1, GETDATE())
END
ELSE
BEGIN
SET @stopTime = DATEADD(DAY, 1, @stopTime) -- Add 1 to selected date to get all records before that
END
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_ProtocolCommands';
BEGIN TRY
DELETE FROM tbl_ProtocolCommands WHERE IsInternal=1 AND Time_stamp >= @startTime AND Time_stamp < @stopTime
END TRY
BEGIN CATCH
-- There was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log to its original creation size
IF @debug=1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Done deleting from tbl_ProtocolCommands';
PRINT 'Procedure Complete'
END
GO
-- Default to purge entire table
-- SET STATISTICS TIME OFF
-- EXEC sp_PurgeEFT_ProtocolCommands NULL, NULL, 1
EXEC sp_PurgeEFT_ProtocolCommands '2018-01-01', '2018-12-31', 1
-- SET STATISTICS TIME OFF

View File

@ -0,0 +1,95 @@
-- EFT Purging Script - tbl_ProtocolCommands
-- Goal: Special script to purge data from tbl_ProtocolCommands with unimportant verbs
-- USAGE
-- 1. Run this script, then
-- to purge all ProtocolCommands which are not relevant to main operations (upload, download, rename, delete, mkd)
-- EXEC sp_PurgeEFT_ProtocolCommands NULL, NULL
-- to purge date range:
-- EXEC sp_PurgeEFT_ProtocolCommands '2019-01-01', '2019-05-18'
--
-- leaving begin date as NULL will default to earliest date
-- leaving end date as NULL will default to current date
-- Change Log:
-- 0.1: Original version
-- 0.2: Changed to remove based on certain commands. the is internal flag wasn't a sufficient qualifier.
-- USE EFTDB
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFT_ProtocolCommands2Version') IS NOT NULL
DROP PROC dbo.sp_PurgeEFT_ProtocolCommands2Version
GO
CREATE PROCEDURE sp_PurgeEFT_ProtocolCommands2Version
AS
PRINT 'GlobalSCAPE, Inc. Purge Protocol Commands Script 2 Version 0.2'
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFT_ProtocolCommands2') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFT_ProtocolCommands2
END
GO
-- By default, with no parameters, this procedure will purge all Protocol connections
CREATE PROCEDURE sp_PurgeEFT_ProtocolCommands2
@startTime datetime = NULL,
@stopTime datetime = NULL,
@debug bit = 0
AS
BEGIN
DECLARE @ErrMsg nvarchar(4000);
DECLARE @ErrSeverity int;
EXEC dbo.sp_PurgeEFT_ProtocolCommands2Version
SET NOCOUNT ON
IF @startTime IS NULL
BEGIN
SET @startTime = '1970-01-01 00:00:00'
END
IF @stopTime IS NULL
BEGIN
SET @stopTime = DATEADD(DAY, 1, GETDATE())
END
ELSE
BEGIN
SET @stopTime = DATEADD(DAY, 1, @stopTime) -- Add 1 to selected date to get all records before that
END
IF @debug=1 PRINT CONVERT(varchar(30), CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_ProtocolCommands';
BEGIN TRY
DELETE FROM tbl_ProtocolCommands
WHERE Time_stamp >= @startTime AND Time_stamp < @stopTime AND
Command NOT IN ('sent', 'created', 'mkd', 'rmd', 'dele', 'rnfr', 'rnto', 'DELETE', 'retr', 'POST', 'patch', 'copy')
END TRY
BEGIN CATCH
-- There was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log to its original creation size
IF @debug=1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Done deleting from tbl_ProtocolCommands';
PRINT 'Procedure Complete'
END
GO
SET STATISTICS TIME OFF
/* EXEC sp_PurgeEFT_ProtocolCommands2 NULL, NULL -- Default to purge entire table */
EXEC sp_PurgeEFT_ProtocolCommands2 '2018-01-01', '2018-12-31', 1

View File

@ -0,0 +1,119 @@
-- EFT Purging Script - tbl_SocketConnections
-- Goal: Special script to purge data from tbl_SocketConnections by date
-- USAGE
-- 1. Configure the purge (bottom of script)
-- To perform a complete purge, just run the command at the bottom of the script: EXEC sp_PurgeEFT_SocketConnections NULL, NULL, NULL
-- If you want to purge a specific date range, then specify a start and end date: EXEC sp_PurgeEFT_SocketConnections '2019-01-01', '2019-05-18', NULL
-- If you want to purge a specific error code, for example error code 0: EXEC sp_PurgeEFT_SocketConnections '2019-01-01', '2019-05-18', 0
-- Note: Leaving begin date as NULL will default to earliest date.
-- Leaving end date as NULL will default to current date.
-- Leaving errorCode as NULL will purge all error codes.
-- Change Log:
-- 0.1: Original version
-- 0.2: Updated comments
-- USE EFTDB
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFT_SocketConnectionsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFT_SocketConnectionsVersion
GO
CREATE PROCEDURE sp_PurgeEFT_SocketConnectionsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Script Version 0.2'
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFT_SocketConnections') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFT_SocketConnections
END
GO
-- By default, with no parameters, this procedure will purge all socket connections
CREATE PROCEDURE sp_PurgeEFT_SocketConnections
@startTime datetime = NULL,
@stopTime datetime = NULL,
@errorCode int = NULL,
@debug bit = 0
AS
BEGIN
DECLARE @ErrMsg nvarchar(4000);
DECLARE @ErrSeverity int;
EXEC dbo.sp_PurgeEFT_SocketConnectionsVersion
SET NOCOUNT ON
IF @startTime IS NULL AND @stopTime IS NULL AND @errorCode IS NULL
BEGIN
--This will remove everything, regardless of ResultID code
TRUNCATE TABLE tbl_SocketConnections
END
ELSE
BEGIN
IF @startTime IS NULL
BEGIN
SET @startTime = '1970-01-01 00:00:00'
END
IF @stopTime IS NULL
BEGIN
SET @stopTime = DATEADD(DAY, 1, GETDATE())
END
ELSE
BEGIN
SET @stopTime = DATEADD(DAY, 1, @stopTime)
END
IF @debug=1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Deleting from tbl_SocketConnections';
BEGIN TRY
IF @errorCode IS NULL
BEGIN
DELETE FROM tbl_SocketConnections WHERE Time_stamp >= @startTime AND Time_stamp < @stopTime
END
ELSE
BEGIN
DELETE FROM tbl_SocketConnections WHERE Time_stamp >= @startTime AND Time_stamp < @stopTime AND ResultID = @errorCode
END
END TRY
BEGIN CATCH
-- There was an error
IF @@TRANCOUNT > 0 ROLLBACK
-- Raise an error with the details of the exception
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
DBCC SHRINKFILE (2) WITH NO_INFOMSGS; -- Truncate the log to its original creation size
IF @debug=1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP, 8) + ' Done deleting from tbl_SocketConnections';
END
PRINT 'Procedure Complete'
END
GO
-- sp_PurgeEFT_SocketConnections parameters
--
-- startTime: set the time to purge from. If set to NULL it will default to January 1970.
-- stopTime : set the time to purge to. If set to NULL it will default to todays date.
-- errorCode: set the resultID to purge. If set to NULL it will purge all resultIDs.
-- The errorCodes are as follows:
-- - TOO_MANY_CONNECTIONS_PER_SITE = 8
-- - TOO_MANY_CONNECTIONS_PER_IP = 9
-- - RESTRICTED_IP = 10
-- - BANNED_IP = 11
-- - EFT_IN_DEV_MODE = 12
-- - INTERNAL_SERVER_ERROR = 13
-- - OK = 0
-- Default to purge entire table
-- SET STATISTICS TIME OFF
EXEC sp_PurgeEFT_SocketConnections NULL, NULL, NULL, 1
-- EXEC sp_PurgeEFT_SocketConnections '2018-01-01', '2018-12-31', NULL, 1
-- SET STATISTICS TIME OFF

View File

@ -0,0 +1,34 @@
/*
WHAT:
Detects superfluous indexes
WHY:
These can hurt performance, since the DB must update them during Inserts, Updates and Deletes. And if theyre never used, then thats a waste of resources.
WHEN:
Created in April of 2019
WHO:
Created by Globalscape, Inc.
HOW:
Its best run on one of the larger, well-used databases, since it then has more info to work with. Otherwise stats won't be available to determine whether indexes are unused or not. Indexes that are identified as seldom used should be deleted by your db admin.
*/
SELECT TOP 10 o.name AS TableName, i.name AS IndexName, u.user_seeks As Seeks, u.user_scans As Scans, u.user_lookups As Lookups,
u.user_updates As UserUpdates, u.last_user_seek As LastUserSeek, u.last_user_scan As LastUserScan,
(SELECT SUM(s.[used_page_count]) * 8 FROM sys.dm_db_partition_stats s WHERE s.[object_id] = i.[object_id] AND s.[index_id] = i.[index_id]) As IndexSizeKB,
'Drop index ' + i.name + ' on ' + o.name as DropIndexStatement
FROM sys.indexes i
JOIN sys.objects o ON i.object_id = o.object_id
LEFT JOIN sys.dm_db_index_usage_stats u ON i.object_id = u.object_id
AND i.index_id = u.index_id
AND u.database_id = DB_ID()
WHERE o.type <> 'S'
and isnull(u.user_updates,0) > 0
and i.type_desc <> 'HEAP'
and i.type_desc <> 'CLUSTERED'
and u.user_seeks < 5 and u.user_scans < 5 and u.user_lookups < 5
ORDER BY IndexSizeKB DESC, UserUpdates DESC

View File

@ -0,0 +1,98 @@
/*
WHAT:
Records the number of rows in each table
WHY:
Can be useful to count rows before and after a purge.
WHEN:
Created in April of 2019
WHO:
Created by Globalscape, Inc.
HOW:
Row count can take several minutes depending on the size of the database
*/
declare @count int
select @count = count(*) from tbl_Actions
print 'tbl_Actions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_AdminActions
print 'tbl_AdminActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_AS2Actions
print 'tbl_AS2Actions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_AS2Transactions
print 'tbl_AS2Transactions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Authentications
print 'tbl_Authentications count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_AuthenticationsExpired
print 'tbl_AuthenticationsExpired count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_AWESteps
print 'tbl_AWESteps count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ClientOperations
print 'tbl_ClientOperations count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_CustomCommands
print 'tbl_CustomCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_EventRules
print 'tbl_EventRules count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_EventRuleTransfers
print 'tbl_EventRuleTransfers count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Groups
print 'tbl_Groups count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_NegotiatedCiphersSSH
print 'tbl_NegotiatedCiphersSSH count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_NegotiatedCiphersSSL
print 'tbl_NegotiatedCiphersSSL count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_OutlookReport
print 'tbl_OutlookReport count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_PCIViolations
print 'tbl_PCIViolations count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_PersonalDataActions
print 'tbl_PersonalDataActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_PrivacyTermsEUStatus
print 'tbl_PrivacyTermsEUStatus count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ProtocolCommands
print 'tbl_ProtocolCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_PrivacyRightExercised
print 'tbl_PrivacyRightExercised count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ScanDataActions
print 'tbl_ScanDataActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ServerInternalEvents
print 'tbl_ServerInternalEvents count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_SocketConnections
print 'tbl_SocketConnections count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Transactions
print 'tbl_Transactions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_WorkspaceActions
print 'tbl_WorkspaceActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_WorkspaceParticipants
print 'tbl_WorkspaceParticipants count = ' +CAST(@count AS NVARCHAR)

View File

@ -0,0 +1,75 @@
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Actions_TransactionID' AND object_id = OBJECT_ID('tbl_Actions'))
CREATE NONCLUSTERED INDEX [IX_tbl_Actions_TransactionID] ON [tbl_Actions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AdminActions_TransactionID' AND object_id = OBJECT_ID('tbl_AdminActions'))
CREATE NONCLUSTERED INDEX [IX_tbl_AdminActions_TransactionID] ON [tbl_AdminActions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AS2Actions_TransactionID' AND object_id = OBJECT_ID('tbl_AS2Actions'))
CREATE NONCLUSTERED INDEX [IX_tbl_AS2Actions_TransactionID] ON [tbl_AS2Actions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_CustomCommands_TransactionID' AND object_id = OBJECT_ID('tbl_CustomCommands'))
CREATE NONCLUSTERED INDEX [IX_tbl_CustomCommands_TransactionID] ON [tbl_CustomCommands] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Groups_AuthenticationID' AND object_id = OBJECT_ID('tbl_Groups'))
CREATE NONCLUSTERED INDEX [IX_tbl_Groups_AuthenticationID] ON [tbl_Groups] ([AuthenticationID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_TransactionID' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
CREATE NONCLUSTERED INDEX [IX_tbl_ProtocolCommands_TransactionID] ON [tbl_ProtocolCommands] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Emails_txid' AND object_id = OBJECT_ID('tbl_SAT_Emails'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Emails_txid] ON [tbl_SAT_Emails] ([txid] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Files_txid' AND object_id = OBJECT_ID('tbl_SAT_Files'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Files_txid] ON [tbl_SAT_Files] ([txid] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_TransactionID' AND object_id = OBJECT_ID('tbl_SocketConnections'))
CREATE NONCLUSTERED INDEX [IX_tbl_SocketConnections_TransactionID] ON [tbl_SocketConnections] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Transactions_ParentTransactionID' AND object_id = OBJECT_ID('tbl_Transactions'))
CREATE NONCLUSTERED INDEX [IX_tbl_Transactions_ParentTransactionID] ON [tbl_Transactions] ([ParentTransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_TransactionID' AND object_id = OBJECT_ID('tbl_WorkspaceActions'))
CREATE NONCLUSTERED INDEX [IX_tbl_WorkspaceActions_TransactionID] ON [tbl_WorkspaceActions] ([TransactionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_TransactionID' AND object_id = OBJECT_ID('tbl_WorkspaceParticipants'))
CREATE NONCLUSTERED INDEX [IX_tbl_WorkspaceActions_TransactionID] ON [tbl_WorkspaceParticipants] ([WorkspaceActionID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- Add indexes on time_stamps
-- tbl_SAT_Transactions
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SAT_Transactions_Time_Stamp' AND object_id = OBJECT_ID('tbl_SAT_Transactions'))
CREATE NONCLUSTERED INDEX [IX_tbl_SAT_Transactions_Time_Stamp] ON [tbl_SAT_Transactions] ([time_stamp] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_ProtocolCommands (index existed, but adding INCLUDE TransactionID)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Time_stamp' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX [IX_tbl_ProtocolCommands_Time_stamp] ON [tbl_ProtocolCommands]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_ProtocolCommands_Time_stamp] ON [tbl_ProtocolCommands] ([time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_SocketConnections (index existed, but adding INCLUDE TransactionID)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_Time_stamp' AND object_id = OBJECT_ID('tbl_SocketConnections'))
DROP INDEX [IX_tbl_SocketConnections_Time_stamp] ON [tbl_SocketConnections]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_SocketConnections_Time_stamp] ON [tbl_SocketConnections] ([Time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_Authentications (index existed, but adding Time_stamp)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_User_Name' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX [IX_tbl_Authentications_User_Name] ON [tbl_Authentications]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_Authentications_User_Name] ON [tbl_Authentications] ([UserName],[Time_stamp]) INCLUDE ([TransactionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
-- tbl_ScanDataActions
/*
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ScanDataActions_Time_Stamp' AND object_id = OBJECT_ID('tbl_ScanDataActions'))
DROP INDEX [IX_tbl_ScanDataActions_Time_Stamp] ON [tbl_ScanDataActions]
GO
CREATE NONCLUSTERED INDEX [IX_tbl_ScanDataActions_Time_Stamp] ON [tbl_ScanDataActions] ([Time_stamp]) INCLUDE ([ActionID]) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
*/

View File

@ -0,0 +1,295 @@
-- repair_foreign_keys.sql
-- Delete orphan records for any cascade delete foreign key constraints
-- 1. Test to see if any orphan records in sub-tables
-- 2. If orphan records exist
-- a. Drop the constraint between the table and parent table
-- b. Delete the orphan records
-- c. Recreate the constraint with the cascade delete
-- ****************************
-- tbl_Transactions constraints
-- ****************************
-- tbl_AdminActions
-- IF EXISTS (SELECT * FROM tbl_AdminActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_AdminActions_TransID') AND parent_object_id = OBJECT_ID(N'tbl_AdminActions'))
ALTER TABLE tbl_AdminActions DROP CONSTRAINT FK_tbl_AdminActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_AdminActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_AdminActions ADD CONSTRAINT FK_tbl_AdminActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Authentications WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Auth_TransID') AND parent_object_id = OBJECT_ID(N'tbl_Authentications'))
ALTER TABLE tbl_Authentications DROP CONSTRAINT FK_tbl_Auth_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Authentications WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Authentications ADD CONSTRAINT FK_tbl_Auth_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_ClientOperations
-- IF EXISTS (SELECT * FROM tbl_ClientOperations WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ClientOperations_TransID') AND parent_object_id = OBJECT_ID(N'tbl_ClientOperations'))
ALTER TABLE tbl_ClientOperations DROP CONSTRAINT FK_tbl_ClientOperations_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ClientOperations WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ClientOperations ADD CONSTRAINT FK_tbl_ClientOperations_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_CustomCommands
-- IF EXISTS (SELECT * FROM tbl_CustomCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_CustomCommands_TransID') AND parent_object_id = OBJECT_ID(N'tbl_CustomCommands'))
ALTER TABLE tbl_CustomCommands DROP CONSTRAINT FK_tbl_CustomCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_CustomCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_CustomCommands ADD CONSTRAINT FK_tbl_CustomCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_EventRules WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_EventRules_TransID') AND parent_object_id = OBJECT_ID(N'tbl_EventRules'))
ALTER TABLE tbl_EventRules DROP CONSTRAINT FK_tbl_EventRules_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRules WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRules ADD CONSTRAINT FK_tbl_EventRules_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_EventRuleTransfers
/*
-- IF EXISTS (SELECT * FROM tbl_EventRuleTransfers WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_EventRuleTransfers_TransactionID') AND parent_object_id = OBJECT_ID(N'tbl_EventRuleTransfers'))
ALTER TABLE tbl_EventRuleTransfers DROP CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID;
-- Make sure no orphans remaining
DELETE FROM tbl_EventRuleTransfers WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_EventRuleTransfers ADD CONSTRAINT FK_tbl_EventRuleTransfers_TransactionID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- tbl_ProtocolCommands
-- IF EXISTS (SELECT * FROM tbl_ProtocolCommands WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ProtocolCommands_TransID') AND parent_object_id = OBJECT_ID(N'tbl_ProtocolCommands'))
ALTER TABLE tbl_ProtocolCommands DROP CONSTRAINT FK_tbl_ProtocolCommands_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_ProtocolCommands WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ProtocolCommands ADD CONSTRAINT FK_tbl_ProtocolCommands_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_SocketConnections
-- IF EXISTS (SELECT * FROM tbl_SocketConnections WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SocketConnections_TransID') AND parent_object_id = OBJECT_ID(N'tbl_SocketConnections'))
ALTER TABLE tbl_SocketConnections DROP CONSTRAINT FK_tbl_SocketConnections_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_SocketConnections WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SocketConnections ADD CONSTRAINT FK_tbl_SocketConnections_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceActions
/*
-- IF EXISTS (SELECT * FROM tbl_WorkspaceActions WHERE transactionID NOT IN (SELECT transactionID FROM tbl_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_WorkspaceActions_TransID') AND parent_object_id = OBJECT_ID(N'tbl_WorkspaceActions'))
ALTER TABLE tbl_WorkspaceActions DROP CONSTRAINT FK_tbl_WorkspaceActions_TransID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceActions WHERE transactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceActions ADD CONSTRAINT FK_tbl_WorkspaceActions_TransID
FOREIGN KEY (TransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE CASCADE;
END
*/
-- *****************
-- Other constraints
-- *****************
-- tbl_ScanDataActions -> tbl_Actions
/*
IF EXISTS (SELECT * FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_ScanDataActions_ActionID') AND parent_object_id = OBJECT_ID(N'tbl_ScanDataActions'))
ALTER TABLE tbl_ScanDataActions DROP CONSTRAINT FK_tbl_ScanDataActions_ActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_ScanDataActions WHERE ActionID NOT IN
(SELECT ActionID FROM tbl_Actions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_ScanDataActions ADD CONSTRAINT FK_tbl_ScanDataActions_ActionID
FOREIGN KEY (ActionID)
REFERENCES tbl_Actions (ActionID)
ON DELETE CASCADE;
END
*/
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Groups_AuthID') AND parent_object_id = OBJECT_ID(N'tbl_Groups'))
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_Actions -> tbl_EventRules
-- IF EXISTS (SELECT * FROM tbl_Actions WHERE EventID NOT IN (SELECT EventID FROM tbl_EventRules))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Actions_EventId') AND parent_object_id = OBJECT_ID(N'tbl_Actions'))
ALTER TABLE tbl_Actions DROP CONSTRAINT FK_tbl_Actions_EventId;
-- Make sure no orphans remaining
DELETE FROM tbl_Actions WHERE EventID NOT IN
(SELECT EventID FROM tbl_EventRules);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Actions ADD CONSTRAINT FK_tbl_Actions_EventId
FOREIGN KEY (EventID)
REFERENCES tbl_EventRules (EventID)
ON DELETE CASCADE;
END
-- tbl_Groups -> tbl_Authentications
-- IF EXISTS (SELECT * FROM tbl_Groups WHERE AuthenticationID NOT IN (SELECT AuthenticationID FROM tbl_Authentications))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Groups_AuthID') AND parent_object_id = OBJECT_ID(N'tbl_Groups'))
ALTER TABLE tbl_Groups DROP CONSTRAINT FK_tbl_Groups_AuthID;
-- Make sure no orphans remaining
DELETE FROM tbl_Groups WHERE AuthenticationID NOT IN
(SELECT AuthenticationID FROM tbl_Authentications);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_Groups ADD CONSTRAINT FK_tbl_Groups_AuthID
FOREIGN KEY (AuthenticationID)
REFERENCES tbl_Authentications (AuthenticationID)
ON DELETE CASCADE;
END
-- tbl_SAT_Emails -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Emails WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SAT_Emails_TxID') AND parent_object_id = OBJECT_ID(N'tbl_SAT_Emails'))
ALTER TABLE tbl_SAT_Emails DROP CONSTRAINT FK_tbl_SAT_Emails_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Emails WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Emails ADD CONSTRAINT FK_tbl_SAT_Emails_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_SAT_Files -> tbl_SAT_Transactions
-- IF EXISTS (SELECT * FROM tbl_SAT_Files WHERE txid NOT IN (SELECT ID FROM tbl_SAT_Transactions))
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_SAT_Files_TxID') AND parent_object_id = OBJECT_ID(N'tbl_SAT_Files'))
ALTER TABLE tbl_SAT_Files DROP CONSTRAINT FK_tbl_SAT_Files_TxID;
-- Make sure no orphans remaining
DELETE FROM tbl_SAT_Files WHERE txid NOT IN
(SELECT ID FROM tbl_SAT_Transactions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_SAT_Files ADD CONSTRAINT FK_tbl_SAT_Files_TxID
FOREIGN KEY (txid)
REFERENCES tbl_SAT_Transactions (ID)
ON DELETE CASCADE;
END
-- tbl_WorkspaceParticipants -> tbl_WorkspaceActions
-- IF EXISTS (SELECT * FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN (SELECT ID FROM tbl_WorkspaceActions))
/*
BEGIN
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_WorkspaceParticipants_WorkspaceActionID') AND parent_object_id = OBJECT_ID(N'tbl_WorkspaceParticipants'))
ALTER TABLE tbl_WorkspaceParticipants DROP CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID;
-- Make sure no orphans remaining
DELETE FROM tbl_WorkspaceParticipants WHERE WorkspaceActionID NOT IN
(SELECT ID FROM tbl_WorkspaceActions);
-- Now, add it back with cascade delete enabled
ALTER TABLE tbl_WorkspaceParticipants ADD CONSTRAINT FK_tbl_WorkspaceParticipants_WorkspaceActionID
FOREIGN KEY (WorkspaceActionID)
REFERENCES tbl_WorkspaceActions (ID)
ON DELETE CASCADE;
END
*/
-- Re-create FK constraint between ParentTransactionID and TransactionID
-- Drop constraint
IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_tbl_Transactions_ParentTransID') AND parent_object_id = OBJECT_ID(N'tbl_Transactions'))
ALTER TABLE tbl_Transactions DROP CONSTRAINT FK_tbl_Transactions_ParentTransID;
-- Make sure no orphans remaining
DELETE FROM tbl_Transactions WHERE ParentTransactionID IS NOT NULL AND ParentTransactionID NOT IN
(SELECT transactionID FROM tbl_Transactions);
-- Now, add it back without cascade delete enabled
ALTER TABLE tbl_Transactions ADD CONSTRAINT FK_tbl_Transactions_ParentTransID
FOREIGN KEY (ParentTransactionID)
REFERENCES tbl_Transactions (TransactionID)
ON DELETE NO ACTION;

View File

@ -0,0 +1,156 @@
-- For reports Activity-AS2 Transfers (Detailed) and Activity-AS2 Transfers (Summary)
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AS2Transactions_StartTime' AND object_id = OBJECT_ID('tbl_AS2Transactions'))
DROP INDEX IX_tbl_AS2Transactions_StartTime ON tbl_AS2Transactions
GO
CREATE INDEX IX_tbl_AS2Transactions_StartTime ON tbl_AS2Transactions (StartTime)
GO
UPDATE STATISTICS tbl_AS2Transactions;
GO
-- For reports Activity-by Permissions Group, Activity-by Users (Detailed),
-- Activity-by Users (Summary), Exec Summary, Traffic-Average Transfer Rates by User,
-- WebServiceInvokeEventRules-Activity(Detailed)
-- Remove IX_tbl_ProtocolCommands_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Time_stamp' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_Time_stamp ON tbl_ProtocolCommands
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Time_stamp_Command_FileName' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_Time_stamp_Command_FileName ON tbl_ProtocolCommands
GO
CREATE INDEX IX_tbl_ProtocolCommands_Time_stamp_Command_FileName ON tbl_ProtocolCommands (Time_stamp, Command, FileName)
GO
UPDATE STATISTICS tbl_ProtocolCommands;
GO
-- For reports Traffic - Connections Summary, Traffic-Datewise-hourly Bytes Transferred,
-- Traffic-Datewise-IPwiseBytesTransferred, Traffic-Monthwise-IPWise Bytes Transferred,
-- Traffic-Protocolwise Connections
-- Remove IX_tbl_ProtocolCommands_Site_Name since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Site_Name' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_Site_Name ON tbl_ProtocolCommands
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_Site_Name_Time_stamp' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_Site_Name_Time_stamp ON tbl_ProtocolCommands
GO
CREATE INDEX IX_tbl_ProtocolCommands_Site_Name_Time_stamp ON tbl_ProtocolCommands (SiteName, Time_stamp)
GO
UPDATE STATISTICS tbl_ProtocolCommands;
GO
-- For reports Traffic-Most Active IP Connections, Traffic-Most Active IP - Data Transferred
-- Remove IX_tbl_ProtocolCommands_TransactionID since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_TransactionID' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_TransactionID ON tbl_ProtocolCommands
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_ProtocolCommands_TransactionID_Time_Stamp_ResultID' AND object_id = OBJECT_ID('tbl_ProtocolCommands'))
DROP INDEX IX_tbl_ProtocolCommands_TransactionID_Time_Stamp_ResultID ON tbl_ProtocolCommands
GO
CREATE INDEX IX_tbl_ProtocolCommands_TransactionID_Time_Stamp_ResultID ON tbl_ProtocolCommands (TransactionID, Time_stamp, ResultID)
GO
UPDATE STATISTICS tbl_ProtocolCommands;
GO
-- For Admin-Audit Log
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_AdminActions_Time_stamp' AND object_id = OBJECT_ID('tbl_AdminActions'))
DROP INDEX IX_tbl_AdminActions_Time_stamp ON tbl_AdminActions
GO
CREATE INDEX IX_tbl_AdminActions_Time_stamp ON tbl_AdminActions (Timestamp)
GO
UPDATE STATISTICS tbl_AdminActions;
GO
-- For Admin-Authentications
-- Remove IX_tbl_Authentications_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_Time_stamp' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX IX_tbl_Authentications_Time_stamp ON tbl_Authentications
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_Time_stamp_Protocol' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX IX_tbl_Authentications_Time_stamp_Protocol ON tbl_Authentications
GO
CREATE INDEX IX_tbl_Authentications_Time_stamp_Protocol ON tbl_Authentications (Time_stamp, Protocol)
GO
UPDATE STATISTICS tbl_Authentications;
GO
-- For Troubleshooting-Failed Logins
-- Remove IX_tbl_Authentications_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_Time_stamp' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX IX_tbl_Authentications_Time_stamp ON tbl_Authentications
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Authentications_Time_stamp_SiteName_ResultID' AND object_id = OBJECT_ID('tbl_Authentications'))
DROP INDEX IX_tbl_Authentications_Time_stamp_SiteName_ResultID ON tbl_Authentications
GO
CREATE INDEX IX_tbl_Authentications_Time_stamp_SiteName_ResultID ON tbl_Authentications (Time_stamp, SiteName, ResultID)
GO
UPDATE STATISTICS tbl_Authentications;
GO
-- Content Integrity Control
-- [Nothing]
-- Reports: Event Rules (all), Troubleshooting-Event Rules Failuer
-- Remove IX_tbl_Actions_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Actions_Time_stamp' AND object_id = OBJECT_ID('tbl_Actions'))
DROP INDEX IX_tbl_Actions_Time_stamp ON tbl_Actions
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_Actions_Time_stamp_EventID_TransactionID' AND object_id = OBJECT_ID('tbl_Actions'))
DROP INDEX IX_tbl_Actions_Time_stamp_EventID_TransactionID ON tbl_Actions
GO
CREATE INDEX IX_tbl_Actions_Time_stamp_EventID_TransactionID ON tbl_Actions (Time_stamp, EventID, TransactionID)
GO
UPDATE STATISTICS tbl_Actions;
GO
-- Event Rules - Just Transfers
-- Remove IX_tbl_EventRules_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_EventRules_Time_stamp' AND object_id = OBJECT_ID('tbl_EventRules'))
DROP INDEX IX_tbl_EventRules_Time_stamp ON tbl_EventRules
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_EventRules_Time_stamp_TransactionID' AND object_id = OBJECT_ID('tbl_EventRules'))
DROP INDEX IX_tbl_EventRules_Time_stamp_TransactionID ON tbl_EventRules
GO
CREATE INDEX IX_tbl_EventRules_Time_stamp_TransactionID ON tbl_EventRules (Time_stamp, TransactionID)
GO
UPDATE STATISTICS tbl_EventRules;
GO
-- For Troubleshooting-Socket Connection Errors
-- Remove IX_tbl_SocketConnections_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_Time_stamp' AND object_id = OBJECT_ID('tbl_SocketConnections'))
DROP INDEX IX_tbl_SocketConnections_Time_stamp ON tbl_SocketConnections
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_SocketConnections_Time_stamp_ResultID' AND object_id = OBJECT_ID('tbl_SocketConnections'))
DROP INDEX IX_tbl_SocketConnections_Time_stamp_ResultID ON tbl_SocketConnections
GO
CREATE INDEX IX_tbl_SocketConnections_Time_stamp_ResultID ON tbl_SocketConnections (Time_stamp, ResultID)
GO
UPDATE STATISTICS tbl_SocketConnections;
GO
-- For Workspaces-Files Picked Up
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_OutlookReport_Type_TransactionDate' AND object_id = OBJECT_ID('tbl_OutlookReport'))
DROP INDEX IX_tbl_OutlookReport_Type_TransactionDate ON tbl_OutlookReport
GO
CREATE INDEX IX_tbl_OutlookReport_Type_TransactionDate ON tbl_OutlookReport (Type, TransactionDate)
GO
-- For Workspaces-Folders Shared, Unshared reports
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_OutlookReport_WorkspaceID' AND object_id = OBJECT_ID('tbl_OutlookReport'))
DROP INDEX IX_tbl_OutlookReport_WorkspaceID ON tbl_OutlookReport
GO
CREATE INDEX IX_tbl_OutlookReport_WorkspaceID ON tbl_OutlookReport (WorkspaceID)
GO
UPDATE STATISTICS tbl_OutlookReport;
GO
-- For Workspaces-Folders Shared, Unshared reports
-- Remove IX_tbl_WorkspaceActions_Time_stamp since won't be necessary
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_Time_stamp' AND object_id = OBJECT_ID('tbl_WorkspaceActions'))
DROP INDEX IX_tbl_WorkspaceActions_Time_stamp ON tbl_WorkspaceActions
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_tbl_WorkspaceActions_Time_stamp_Action' AND object_id = OBJECT_ID('tbl_WorkspaceActions'))
DROP INDEX IX_tbl_WorkspaceActions_Time_stamp_Action ON tbl_WorkspaceActions
GO
CREATE INDEX IX_tbl_WorkspaceActions_Time_stamp_Action ON tbl_WorkspaceActions (Time_stamp, Action)
GO
UPDATE STATISTICS tbl_WorkspaceActions;
GO

67
sql/Purge Fact Tables.sql Normal file
View File

@ -0,0 +1,67 @@
/*
Script by: Jonathan Branan, 8-10-2020
Purpose: To trim uneeded data from fact tables in EFT's database. A simple function that allows a specification of 'daysSaved'.
DISCLAIMER: Use at your own risk. Globalscape does not accept ANY responsiblity for any unexpected outcomes as a result of use of this script.
Version 1.0 - Added before and after row counts, status updates and set default retention period to match EFT's Purge Script.
*/
DECLARE @count INT
DECLARE @daysSaved DATETIME2
--Set the integer "60" to the amount of days you would like to retain in the fact tables.
SET @daysSaved = DATEADD(DAY, -60, GETDATE())
PRINT 'Fact Table Purge Version 1.0'
PRINT ''
PRINT 'Row count of Fact Tables before the purge:'
PRINT ''
--Initial Row Count
select @count = count(*) from [dbo].[tbl_Report_Exec_Summ] PRINT ' tbl_Report_Exec_Summ count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic1] PRINT ' tbl_Report_Traffic1 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic2] PRINT ' tbl_Report_Traffic2 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic3] PRINT ' tbl_Report_Traffic3 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic4] PRINT ' tbl_Report_Traffic4 count = ' +CAST(@count AS NVARCHAR)
PRINT ''
PRINT 'Purging Fact Tables...'
PRINT ''
--Purge Fact Tables
PRINT 'Purging from tbl_Report_Exec_Summ...'
DELETE FROM tbl_Report_Exec_Summ WHERE DayOfRecord < @daysSaved
PRINT ''
PRINT 'Purging from tbl_Report_Traffic1...'
DELETE FROM tbl_Report_Traffic1 WHERE DayOfRecord < @daysSaved
PRINT ''
PRINT 'Purging from tbl_Report_Traffic2...'
DELETE FROM tbl_Report_Traffic2 WHERE DayOfRecord < @daysSaved
PRINT ''
PRINT 'Purging from tbl_Report_Traffic3...'
DELETE FROM tbl_Report_Traffic3 WHERE DayOfRecord < @daysSaved
PRINT ''
PRINT 'Purging from tbl_Report_Traffic4...'
DELETE FROM tbl_Report_Traffic4 WHERE DayOfRecord < @daysSaved
PRINT ''
PRINT 'Purging Complete'
PRINT ''
PRINT 'Row counts of Fact Tables after the purge:'
PRINT ''
--Final Row Count
select @count = count(*) from [dbo].[tbl_Report_Exec_Summ] PRINT ' tbl_Report_Exec_Summ count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic1] PRINT ' tbl_Report_Traffic1 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic2] PRINT ' tbl_Report_Traffic2 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic3] PRINT ' tbl_Report_Traffic3 count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from [dbo].[tbl_Report_Traffic4] PRINT ' tbl_Report_Traffic4 count = ' +CAST(@count AS NVARCHAR)
PRINT ''
PRINT 'Done'

749
sql/PurgeSQLEFTData.sql Normal file
View File

@ -0,0 +1,749 @@
-- EFT Purging Script
-- Goal: Allow customers to purge data from EFT
-- Change Log:
-- 0.1: Set batch size at 100,000
-- Removed SELECT and extra PRINTT statements.
-- 0.2: Changed to purge up to 60 days per customer request
-- 0.3: Modified script to not assume cascading deletes and to
-- explicitly delete from all tables
-- Modified script to default 'purgesize' to 10,000
-- instead of 1,000
-- 0.4 Added AS2 and SAT purging
-- 0.5 Subset table wasn't being dropped.
PRINT 'Script started at: ' + CAST(CURRENT_TIMESTAMP AS NVARCHAR)
USE EFTDB
-- This procedure will print the version of this script
IF OBJECT_ID('dbo.sp_PurgeEFTTransactionsVersion') IS NOT NULL
DROP PROC dbo.sp_PurgeEFTTransactionsVersion
GO
CREATE PROCEDURE sp_PurgeEFTTransactionsVersion
AS
PRINT 'GlobalSCAPE, Inc. Purge Script Version 0.5'
GO
-- This procedure delete EFT transactions from a given table.
IF OBJECT_ID('dbo.sp_RemoveTxnsFromTable') IS NOT NULL
DROP PROC dbo.sp_RemoveTxnsFromTable
GO
CREATE PROCEDURE sp_RemoveTxnsFromTable @txns_id_table_name nvarchar(200),
@tblname nvarchar(200),
@debug bit = 0
AS
DECLARE @sql nvarchar(4000),
@activeTableName nvarchar(220)
BEGIN TRY
BEGIN TRANSACTION
SET @activeTableName = quotename(N'tbl_' + @tblname)
IF @debug = 1 BEGIN
PRINT 'Deleting Transactions from Table: ' + @activeTableName
END
-- Delete the data from the active table
SET @sql =
'DELETE FROM ' + @activeTableName + ' ' +
'WHERE TransactionID IN ' +
'(' +
'SELECT TransactionID ' +
'FROM ' + @txns_id_table_name +
')'
IF @debug = 1 PRINT @sql
EXEC sp_executesql @sql
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
GO
-- This procedure delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_RemoveTxns') IS NOT NULL
DROP PROC dbo.sp_RemoveTxns
GO
CREATE PROCEDURE sp_RemoveTxns @txns_id_table_name nvarchar(200),
@debug bit = 0
AS
-- We want to wrap these deletes in a transactions so that we don't end
-- up with orphaned rows.
BEGIN TRY
BEGIN TRANSACTION
-- To verify that all children were truly deleted, also explicitly
-- delete from their tables.
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'AdminActions', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'ProtocolCommands', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'Actions', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'EventRules', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'ClientOperations', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'SocketConnections', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'Authentications', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'CustomCommands', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'OutlookReport', @debug
-- Remove from the transactions table
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'Transactions', @debug
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
GO
-- This procedure will delete AS2 transactions.
IF OBJECT_ID('dbo.sp_RemoveAS2Txns') IS NOT NULL
DROP PROC dbo.sp_RemoveAS2Txns
GO
CREATE PROCEDURE sp_RemoveAS2Txns @txns_id_table_name nvarchar(200),
@debug bit = 0
AS
-- We want to wrap these deletes in a transactions so that we don't end
-- up with orphaned rows.
BEGIN TRY
BEGIN TRANSACTION
-- To verify that all children were truly deleted, also explicitly
-- delete from their tables.
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'AS2Actions', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'AS2Files', @debug
EXEC sp_RemoveTxnsFromTable @txns_id_table_name, N'AS2Transactions', @debug
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
GO
-- This procedure will delete EFT transactions from a all tables.
IF OBJECT_ID('dbo.sp_PurgeEFTTransactions') IS NOT NULL BEGIN
DROP PROC dbo.sp_PurgeEFTTransactions
END
GO
-- By default, this procedure will purge data from 1990 to 60 days ago.
CREATE PROCEDURE sp_PurgeEFTTransactions @startTime datetime = NULL,
@stopTime datetime = NULL,
@purgeSize numeric = NULL,
@debug bit = 0
AS
EXEC sp_PurgeEFTTransactionsVersion
DECLARE @iteration numeric
SET @iteration = 0
DECLARE @deleteHappened numeric
SET @deleteHappened = 1
WHILE @deleteHappened = 1
BEGIN
SET @deleteHappened = 0
SET @iteration = @iteration + 1
PRINT ''
PRINT 'Script iteration: ' + CAST(@iteration as NVARCHAR)
BEGIN TRY
SET NOCOUNT ON
IF @startTime IS NULL BEGIN
set @startTime = '19700101 00:00:00'
END
IF @stopTime IS NULL BEGIN
SET @stopTime = DATEADD(DAY, -60, GETDATE())
END
IF @purgeSize IS NULL BEGIN
set @purgeSize = 10000
END
PRINT 'Purging Transactions from ' + CAST(@startTime as NVARCHAR) + ' to ' +
CAST(@stopTime AS NVARCHAR) + ' in batches of ' + CAST(@purgeSize AS NVARCHAR)
DECLARE @tbl_TablesToPurge TABLE
(
[TableName] NVARCHAR(400) NOT NULL
)
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_AdminActions')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_ProtocolCommands')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_Actions')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_EventRules')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_ClientOperations')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_SocketConnections')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_Authentications')
INSERT @tbl_TablesToPurge ([TableName]) VALUES (N'tbl_CustomCommands')
-- Create a cursor to walk through each table name
DECLARE @tableName NVARCHAR(400)
DECLARE tablename_cursor CURSOR FOR
SELECT [TableName]
FROM @tbl_TablesToPurge
OPEN tablename_cursor;
-- Perform the first fetch and store the values in variables.
-- Note: The variables are in the same order as the columns
-- in the SELECT statement.
FETCH NEXT FROM tablename_cursor INTO @tableName
CREATE TABLE #tbl_TxnsToBePurged
(
TransactionID numeric,
CONSTRAINT [PK_tbl_TxnsToBePurged] PRIMARY KEY CLUSTERED
(
TransactionID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE #tbl_SubsetTxnsToBePurged
(
TransactionID numeric,
CONSTRAINT [PK_tbl_SubsetTxnsToBePurged] PRIMARY KEY CLUSTERED
(
TransactionID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
-- Now we'll remove the rows from the active tables.
IF @debug = 1 BEGIN
PRINT 'Now purging transactions from table ' + @tableName
END
-- Unfortunately, the name of the TimeStamp column is not the same
-- for every table. So, I've built this logic to generate the correct
-- name for the corresponding table
DECLARE @tsColumnName NVARCHAR(400)
SET @tsColumnName = 'Time_stamp'
IF @tableName = 'tbl_AdminActions' BEGIN
SET @tsColumnName = 'Timestamp'
END
DECLARE @sql nvarchar(4000)
SET @sql =
'INSERT INTO #tbl_TxnsToBePurged ' +
'SELECT DISTINCT(TransactionID) TransactionID ' +
'FROM ' + @tableName + ' ' +
'WHERE ' + @tsColumnName + ' BETWEEN @lstartTime AND @lstopTime ' +
'GROUP BY TransactionID'
EXEC sp_executesql @sql, N'@lstartTime datetime, @lstopTime datetime', @startTime, @stopTime
DECLARE @resultCount numeric
DECLARE @lastResultCount numeric
SET @lastResultCount = -1
SELECT @resultCount = count(*) FROM #tbl_TxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
WHILE ((@resultCount > 0) AND (@resultCount != @lastResultCount)) BEGIN
SET @lastResultCount = @resultCount
SET @sql =
'INSERT INTO #tbl_SubsetTxnsToBePurged ' +
'SELECT a.TransactionID TransactionID ' +
'FROM (SELECT TOP ' + CAST(@purgeSize AS NVARCHAR) + ' #tbl_TxnsToBePurged.TransactionID FROM #tbl_TxnsToBePurged) a ' +
'LEFT JOIN tbl_Transactions tempTable ON a.TransactionID = tempTable.ParentTransactionID ' +
'WHERE tempTable.ParentTransactionID IS NULL ' +
'ORDER BY a.TransactionID'
IF @debug = 1 BEGIN
PRINT 'SQL to determine PurgeSet: ' + @sql
END
EXEC sp_executesql @sql
SELECT @resultCount = count(*) FROM #tbl_SubsetTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number Txns To Be Purged This Round: ' + CAST(@resultCount AS NVARCHAR)
END
EXEC sp_RemoveTxns N'#tbl_SubsetTxnsToBePurged', @debug
IF @debug = 1 BEGIN
PRINT 'Successfully deleted transactions from tbl_Transactions and associated tables'
END
DELETE FROM #tbl_TxnsToBePurged
WHERE TransactionID IN
(
SELECT #tbl_SubsetTxnsToBePurged.TransactionID TransactionID
FROM #tbl_SubsetTxnsToBePurged
)
IF @debug = 1 BEGIN
PRINT 'Successfully deleted transactions from #tbl_TxnsToBePurged'
END
DELETE FROM #tbl_SubsetTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Determing number of rows remaining to be Purged.'
END
IF (@resultCount > 0) BEGIN
SET @deleteHappened = 1
END
SELECT @resultCount = count(*) FROM #tbl_TxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'BOT of Loop: Total Number Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
END
-- We want to delete all transactions from the temporary table
DELETE FROM #tbl_TxnsToBePurged
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM tablename_cursor INTO @tableName
END
CLOSE tablename_cursor;
--
-- Purge AS2 transactions
--
SET @sql =
'INSERT INTO #tbl_TxnsToBePurged ' +
'SELECT DISTINCT(TransactionID) TransactionID ' +
'FROM tbl_AS2Transactions ' +
'WHERE CompleteTime BETWEEN @lstartTime AND @lstopTime ' +
'GROUP BY TransactionID'
EXEC sp_executesql @sql, N'@lstartTime datetime, @lstopTime datetime', @startTime, @stopTime
SET @lastResultCount = -1
SELECT @resultCount = count(*) FROM #tbl_TxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number AS2 Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
WHILE ((@resultCount > 0) AND (@resultCount != @lastResultCount)) BEGIN
SET @lastResultCount = @resultCount
SET @sql =
'INSERT INTO #tbl_SubsetTxnsToBePurged ' +
'SELECT TOP ' + CAST(@purgeSize AS NVARCHAR) + ' #tbl_TxnsToBePurged.TransactionID ' +
'FROM #tbl_TxnsToBePurged ' +
'ORDER BY TransactionID'
IF @debug = 1 BEGIN
PRINT 'SQL to determine AS2 PurgeSet: ' + @sql
END
EXEC sp_executesql @sql
SELECT @resultCount = count(*) FROM #tbl_SubsetTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number AS2 Txns To Be Purged This Round: ' + CAST(@resultCount AS NVARCHAR)
END
EXEC sp_RemoveAS2Txns N'#tbl_SubsetTxnsToBePurged', @debug
IF @debug = 1 BEGIN
PRINT 'Successfully deleted AS2 transactions'
END
DELETE FROM #tbl_TxnsToBePurged
WHERE TransactionID IN
(
SELECT #tbl_SubsetTxnsToBePurged.TransactionID TransactionID
FROM #tbl_SubsetTxnsToBePurged
)
IF @debug = 1 BEGIN
PRINT 'Successfully deleted transactions from #tbl_TxnsToBePurged'
END
DELETE FROM #tbl_SubsetTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Determing number of rows remaining to be Purged.'
END
IF (@resultCount > 0) BEGIN
SET @deleteHappened = 1
END
SELECT @resultCount = count(*) FROM #tbl_TxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'BOT of AS2 Loop: Total Number Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
END
DELETE FROM #tbl_TxnsToBePurged
--
-- Purge SAT transactions
--
CREATE TABLE #tbl_SATTxnsToBePurged
(
ID numeric,
CONSTRAINT [PK_tbl_SATTxnsToBePurged] PRIMARY KEY CLUSTERED
(
ID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE #tbl_SubsetSATTxnsToBePurged
(
ID numeric,
CONSTRAINT [PK_tbl_SubsetSATTxnsToBePurged] PRIMARY KEY CLUSTERED
(
ID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SET @sql =
'INSERT INTO #tbl_SATTxnsToBePurged ' +
'SELECT DISTINCT(ID) ID ' +
'FROM tbl_SAT_Transactions ' +
'WHERE time_stamp BETWEEN @lstartTime AND @lstopTime ' +
'GROUP BY ID'
EXEC sp_executesql @sql, N'@lstartTime datetime, @lstopTime datetime', @startTime, @stopTime
SET @lastResultCount = -1
SELECT @resultCount = count(*) FROM #tbl_SATTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number SAT Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
WHILE ((@resultCount > 0) AND (@resultCount != @lastResultCount)) BEGIN
SET @lastResultCount = @resultCount
SET @sql =
'INSERT INTO #tbl_SubsetSATTxnsToBePurged ' +
'SELECT TOP ' + CAST(@purgeSize AS NVARCHAR) + ' #tbl_SATTxnsToBePurged.ID ' +
'FROM #tbl_SATTxnsToBePurged ' +
'ORDER BY ID'
IF @debug = 1 BEGIN
PRINT 'SQL to determine SAT PurgeSet: ' + @sql
END
EXEC sp_executesql @sql
SELECT @resultCount = count(*) FROM #tbl_SubsetSATTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number SAT Txns To Be Purged This Round: ' + CAST(@resultCount AS NVARCHAR)
END
BEGIN TRANSACTION
DELETE FROM tbl_SAT_Emails
WHERE ID IN
(
SELECT ID
FROM #tbl_SubsetSATTxnsToBePurged
)
DELETE FROM tbl_SAT_Files
WHERE ID IN
(
SELECT ID
FROM #tbl_SubsetSATTxnsToBePurged
)
DELETE FROM tbl_SAT_Transactions
WHERE ID IN
(
SELECT ID
FROM #tbl_SubsetSATTxnsToBePurged
)
COMMIT TRANSACTION
IF @debug = 1 BEGIN
PRINT 'Successfully deleted SAT transactions'
END
DELETE FROM #tbl_SATTxnsToBePurged
WHERE ID IN
(
SELECT #tbl_SubsetSATTxnsToBePurged.ID ID
FROM #tbl_SubsetSATTxnsToBePurged
)
IF @debug = 1 BEGIN
PRINT 'Successfully deleted transactions from #tbl_TxnsToBePurged'
END
DELETE FROM #tbl_SubsetTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'Determing number of rows remaining to be Purged.'
END
IF (@resultCount > 0) BEGIN
SET @deleteHappened = 1
END
SELECT @resultCount = count(*) FROM #tbl_SATTxnsToBePurged
IF @debug = 1 BEGIN
PRINT 'BOT of SAT Loop: Total Number Txns To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
END
DELETE FROM #tbl_SATTxnsToBePurged
--
-- Purge AWESteps transactions
--
CREATE TABLE #tbl_AWEStepsToBePurged
(
ID numeric,
CONSTRAINT [PK_tbl_AWEStepsToBePurged] PRIMARY KEY CLUSTERED
(
ID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE #tbl_SubsetAWEStepsToBePurged
(
ID numeric,
CONSTRAINT [PK_tbl_SubsetAWEStepsToBePurged] PRIMARY KEY CLUSTERED
(
ID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SET @sql =
'INSERT INTO #tbl_AWEStepsToBePurged ' +
'SELECT DISTINCT(ID) ID ' +
'FROM tbl_AWESteps ' +
'WHERE time_stamp BETWEEN @lstartTime AND @lstopTime ' +
'GROUP BY ID'
EXEC sp_executesql @sql, N'@lstartTime datetime, @lstopTime datetime', @startTime, @stopTime
SET @lastResultCount = -1
SELECT @resultCount = count(*) FROM #tbl_AWEStepsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number AWESteps To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
WHILE ((@resultCount > 0) AND (@resultCount != @lastResultCount)) BEGIN
SET @lastResultCount = @resultCount
SET @sql =
'INSERT INTO #tbl_SubsetAWEStepsToBePurged ' +
'SELECT TOP ' + CAST(@purgeSize AS NVARCHAR) + ' #tbl_AWEStepsToBePurged.ID ' +
'FROM #tbl_AWEStepsToBePurged ' +
'ORDER BY ID'
IF @debug = 1 BEGIN
PRINT 'SQL to determine AWESteps PurgeSet: ' + @sql
END
EXEC sp_executesql @sql
SELECT @resultCount = count(*) FROM #tbl_SubsetAWEStepsToBePurged
IF @debug = 1 BEGIN
PRINT 'Total Number AWESteps To Be Purged This Round: ' + CAST(@resultCount AS NVARCHAR)
END
BEGIN TRANSACTION
DELETE FROM tbl_AWESteps
WHERE ID IN
(
SELECT ID
FROM #tbl_SubsetAWEStepsToBePurged
)
COMMIT TRANSACTION
IF @debug = 1 BEGIN
PRINT 'Successfully deleted AWESteps'
END
DELETE FROM #tbl_AWEStepsToBePurged
WHERE ID IN
(
SELECT #tbl_AWEStepsToBePurged.ID ID
FROM #tbl_SubsetAWEStepsToBePurged
)
IF @debug = 1 BEGIN
PRINT 'Successfully deleted rows from #tbl_AWEStepsToBePurged'
END
DELETE FROM #tbl_SubsetAWEStepsToBePurged
IF @debug = 1 BEGIN
PRINT 'Determing number of rows remaining to be Purged.'
END
IF (@resultCount > 0) BEGIN
SET @deleteHappened = 1
END
SELECT @resultCount = count(*) FROM #tbl_AWEStepsToBePurged
IF @debug = 1 BEGIN
PRINT 'BOT of AWESteps Loop: Total Number Rows To Be Purged: ' + CAST(@resultCount AS NVARCHAR)
END
END
DELETE FROM #tbl_AWEStepsToBePurged
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0 BEGIN
ROLLBACK
END
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
-- Regardless of whether there was an error, we need to
-- remove the temporary table and dealloate the cursor
-- we created.
BEGIN TRY
DROP TABLE #tbl_TxnsToBePurged
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DROP TABLE #tbl_SubsetTxnsToBePurged
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DEALLOCATE id_cursor;
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DEALLOCATE tablename_cursor;
END TRY
BEGIN CATCH
END CATCH
--
-- drop sat and AWESteps temp tables
--
BEGIN TRY
DROP TABLE #tbl_SATTxnsToBePurged
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DROP TABLE #tbl_SubsetSATTxnsToBePurged
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DROP TABLE #tbl_AWEStepsToBePurged
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY
DROP TABLE #tbl_SubsetAWEStepsToBePurged
END TRY
BEGIN CATCH
END CATCH
END
GO
SET STATISTICS TIME OFF
EXEC sp_PurgeEFTTransactions NULL, NULL, 100000, 1
SET STATISTICS TIME OFF
PRINT ''
PRINT 'Script completed at: ' + CAST(CURRENT_TIMESTAMP AS NVARCHAR)
GO

34
sql/SQL_File_Import.ps1 Normal file
View File

@ -0,0 +1,34 @@
<#
Sql Import Script
Keith Lowery, Erich Leenheer, Jonathan Branan
This script is provided without warranty. Globalscape does not accept
responsibility for any unexpected outcomes that result from use of this script.
Version 1.0 Added variables and checking for open sql connections
Version 1.1 Added comments
#>
# SQL Instance
$DBServer = "192.168.102.18\Globalscape"
#Database Name
$DBName = "eft1"
#Folder where the .sql files are stored
$databasefolder = "C:\Temp\sql"
#Connect to SQL Server
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString= "Server=$DBServer;Database=$DBName;Integrated Security=True;"
$sqlConnection.Open()
if ($sqlConnection.State -ne [Data.ConnectionState]::Open) {
"Connection to DB is not open."
Exit
}
Get-ChildItem $databaseFolder -Filter *.sql -Recurse | ForEach-Object { sqlcmd -S $DBServer -d $DBName -E -i $_.FullName }
if ($sqlConnection.State -eq [Data.ConnectionState]::Open) {
$sqlConnection.Close()
}

View File

@ -0,0 +1,3 @@
SELECT *
FROM tbl_ClientOperations
WHERE Protocol = 'AS2' AND Operation = 'UPLOAD_MOVE' AND LocalPath LIKE '%%' AND BytesTransferred LIKE '0' --AND Time_stamp > '2020-04-1' AND Time_stamp < '2020-04-2'

63
sql/eftArmGetSettings.ps1 Normal file
View File

@ -0,0 +1,63 @@
<#
.SYNOPSIS
Use EFT's COM interface to configure ARM settings for auditing and reporting.
.DESCRIPTION
Use EFT's COM interface to retrieve ARM settings
.PARAMETER serverName
.PARAMETER eftAdminPort
.PARAMETER authMethod
.PARAMETER eftAdminName
.PARAMETER eftAdminPassword
#>
param(
[Parameter(Mandatory=$False)][string]$serverName = "localhost",
[Parameter(Mandatory=$False)][int]$eftAdminPort = 1100,
[Parameter(Mandatory=$False)][int]$authMethod = 1,
[Parameter(Mandatory=$False)][string]$eftAdminName = "",
[Parameter(Mandatory=$False)][string]$eftAdminPassword = ""
)
#------------------------------------------------------------
# login as admin
#------------------------------------------------------------
try {
$oServer = New-Object -ComObject 'SFTPComInterface.CIServer'
$oServer.ConnectEx( $serverName, $eftAdminPort, $authMethod, $eftAdminName, $eftAdminPassword );
Write-Host "connected"
}
catch {
$errorMessage = $_.Exception.Message;
Write-Host "failed to connect to server ${serverName}: ${errorMessage}"
Exit;
}
#------------------------------------------------------------
# get ARM settings
#------------------------------------------------------------
Write-Output ("ARMServerName: {0}" -f $oServer.ARMServerName)
Write-Output ("ARMDatabaseName: {0}" -f $oServer.ARMDatabaseName)
Write-Output ("ARMUserName: {0}" -f $oServer.ARMUserName)
Write-Output ("ARMPassword: {0}" -f $oServer.ARMPassword)
Write-Output ("ARMDatabaseType: {0}" -f $oServer.ARMDatabaseType)
Write-Output ("ARMAuthenticationType: {0}" -f $oServer.ARMAuthenticationType)
#------------------------------------------------------------
# close resources
#------------------------------------------------------------
$oServer.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($oServer) | out-null
Remove-Variable oServer

View File

@ -0,0 +1,43 @@
-- [Optional] Set Database Recovery Mode to Simple
-- [Optional] Comment out lines 20-27 from sp_RemoveTxns (these seem unnecessary since the auxiliary tables are cleaned up by their cascade delete rule)
USE jonathan27
GO
-- CREATE INDEXES TO SPEED UP TRANSACTION PURGE
-- Note that these commands took appromimately 2 minutes 30 seconds to complete in total.
-- This IX_tbl_Transactions_ParentTransactionID index provides the most significant performance improvement
-- because otherwise for each record being deleted it would have to perform a full table scan to find any records
-- that have it as a parent. The table scan is likely to be very slow when tbl_Transactions is large. With this
-- index the query can do an index seek which is a much faster operation.
CREATE NONCLUSTERED INDEX IX_tbl_Transactions_ParentTransactionID
ON [dbo].[tbl_Transactions] ([ParentTransactionID])
GO
CREATE NONCLUSTERED INDEX IX_tbl_ProtocolCommands_TransactionID
ON [dbo].[tbl_ProtocolCommands] ([TransactionID])
INCLUDE ([ProtocolCommandID])
GO
CREATE NONCLUSTERED INDEX IX_tbl_SocketConnections_TransactionID
ON [dbo].[tbl_SocketConnections] ([TransactionID])
INCLUDE ([SocketID])
GO
-- PERFORM PURGE
DECLARE @return_value int
DECLARE @stopTimetemp DATETIME2
SET @stopTimetemp = DATEADD(DAY, -60, GETDATE())
EXEC @return_value = [dbo].[sp_PurgeEFTTransactions]
@startTime = N'19700101', -- Set to desired start time
@stopTime = @stopTimetemp, -- Set to desired stop time
@purgeSize = NULL,
@debug = 0
SELECT 'Return Value' = @return_value
-- DELETE INDEXES CREATED TO SPEED UP PURGE
DROP INDEX IX_tbl_Transactions_ParentTransactionID ON [dbo].[tbl_Transactions]
DROP INDEX IX_tbl_ProtocolCommands_TransactionID ON [dbo].[tbl_ProtocolCommands]
DROP INDEX IX_tbl_SocketConnections_TransactionID ON [dbo].[tbl_SocketConnections]
GO

188
sql/insight/SQL cleanup.sql Normal file
View File

@ -0,0 +1,188 @@
-- ******************** WARNING ********************
-- EFT is about to upgrade your database! If necessary please check with your database administrator before proceeding.
--
-- This script will add 3 stored procedures, you will have to call the procedures manually
-- Samples of how to run the stored procedures is located at the end of this script
-- USE EFTInsight
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- sp_countEFTInsightRows
-- This stored procedure will count the number of rows.
--
-- Parameters
-- @DaystoKeep - default is 0, if set to a value greater than 0 the procedure will also show how many rows will be deleted
CREATE PROCEDURE sp_countEFTInsightRows @DaystoKeep int = 0
AS
DECLARE @DateToPurgeTo DATETIME
-- If @DaystoKeep = 0, then keep everything
IF @DaystoKeep = 0 OR @DaystoKeep IS NULL
BEGIN
SELECT 'Action' as tableName, count(1) AS rows, MIN([timestamp]) as oldestRow FROM Action
UNION ALL
SELECT 'Authentication', count(1), MIN([timestamp]) FROM Authentication
UNION ALL
SELECT 'AweTask', count(1), MIN([started]) FROM AweTask
UNION ALL
SELECT 'EventRule', count(1), MIN([timestamp]) FROM EventRule
UNION ALL
SELECT 'Evaluation', count(1), MIN([EvaluateeStartDate]) FROM Evaluation
UNION ALL
SELECT 'LogEntry', count(1), MIN([entrytime]) FROM LogEntry
UNION ALL
SELECT 'Message', count(1), MIN([created]) FROM Message
UNION ALL
SELECT 'Transfer', count(1), MIN([timestamp]) FROM Transfer
ORDER BY rows DESC
END
ELSE
BEGIN
SET @DaystoKeep = @DaystoKeep * -1; -- e.g. 60 becomes -60
SET @DateToPurgeTo = DATEADD(day,@DaystoKeep,GetDate())
SELECT 'Action' as tableName, count(1) AS rows, MIN([timestamp]) as oldestRow, sum(CASE WHEN [timestamp] < @DateToPurgeTo THEN 1 ELSE 0 END ) as rowsOlderThanCutOff FROM Action
UNION ALL
SELECT 'Authentication', count(1), MIN([timestamp]), sum(CASE WHEN [timestamp] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM Authentication
UNION ALL
SELECT 'AweTask', count(1), MIN([started]), sum(CASE WHEN [started] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM AweTask
UNION ALL
SELECT 'EventRule', count(1), MIN([timestamp]), sum(CASE WHEN [timestamp] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM EventRule
UNION ALL
SELECT 'Evaluation', count(1), MIN([EvaluateeStartDate]), sum(CASE WHEN [EvaluateeStartDate] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM Evaluation
UNION ALL
SELECT 'LogEntry', count(1), MIN([entrytime]), sum(CASE WHEN [entrytime] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM LogEntry
UNION ALL
SELECT 'Message', count(1), MIN([created]), sum(CASE WHEN [created] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM Message
UNION ALL
SELECT 'Transfer', count(1), MIN([timestamp]), sum(CASE WHEN [timestamp] < @DateToPurgeTo THEN 1 ELSE 0 END ) FROM Transfer
ORDER BY rows DESC
END
GO
-- sp_purgeMarkedForDeletion
-- This stored procedure will purge all rows that have the column MarkedForDeletion set to 1
create Procedure [dbo].[sp_purgeMarkedForDeletion]
AS
BEGIN
DELETE FROM [dbo].[Action] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Authentication] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[AweTask] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Configuration] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Evaluation] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Expectation] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[ExpectationDashboard] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[License] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[LogEntry] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Message] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Queue] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[SecurityPrincipal] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Server] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Session] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Site] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[TableSyncStatus] WHERE [MarkedForDeletion] = 1
DELETE FROM [dbo].[Transfer] WHERE [MarkedForDeletion] = 1
END;
GO
-- sp_purgeEFTInsight
-- This stored procedure will delete rows older than number of days specified by @DaystoKeep
--
-- Parameters
-- @DaystoKeep - default is 180, the procedure will purge all rows older than @DaystoKeep old
-- @debug - default is 0, if set to 1 the procedure will show some debug functions while running
CREATE PROCEDURE sp_purgeEFTInsight @DaystoKeep int = 180,
@debug bit = 0
AS
DECLARE @DateToPurgeTo DATETIME
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' sp_PurgeEFTInsight started';
-- If @DaystoKeep = 0, then purge only older than 40 years
IF @DaystoKeep = 0 OR @DaystoKeep IS NULL
SET @DaystoKeep = -15000; -- Go back 40 years
ELSE
SET @DaystoKeep = @DaystoKeep * -1; -- e.g. 60 becomes -60
SET @DateToPurgeTo = DATEADD(day,@DaystoKeep,GetDate())
BEGIN TRY
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for Action about to be purged';
DELETE FROM [Action] WHERE [Timestamp] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for Authentication about to be purged';
DELETE FROM [Authentication] WHERE [Timestamp] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for AweTask about to be purged';
DELETE FROM [AweTask] WHERE [started] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for EventRule about to be purged';
DELETE FROM [EventRule] WHERE [Timestamp] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for Evaluation about to be purged';
DELETE FROM [Evaluation] WHERE [EvaluateeStartDate] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for LogEntry about to be purged';
DELETE FROM [LogEntry] WHERE [entrytime] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for Message about to be purged';
DELETE FROM [Message] WHERE [created] <= @DateToPurgeTo
COMMIT TRANSACTION
BEGIN TRANSACTION
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' transactions for Transfer about to be purged';
DELETE FROM [Transfer] WHERE [timestamp] <= @DateToPurgeTo
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- If error, roll back
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000),
@ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
IF @debug = 1 PRINT CONVERT(varchar(30),CURRENT_TIMESTAMP,8) + ' sp_PurgeEFTInsight ended';
GO
--EXEC sp_countEFTInsightRows NULL
--GO
--EXEC sp_purgeMarkedForDeletion
--GO
--EXEC sp_countEFTInsightRows 180
--GO
--EXEC sp_purgeEFTInsight 180, 1
--GO
--EXEC sp_countEFTInsightRows
--GO

25
sql/invokeSQL.ps1 Normal file
View File

@ -0,0 +1,25 @@
#James McGregor uwu and Jonathan Branan
$ConnectionString = "server=localhost\SQLEXPRESS,1433;database=EFTDB;UID=eft;Pwd=password1;"
$queryFile = "C:\Users\jbranan\Desktop\PurgeEFT.sql"
Function LogWrite
{
Param ([string]$logstring)
$curDate = getdate
$toWrite = $curDate + $logstring
Write-Host $toWrite
Add-content $Logfile -value $toWrite
}
Function getdate
{
Get-Date -Format "MM/dd/yyyy "
}
#$currenttime = getdate
$Logfile = "c:\Users\jbranan\Desktop\purge.log"
Write-Host "Running query for Jonny Boi"
$logstring = Invoke-Sqlcmd -ConnectionString $ConnectionString -InputFile $queryFile -Verbose 4>&1
Logwrite $logstring

11
sql/needyusers.sql Normal file
View File

@ -0,0 +1,11 @@
SELECT TOP 3 UserName, Count(*) As SuccessConnections
FROM tbl_Authentications
WHERE resultID = 0 AND protocol <> 'Administration' AND Time_stamp >= DATEADD(minute,-1440,GetDate())
GROUP BY UserName
ORDER BY SuccessConnections DESC
SELECT TOP 3 UserName, Count(*) As FailedConnections
FROM tbl_Authentications
WHERE resultID = 1 AND protocol <> 'Administration' AND Time_stamp >= DATEADD(minute,-1440,GetDate())
GROUP BY UserName
ORDER BY FailedConnections DESC

View File

@ -0,0 +1,3 @@
SELECT *
FROM tbl_ProtocolCommands
WHERE Protocol = 'HTTPS' AND Command = 'copy' AND CommandParameters LIKE '%filename.txt%' AND Time_stamp > '2020-04-1' AND Time_stamp < '2020-04-2'

12
sql/rowcount.sql Normal file
View File

@ -0,0 +1,12 @@
declare @count int
print 'Row counts before purge'
select @count = count(*) from [dbo].[tbl_AdminActions] print 'tbl_AdminActions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ProtocolCommands print 'tbl_ProtocolCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Actions print 'tbl_Actions count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_ClientOperations print 'tbl_ClientOperations count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_SocketConnections print 'tbl_SocketConnections count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Authentications print 'tbl_Authentications count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_CustomCommands print 'tbl_CustomCommands count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_EventRules print 'tbl_EventRules count = ' +CAST(@count AS NVARCHAR)
select @count = count(*) from tbl_Transactions print 'tbl_Transactions count = ' +CAST(@count AS NVARCHAR)

View File

@ -0,0 +1 @@
SELECT name, NameLowered, json_extract(GeneralTab, '$.HomeFolder'), datetime(json_extract(Stats, '$.LastConnectedTime'), 'unixepoch', 'localtime')FROM Client;

View File

@ -0,0 +1,10 @@
INSERT INTO "main"."Admin" ("id", "Name", "NameLowered", "Type", "LastActiveTime", "PasswordHash", "PasswordIsTemporary", "PasswordChangedTime", "PasswordHistory", "UnlockTime", "InvalidLoginAttempts", "Permissions") VALUES (X'b76a1d7bc3ad5ac4863606ce71ba3af3', 'Local computer\Administrators', 'local computer\administrators', '2', '1608331504', '', '1', '1608331504', '[]', '0', '[]', '{
"ACLs": [],
"Level": "Server",
"ManageCom": true,
"ManagePersonalData": true,
"ManageReporting": true,
"RestAccess": true,
"RestAdminRole": "server_full_access",
"SettingsTemplates": []
}');

View File

@ -0,0 +1 @@
UPDATE AdvancedWorkflow set settings = json_set(AdvancedWorkflow.Settings, '$.LogDir', '\\file.core.windows.net\gsbslogs\AWE\')

402
vbs/1ExportPermissions.vbs Normal file
View File

@ -0,0 +1,402 @@
'FILENAME: ExportVirtualPermissions.vbs
'DATE: 1 JUL 2011
'PROGRAMMER: A. ACUNA
'USE: Use this to export all the permissions in a site.
'**** run cmd "cscript (script location) > (location of output txt document)****
'Create GlobalSCAPE object
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
Dim strHost, strLogin, strPassword, strTextFile, strSite, strPort
Dim oSFTPServer, oSites, oSite
CRLF = (Chr(13)& Chr(10))
'Comment this next line if you want to use arguments passed to the script
If (ProcessArgs=-1) then wscript.quit
'Un-comment if you want to hardcode the variable info
REM strHost = "192.168.102.143"
REM strPort = "1100"
REM strLogin = "test"
REM strPassword = "test"
REM strTextFile = "output.txt"
REM strSite = "MySite"
WScript.Echo "Runtime Parameters:" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
'Get File Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create/overwrite log file
Set objLogFile = objFSO.CreateTextFile(strTextFile, True)
Call ConnectAndLogin()
Sub ConnectAndLogIn()
Dim WshShell
' Let's check to be sure we can connect to the specified EFT Server:
WScript.Echo "<CONNECTING TO SERVER>"
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
' NOTE we assume default ADMIN port of 1100 -- please chang this if you have
' manually configured your EFT to be different.
On Error Resume Next
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Echo Chr(9) & "Attempting to restart service..."
err.Clear
Set WshShell = WScript.CreateObject("WScript.Shell")
call WshShell.Run("net start ""eft server""", 1, true)
Set WshShell = nothing
WScript.Echo Chr(9) & "Waiting for 5 seconds for the service to initiate..."
WScript.Sleep 5000
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quit 253
Else
WScript.Echo Chr(9) & "Connected to " & strHost
end if
End If
On Error GoTo 0 ' resume error trapping
set oSites=oSFTPServer.Sites
Dim iCount
For iCount=0 to oSites.count - 1
Set oSite = oSites.Item(iCount)
if LCase(Trim(oSite.Name)) = LCase(Trim(strSite)) then
exit for
End if
Next
WScript.Echo Chr(9) & "Connected to site '" & oSite.Name & "'" & vbCrLf
End Sub
'==============================================================================
'
' ProcessArgs
'
' Parse the command-line arguments. Results are set in global variables
' (strHost, strLogin, strPassword, strTextFile, strSite, strPort ).
'
'==============================================================================
public function ProcessArgs
Dim iCount
Dim oArgs
on error resume next
' Default our arguments. Some are required.
strHost = ""
strLogin = ""
strPassword = ""
strPort = "1100"
strSite = ""
strTextFile=""
' Get the command-line arguments
'
Set oArgs = WScript.Arguments
if oArgs.Count > 0 then
' We have command-line arguments. Loop through them.
iCount = 0
ProcessArgs = 0
do while iCount < oArgs.Count
select case oArgs.Item(iCount)
'
' Server name argument
'
case "-s"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strHost = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' What port to connect to for EFT server. Default to 1100
'
case "-port"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPort = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin login name argument
'
case "-u"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strLogin = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin password argument
'
case "-p"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPassword = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Which site to look into. Defaults into 1.
'
case "-site"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strSite = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' CSVFile name argument
'
case "-f"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strTextFile = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Help option
'
case "-?"
Syntax
ProcessArgs = -1
exit function
'
' Invalid argument
'
case else
' Display the syntax and return an error
wscript.echo "Unknown argument: " & oArgs.Item(iCount) & vbCrLf
Syntax
ProcessArgs = -1
Exit function
end select
loop
Else
'
' There were no command-line arguments, display the syntax
' and return an error.
'
Syntax
ProcessArgs = -1
End if
Set oArgs = Nothing
If ( strHost = "" OR strLogin = "" or strSite = "" or strPassword = "" or strTextFile = "" ) Then
Syntax
ProcessArgs = -1
End If
End function ' ProcessArgs
REM Start code here
g_strVFSBuffer= ""
'Retrieve all the paths that have permissions in the config and decorate the orphans with a *
arVFolders = oSite.GetPermPathsList("-do")
'Uncomment this next line to show the folder list for debug only
'objLogFile.WriteLine(arVFolders)
'Break down the return string by its delimiter CRLF
arVFolders = Split(arVFolders, CRLF)
For Each fl in arVFolders
sPath = fl
If Not IsOrphan(spath) Then
WScript.Echo "Getting permissions for path: " & fl
On Error Resume Next
'WScript.Echo "Calling GetFolderPerms "
pFolder = oSite.GetFolderPermissions(sPath)
'Check to see if there was an error getting the permissions. If so, we don't want to write this to path to file.
If Not Err.Number <> 0 Then
'WScript.Echo "Calling StorePermissions "
Call StorePermissions(pFolder,sPath)
Err.Number = 0
Else
WScript.Echo "Error when checking folder: " & fl
WScript.Echo "Error Description: " & Err.Number & ": " & Err.Description
End If
End If
Next
SFTPServer.Close
Set SFTPServer = nothing
'Function used to determine if the returned path is an orphan in the VFS.
Function IsOrphan(chkpath)
IsOrphan = False
If Right(chkpath,1) = "*" then
IsOrphan = True
End If
End Function
'User-defined IIf function to perform ternary operation i.e. expression? true_value : false_value
Function IIf(bCondition, sTrueValue, sFalseValue)
if bCondition Then
If IsObject(sTrueValue) Then
Set IIf = sTrueValue
Else
IIf = sTrueValue
End If
Else
If IsObject(sFalseValue) Then
Set IIf = sFalseValue
Else
IIf = sFalseValue
End If
End If
End Function
Function StripVirtualPortion(ByVal sPath)
Dim iPos , sVirtualFolderPath,bIsVirtual
iPos = InStr(1, sPath, " - Virtual", 1 )
If ( iPos > 0 ) Then
WScript.Echo "-->Stripping VIRTUAL portion of folder name"
sVirtualFolderPath = sPath
sPath = Left( sPath, iPos -1 ) & "/"
End If
StripVirtualPortion = sPath
End Function
function StorePermissions(arPerms, strFullFolderPath)
Dim iCount, oPermission
sPath = StripVirtualPortion(strFullFolderPath)
If sPath = "" Or Right(sPath, 1) <> "/" Then
sPath = sPath & "/"
End If
'WScript.Echo "Begin StorePerimssions: Exporting data for folder " & strFullFolderPath
'WScript.Echo "Looping through permissions..."
For iCount = LBound(arPerms) To UBound(arPerms)
Set oPermission = arPerms (iCount)
'WScript.Echo "DEBUG: Checking path... " & sPath
'WScript.Echo "DEBUG: Value of oPermission.InheritedFrom = " & oPermission.InheritedFrom
'If the current folder is the root folder Or
'If the folder path length matches that of the "inherited from" path
'(means that personal permissions are set on the folder for this group and inherit status is not set)
If (sPath = "/" Or (Len(sPath) = Len(oPermission.InheritedFrom))) then
'WScript.Echo "DEBUG: First If has been matched "
'Append permissions group name
g_sOutPut = g_sOutPut & strFullFolderPath & ","
g_sOutPut = g_sOutPut & oPermission.Client & ","
'Append folder permissions
g_sOutPut = g_sOutPut & IIf(oPermission.FileUpload, "U", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.FileDownload, "D", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.FileAppend, "A", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.FileDelete, "D", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.FileRename, "R", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirShowinList, "S", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirCreate, "C", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirDelete, "D", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirList, "L", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirShowHidden, "H", "-")
g_sOutPut = g_sOutPut & IIf(oPermission.DirShowReadOnly,"O", "-")
g_sOutPut = g_sOutPut & ","
'Append "Inherited from" foldername
g_sOutPut = g_sOutPut & IIf(oPermission.Folder = "", "/", oPermission.Folder)
WScript.Echo g_sOutPut
g_strVFSBuffer = g_strVFSBuffer & g_sOutPut
objLogFile.WriteLine(g_strVFSBuffer)
g_strVFSBuffer = ""
g_sOutPut = ""
Else
'In case of virtual folder with inheritance set to true, then
'the above logic fails to make an entry into the back up permissions file
'so handle the virtual folder case here
'WScript.Echo "Else has been matched "
'If the folder is a virtual folder and if the folder entry is not found in the global buffer
If InStr(1,strFullFolderPath, "- Virtual", 1 ) > 0 And InStr (1, g_strVFSBuffer, strFullFolderPath, 1) = 0 Then
WScript.Echo "Found a virtual folder " + strFullFolderPath + " with inherited group permission. Adding a blank entry"
g_strVFSBuffer = g_strVFSBuffer & strFullFolderPath &",,,"
objLogFile.WriteLine(g_strVFSBuffer)
g_strVFSBuffer = ""
End If
End If
Next
end function
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function
'==============================================================================
' Syntax
' Show the command-line syntax
'==============================================================================
public function Syntax
wscript.echo vbCrLf & _
"Purpose: Export VFS tree permissions to a text file " & vbCrLf & _
"Usage: " & wscript.scriptname & " <arguments>" & vbCrLf & _
"Required Arguments:" & vbCrLf & _
" -s EFT Server" & vbCrLf & _
" -u Admin username for EFT Server" & vbCrLf & _
" -p Admin password" & vbCrLf & _
" -site Site name on the server we are manipulating. Defaults to first site" & vbCrLf & _
" -f Path of text file to retrieve data " & vbCrLf & _
vbCrLf & _
"Optional Arguments: " & vbCrLf & _
" -? This help" & vbCrLf & _
" -port Admin port on EFT server. Defaults to 1100" & vbCrLf & _
"Example: " & wscript.scriptname & " -s localhost -port 1100 -u admin -p secret -site SiteName -f c:\migrate.txt"
end function ' Syntax

View File

@ -0,0 +1,282 @@
'FILENAME: Export Virtual Folders.vbs
'DATE: 19 April 2011
'PROGRAMMER: A. ACUNA
'USE: Use this to export all the virtual folders in a site.
'**** run cmd "cscript (script location) > (location of output txt document)****
'Get File Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim strHost, strLogin, strPassword, strTextFile, strSite, strPort
Dim oSFTPServer, oSites, oSite
'Create GlobalSCAPE object
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Comment this next line if you want to use arguments passed to the script
If (ProcessArgs=-1) then wscript.quit
'Un-comment if you want to hardcode the variable info
REM strHost = "192.168.102.143"
REM strPort = "1100"
REM strLogin = "test"
REM strPassword = "test"
REM strTextFile = "output.txt"
REM strSite = "MySite"
WScript.Echo "Runtime Parameters:" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
'Get File Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create/overwrite log file
Set objLogFile = objFSO.CreateTextFile(strTextFile, True)
Call ConnectAndLogin()
Call ExportFolders()
oSFTPServer.Close
Set oSFTPServer = nothing
Public function ExportFolders
g_strVFSBuffer= ""
arVFolders = oSite.GetVirtualFolderList("/")
'objLogFile.WriteLine(arVFolders)
arVFolders = Split(arVFolders, CRLF)
For Each fl in arVFolders
if Not fl = "" then
WScript.Echo "INFO: Exporting info for folder: " & fl
physPath = oSite.GetPhysicalPath(fl)
objLogFile.WriteLine(fl & "," & physPath)
End if
Next
End function
'==============================================================================
'
' ProcessArgs
'
' Parse the command-line arguments. Results are set in global variables
' (strHost, strLogin, strPassword, strTextFile, strSite, strPort ).
'
'==============================================================================
public function ProcessArgs
Dim iCount
Dim oArgs
on error resume next
' Default our arguments. Some are required.
strHost = ""
strLogin = ""
strPassword = ""
strPort = "1100"
strSite = ""
strTextFile=""
' Get the command-line arguments
'
Set oArgs = WScript.Arguments
if oArgs.Count > 0 then
' We have command-line arguments. Loop through them.
iCount = 0
ProcessArgs = 0
do while iCount < oArgs.Count
select case oArgs.Item(iCount)
'
' Server name argument
'
case "-s"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strHost = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' What port to connect to for EFT server. Default to 1100
'
case "-port"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPort = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin login name argument
'
case "-u"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strLogin = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin password argument
'
case "-p"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPassword = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Which site to look into. Defaults into 1.
'
case "-site"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strSite = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' CSVFile name argument
'
case "-f"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strTextFile = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Help option
'
case "-?"
Syntax
ProcessArgs = -1
exit function
'
' Invalid argument
'
case else
' Display the syntax and return an error
wscript.echo "### ERROR: UNKNOWN ARGUMENT " & oArgs.Item(iCount) & vbCrLf
Syntax
ProcessArgs = -1
Exit function
end select
loop
Else
'
' There were no command-line arguments, display the syntax
' and return an error.
'
Syntax
ProcessArgs = -1
End if
Set oArgs = Nothing
If ( strHost = "" OR strLogin = "" or strSite = "" or strPassword = "" or strTextFile = "" ) Then
WScript.Echo "### ERROR : MISSING PARAMETERS" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
Syntax
ProcessArgs = -1
End If
End function ' ProcessArgs
'==============================================================================
' Syntax
' Show the command-line syntax
'==============================================================================
public function Syntax
wscript.echo "Purpose: Export Virtual Folders to a text file " & vbCrLf & _
"Usage: " & wscript.scriptname & " <arguments>" & vbCrLf & _
"Required Arguments:" & vbCrLf & _
" -s EFT Server" & vbCrLf & _
" -u Admin username for EFT Server" & vbCrLf & _
" -p Admin password" & vbCrLf & _
" -site Site name on the server we are manipulating. Defaults to first site" & vbCrLf & _
" -f Path of text file to retrieve data " & vbCrLf & _
vbCrLf & _
"Optional Arguments: " & vbCrLf & _
" -? This help" & vbCrLf & _
" -port Admin port on EFT server. Defaults to 1100" & vbCrLf & _
"Example: " & wscript.scriptname & " -s localhost -port 1100 -u admin -p secret -site SiteName -f c:\migrate.txt"
end function ' Syntax
'==============================================================================
' This method connectst to the specified EFT server and attempts to
' log in using the supplied information.
'==============================================================================
Sub ConnectAndLogIn()
Dim WshShell
' Let's check to be sure we can connect to the specified EFT Server:
WScript.Echo "<CONNECTING TO SERVER>"
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
' NOTE we assume default ADMIN port of 1100 -- please chang this if you have
' manually configured your EFT to be different.
On Error Resume Next
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Echo Chr(9) & "Attempting to restart service..."
err.Clear
Set WshShell = WScript.CreateObject("WScript.Shell")
call WshShell.Run("net start ""eft server""", 1, true)
Set WshShell = nothing
WScript.Echo Chr(9) & "Waiting for 5 seconds for the service to initiate..."
WScript.Sleep 5000
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quit 253
Else
WScript.Echo Chr(9) & "Connected to " & strHost
end if
End If
On Error GoTo 0 ' resume error trapping
set oSites=oSFTPServer.Sites
Dim iCount
For iCount=0 to oSites.count - 1
Set oSite = oSites.Item(iCount)
if LCase(Trim(oSite.Name)) = LCase(Trim(strSite)) then
exit for
End if
Next
WScript.Echo Chr(9) & "Connected to site '" & oSite.Name & "'" & vbCrLf
End Sub 'End ConnectAndLogin

View File

@ -0,0 +1,318 @@
'FILENAME: Import Virtual Folders.vbs
'DATE: 19 April 2011
'PROGRAMMER: A. ACUNA
'USE: Use this to export all the virtual folders in a site.
'**** run cmd "cscript (script location) > (location of output txt document)****
Dim g_arrFileLines()
Dim strHost, strLogin, strPassword, strTextFile, strSite, strPort
Dim oSFTPServer, oSites, oSite
'Create GlobalSCAPE object
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Comment this next line if you want to use arguments passed to the script
If (ProcessArgs=-1) then wscript.quit
'Un-comment if you want to hardcode the variable info
REM strHost = "192.168.102.143"
REM strPort = "1100"
REM strLogin = "test"
REM strPassword = "test"
REM strTextFile = "output.txt"
REM strSite = "MySite"
WScript.Echo "Runtime Parameters:" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
'Get File Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call ConnectAndLogin()
Call ReadVFSData()
Call ImportVFSData()
oSFTPServer.Close
Set oSFTPServer = nothing
Sub ImportVFSData()
Dim i,j,iPos,arLine
'WScript.Echo "DEBUG: ImportVFSData i = " & i
'WScript.Echo "DEBUG: notes on i = " & UBound(g_arrFileLines)
For i = Lbound(g_arrFileLines) to UBound(g_arrFileLines)
'WScript.Echo "DEBUG: ImportVFSData i = " & i
'WScript.Echo "DEBUG: g_arrFileLines i = " & g_arrFileLines(i)
arLine = Split(g_arrFileLines(i),",")
strVirtualP = arLine(0)
strPhysicalP = arLine(1)
WScript.Echo "Creating Virtual Folder: " & strVirtualP
WScript.Echo "Using Path: " & strPhysicalP
On Error Resume Next
Err.Clear
Call oSite.CreateVirtualFolder(strVirtualP, strPhysicalP)
If Err.Number<>0 then
If InStr(1,Err.Description,"MX Error: 27",1) > 0 Then
oSite.RemoveFolder(strVirtualP)
Call oSite.CreateVirtualFolder(strVirtualP, strPhysicalP)
Else
WScript.Echo "-*-ERROR: " & Err.Description
WScript.Echo "-*-ERROR: Failed to create Virtual folder: " & strVirtualP
WScript.Echo "Check virtual and physical folder." & Err.Description
End if
End if
Next
'.Echo "DEBUG: ImportVFSData Final i = " & i
End Sub
'==============================================================================
'
' ReadVFSData
'
' Read the data from the text file and create an
'
'==============================================================================
Sub ReadVFSData()
Dim i: i = 0
'WScript.Echo "DEBUG: readVFSData i =" & i
Dim oFSO, oFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.OpenTextFile( strTextFile, 1 )
Do Until oFile.AtEndOfStream
Redim Preserve g_arrFileLines(i)
'WScript.Echo "DEBUG: readVFSData i =" & i
g_arrFileLines(i) = oFile.ReadLine
'WScript.Echo "DEBUG: g_arrFileLines i =" & g_arrFileLines(i)
i = i + 1
Loop
'WScript.Echo "DEBUG: readVFSData i =" & i
oFile.Close
End Sub
'==============================================================================
'
' ProcessArgs
'
' Parse the command-line arguments. Results are set in global variables
' (strHost, strLogin, strPassword, strTextFile, strSite, strPort ).
'
'==============================================================================
public function ProcessArgs
Dim iCount
Dim oArgs
on error resume next
' Default our arguments. Some are required.
strHost = ""
strLogin = ""
strPassword = ""
strPort = "1100"
strSite = ""
strTextFile=""
' Get the command-line arguments
'
Set oArgs = WScript.Arguments
if oArgs.Count > 0 then
' We have command-line arguments. Loop through them.
iCount = 0
ProcessArgs = 0
do while iCount < oArgs.Count
select case oArgs.Item(iCount)
'
' Server name argument
'
case "-s"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strHost = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' What port to connect to for EFT server. Default to 1100
'
case "-port"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPort = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin login name argument
'
case "-u"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strLogin = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin password argument
'
case "-p"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPassword = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Which site to look into. Defaults into 1.
'
case "-site"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strSite = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' CSVFile name argument
'
case "-f"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strTextFile = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Help option
'
case "-?"
Syntax
ProcessArgs = -1
exit function
'
' Invalid argument
'
case else
' Display the syntax and return an error
wscript.echo "### ERROR: UNKNOWN ARGUMENT " & oArgs.Item(iCount) & vbCrLf
Syntax
ProcessArgs = -1
Exit function
end select
loop
Else
'
' There were no command-line arguments, display the syntax
' and return an error.
'
Syntax
ProcessArgs = -1
End if
Set oArgs = Nothing
If ( strHost = "" OR strLogin = "" or strSite = "" or strPassword = "" or strTextFile = "" ) Then
WScript.Echo "### ERROR : MISSING PARAMETERS" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
Syntax
ProcessArgs = -1
End If
End function ' ProcessArgs
'==============================================================================
' Syntax
' Show the command-line syntax
'==============================================================================
public function Syntax
wscript.echo "Purpose: Import Virtual Folders from a text file." & vbCrLf & _
"Usage: " & wscript.scriptname & " <arguments>" & vbCrLf & _
"Required Arguments:" & vbCrLf & _
" -s EFT Server" & vbCrLf & _
" -u Admin username for EFT Server" & vbCrLf & _
" -p Admin password" & vbCrLf & _
" -site Site name on the server we are manipulating. Defaults to first site" & vbCrLf & _
" -f Path of text file to retrieve data " & vbCrLf & _
vbCrLf & _
"Optional Arguments: " & vbCrLf & _
" -? This help" & vbCrLf & _
" -port Admin port on EFT server. Defaults to 1100" & vbCrLf & _
"Example: " & wscript.scriptname & " -s localhost -port 1100 -u admin -p secret -site SiteName -f c:\migrate.txt"
end function ' Syntax
'==============================================================================
' This method connectst to the specified EFT server and attempts to
' log in using the supplied information.
'==============================================================================
Sub ConnectAndLogIn()
Dim WshShell
' Let's check to be sure we can connect to the specified EFT Server:
WScript.Echo "<CONNECTING TO SERVER>"
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
' NOTE we assume default ADMIN port of 1100 -- please chang this if you have
' manually configured your EFT to be different.
On Error Resume Next
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Echo Chr(9) & "Attempting to restart service..."
err.Clear
Set WshShell = WScript.CreateObject("WScript.Shell")
call WshShell.Run("net start ""eft server""", 1, true)
Set WshShell = nothing
WScript.Echo Chr(9) & "Waiting for 5 seconds for the service to initiate..."
WScript.Sleep 5000
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quit 253
Else
WScript.Echo Chr(9) & "Connected to " & strHost
end if
End If
On Error GoTo 0 ' resume error trapping
set oSites=oSFTPServer.Sites
Dim iCount
For iCount=0 to oSites.count - 1
Set oSite = oSites.Item(iCount)
if LCase(Trim(oSite.Name)) = LCase(Trim(strSite)) then
exit for
End if
Next
WScript.Echo Chr(9) & "Connected to site '" & oSite.Name & "'" & vbCrLf
End Sub 'End ConnectAndLogin

543
vbs/4ImportPermissions.vbs Normal file
View File

@ -0,0 +1,543 @@
'
' FILE: EFTImport.vbs
' CREATED: 10 JAN 2008 GTH/ PPK
' MODIFIED: 7 JUL 2011 ALA
' PURPOSE: To import EFT VFS permissions from text file
Option Explicit
Dim oArgs
Dim strHost, strLogin, strPassword, strTextFile, strSite, strPort
Dim oSFTPServer, oSites, oSite, oPerm
Dim aSiteGroups, aSiteUsers, strGroupList, strUserList, strUsersAndGroups
Dim g_arrFileLines()
Class CPermission
Private m_sPermissionGroup
Private m_sPermissionString
Private m_sInheritedFrom
'File permissions
Private m_sFileUpload
Private m_sFileDownload
Private m_sFileAppend
Private m_sFileDelete
Private m_sFileRename
Private m_sDirList
'Folder permissions
Private m_sDirShowInList
Private m_sDirCreate
Private m_sDirDelete
'Contents
Private m_sDirShowReadOnly
Private m_sDirShowHidden
Public Property Get PermissionGroup()
PermissionGroup = m_sPermissionGroup
End Property
Public Property Let PermissionGroup(value)
m_sPermissionGroup = value
End Property
Public Property Get PermissionString()
PermissionString = m_sPermissionString
End Property
Public Property Let PermissionString(value)
m_sPermissionString = value
End Property
Public Property Get InheritedFrom()
InheritedFrom = m_sInheritedFrom
End Property
Public Property Let InheritedFrom(value)
m_sInheritedFrom = value
End Property
'File permissions
Public Property Get FileUpload()
FileUpload = m_sFileUpload
End Property
Public Property Let FileUpload(value)
m_sFileUpload = value
End Property
Public Property Get FileDownload()
FileDownload = m_sFileDownload
End Property
Public Property Let FileDownload(value)
m_sFileDownload=value
End Property
Public Property Get FileAppend()
FileAppend = m_sFileAppend
End Property
Public Property Let FileAppend(value)
m_sFileAppend=value
End Property
Public Property Get FileRename()
FileRename = m_sFileRename
End Property
Public Property Let FileRename(value)
m_sFileRename=value
End Property
Public Property Get DirList()
DirList = m_sDirList
End Property
Public Property Let DirList(value)
m_sDirList=value
End Property
Public Property Get FileDelete()
FileDelete = m_sFileDelete
End Property
Public Property Let FileDelete(value)
m_sFileDelete=value
End Property
'Folder permissions
Public Property Get DirShowinList()
DirShowinList = m_sDirShowinList
End Property
Public Property Let DirShowinList(value)
m_sDirShowinList=value
End Property
Public Property Get DirCreate()
DirCreate = m_sDirCreate
End Property
Public Property Let DirCreate(value)
m_sDirCreate=value
End Property
Public Property Get DirDelete()
DirDelete = m_sDirDelete
End Property
Public Property Let DirDelete(value)
m_sDirDelete=value
End Property
'Content permissions
Public Property Get DirShowHidden()
DirShowHidden = m_sDirShowHidden
End Property
Public Property Let DirShowHidden(value)
m_sDirShowHidden=value
End Property
Public Property Get DirShowReadonly()
DirShowReadonly = m_sDirShowReadonly
End Property
Public Property Let DirShowReadonly(value)
m_sDirShowReadonly=value
End Property
End Class
'==============================================================================
'
' Main
'
'==============================================================================
'Comment this next line if you want to use arguments passed to the script
If (ProcessArgs=-1) then wscript.quit
'Un-comment if you want to hardcode the variable info
REM strHost = "localhost"
REM strLogin = "test"
REM strPassword= "test"
REM strTextFile = "output.txt"
REM strSite= "MySite"
REM strPort="1100"
WScript.Echo "Runtime Parameters:" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
Call ConnectAndLogin()
Call ReadVFSData()
Call RetrieveUsersAndGroups()
Call ImportVFSData()
'==============================================================================
' This method connectst to the specified EFT server and attempts to
' log in using the supplied information.
'==============================================================================
Sub ConnectAndLogIn()
Dim WshShell
' Let's check to be sure we can connect to the specified EFT Server:
WScript.Echo "<CONNECTING TO SERVER>"
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
Set oSFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
' NOTE we assume default ADMIN port of 1100 -- please chang this if you have
' manually configured your EFT to be different.
On Error Resume Next
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Echo Chr(9) & "Attempting to restart service..."
err.Clear
Set WshShell = WScript.CreateObject("WScript.Shell")
call WshShell.Run("net start ""globalscape eft server""", 1, true)
Set WshShell = nothing
WScript.Echo Chr(9) & "Waiting for 5 seconds for the service to initiate..."
WScript.Sleep 5000
WScript.Echo Chr(9) & "Connecting to " & strLogin & "@" & strHost & ":1100 [Site " & strSite & "]"
oSFTPServer.Connect strHost, CLng(strPort), strLogin, strPassword
If Err.Number <> 0 Then
WScript.Echo Chr(9) & "Error connecting to '" & strHost & ":" & 1100 & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quit 253
Else
WScript.Echo Chr(9) & "Connected to " & strHost
end if
End If
On Error GoTo 0 ' resume error trapping
set oSites=oSFTPServer.Sites
Dim iCount
For iCount=0 to oSites.count - 1
Set oSite = oSites.Item(iCount)
if LCase(Trim(oSite.Name)) = LCase(Trim(strSite)) then
exit for
End if
Next
WScript.Echo Chr(9) & "Connected to site '" & oSite.Name & "'" & vbCrLf
End Sub
'==============================================================================
'
' ProcessArgs
'
' Parse the command-line arguments. Results are set in global variables
' (strHost, strLogin, strPassword, strTextFile, strSite, strPort ).
'
'==============================================================================
public function ProcessArgs
Dim iCount
Dim oArgs
on error resume next
' Default our arguments. Some are required.
strHost = ""
strLogin = ""
strPassword = ""
strPort = "1100"
strSite = ""
strTextFile=""
' Get the command-line arguments
'
Set oArgs = WScript.Arguments
if oArgs.Count > 0 then
' We have command-line arguments. Loop through them.
iCount = 0
ProcessArgs = 0
do while iCount < oArgs.Count
select case oArgs.Item(iCount)
'
' Server name argument
'
case "-s"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strHost = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' What port to connect to for EFT server. Default to 1100
'
case "-port"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPort = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin login name argument
'
case "-u"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strLogin = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' admin password argument
'
case "-p"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strPassword = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Which site to look into. Defaults into 1.
'
case "-site"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strSite = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' CSVFile name argument
'
case "-f"
if( iCount + 1 >= oArgs.Count ) then
Syntax
ProcessArgs = -1
exit do
end if
strTextFile = oArgs.Item(iCount+1)
iCount = iCount + 2
'
' Help option
'
case "-?"
Syntax
ProcessArgs = -1
exit function
'
' Invalid argument
'
case else
' Display the syntax and return an error
wscript.echo "### ERROR: UNKNOWN ARGUMENT " & oArgs.Item(iCount) & vbCrLf
Syntax
ProcessArgs = -1
Exit function
end select
loop
Else
'
' There were no command-line arguments, display the syntax
' and return an error.
'
Syntax
ProcessArgs = -1
End if
Set oArgs = Nothing
If ( strHost = "" OR strLogin = "" or strSite = "" or strPassword = "" or strTextFile = "" ) Then
WScript.Echo "### ERROR : MISSING PARAMETERS" & vbCrLf & "-------------------" & vbCrLf & _
"strHost = " & strHost & vbCrLf & _
"strPort = " & strPort & vbCrLf & _
"Login = " & strLogin & vbCrLf & _
"Password= " & strPassword & vbCrLf & _
"strSite = " & strSite & vbCrLf & _
"strTextFile = " & strTextFile & vbCrLf
Syntax
ProcessArgs = -1
End If
End function ' ProcessArgs
'Parse the permission string, e.g. UDADRSCDLHO etc., and create an object of CPermission class.
'This is to make the easier handling of permissions.
Public Function ParsePermissionString(sPermissionGroup, sPermissionString, sInheritedFrom)
Set oPerm = New CPermission
oPerm.PermissionGroup = sPermissionGroup
oPerm.InheritedFrom = sInheritedFrom
oPerm.PermissionString = UCase(Trim(sPermissionString))
sPermissionString = UCase(Trim(sPermissionString))
'File Permissions
oPerm.FileUpload = IIf( Mid(sPermissionString,1,1) = "U", True, False) 'File Upload
oPerm.FileDownload = IIf( Mid(sPermissionString,2,1) = "D", True, False) 'File Download
oPerm.FileAppend = IIf( Mid(sPermissionString,3,1) = "A", True, False) 'File Append
oPerm.FileDelete = IIf( Mid(sPermissionString,4,1) = "D", True, False) 'File Delete
oPerm.FileRename = IIf( Mid(sPermissionString,5,1) = "R", True, False) 'File Rename
oPerm.DirShowinList = IIf( Mid(sPermissionString,6,1) = "S", True, False) 'Dir Show in list
oPerm.DirCreate = IIf( Mid(sPermissionString,7,1) = "C", True, False) 'Dir Create
oPerm.DirDelete = IIf( Mid(sPermissionString,8,1) = "D", True, False) 'Dir Delete
oPerm.DirList = IIf( Mid(sPermissionString,9,1) = "L", True, False) 'File List
oPerm.DirShowHidden = IIf( Mid(sPermissionString,10,1)= "H", True, False) 'content Show hidden
oPerm.DirShowReadOnly = IIf( Mid(sPermissionString,11,1)= "O", True, False) 'Cotent Show Readonly
'Return the CPermission object
Set ParsePermissionString=oPerm
End Function
'Updates the folder permission using SFTPCOMInterface's "SetPermissions" method
Function UpdateFolderPermissions(oPerm, sFolderName)
On Error resume next
Dim oFolderPerm
'Getting permissions for the folder and also verifying that it can get the Group object
Set oFolderPerm = oSite.GetBlankPermission(sFolderName, oPerm.PermissionGroup)
if oFolderPerm then
oFolderPerm.FileUpload = oPerm.FileUpload
oFolderPerm.FileDownload = oPerm.FileDownload
oFolderPerm.FileDelete = oPerm.FileDelete
oFolderPerm.FileRename = oPerm.FileRename
oFolderPerm.FileAppend = oPerm.FileAppend
oFolderPerm.DirCreate = oPerm.DirCreate
oFolderPerm.DirDelete = oPerm.DirDelete
oFolderPerm.DirList = oPerm.DirList
oFolderPerm.DirShowInList = oPerm.DirShowInList
oFolderPerm.DirShowHidden = oPerm.DirShowHidden
oFolderPerm.DirShowReadOnly = oPerm.DirShowReadOnly
Call oSite.SetPermission(oFolderPerm, false)
oSFTPServer.ApplyChanges
UpdateFolderPermissions = true
else
Wscript.Echo "ERROR: Permissions import failed for folder: " & sFolderName & "."
Wscript.Echo "ERROR: Verify that folder and group '" & oPerm.PermissionGroup & "' exists in new site."
end if
Set oPerm = Nothing
End Function
'Obtain list of permission groups and create single string for validating later (ala: 7/7/2011)
Sub RetrieveUsersAndGroups()
Dim SiteGrp
Dim SiteUser
aSiteGroups = oSite.GetPermissionGroups
aSiteUsers = oSite.GetUsers()
strGroupList = ""
strUserList = ""
For Each SiteGrp in aSiteGroups
strGroupList = strGroupList & SiteGrp & vbCrLf
Next
For Each SiteUser in aSiteUsers
strUserList = strUserList & SiteUser & vbCrLf
Next
strUsersAndGroups = strGroupList & strUserList
'WScript.Echo "DEBUG: strUsersAndGroups = " & strUsersAndGroups
End Sub
Sub ImportVFSData()
Dim i,j,iPos,arLine,iPosg
Dim strFolder,strGroupName,strPermissions,strInheritFromFolder, strVirtulPath, strRealPath
WScript.Echo "INFO: Importing VFS data started ...."& VBcrlf
For i = Lbound(g_arrFileLines) to UBound(g_arrFileLines)-1
arLine = Split(g_arrFileLines(i),",")
strFolder = arLine(0)
'WScript.Echo "DEBUG: strFolder = " & strFolder
strGroupName = arLine(1)
'WScript.Echo "DEBUG: strGroupName = " & strGroupName
strPermissions = arLine(2)
'WScript.Echo "DEBUG: strPermissions = " & strPermissions
strInheritFromFolder = arLine(3)
'WScript.Echo "DEBUG: strInheritFromFolder = " & strInheritFromFolder
'Verify that the group is valid (ala: 7/7/2011)
iPosg = InStr(1, strUsersAndGroups, strGroupName, 1)
'WScript.Echo "DEBUG: iPosg = " & iPosg
If ( iPosg > 0) Then
iPosg = 0
'fixed echo string. folder and group are now enumerated.
WScript.Echo "INFO: Importing VFS data for folder '" & strFolder & "' for Group '" & strGroupName & "'"
iPos = InStr(1, strFolder, " - Virtual", 1 )
If ( iPos > 0 ) Then
WScript.Echo "INFO: -->Stripping VIRTUAL portion of folder name" & strFolder
strVirtulPath = Left( strFolder, iPos -1 ) & "/"
iPos = InStr(1, strFolder, "(", 1 )
if( iPos > 0 ) Then
strRealPath = Mid(strFolder,iPos+1, len(strFolder)- (iPos + 2))
'Now we have virtual name and real path ..Try to create virtual folder on site
'If it fails, just move on to the next step which is setting permissions. We're assuming it's failing because the virtual folder already exists.
On Error Resume Next
call oSite.CreateVirtualFolder(strVirtulPath, strRealPath)
end if
strFolder = strVirtulPath 'assign correct folder name to update permissions
End If
if(strGroupName <> "") Then ' if no permission, means we are working with virtual folder which has inherited permissions, so we only need to create the folder.
Call ParsePermissionString(strGroupName,strPermissions,strInheritFromFolder)
Call UpdateFolderPermissions(oPerm,strFolder)
End if
End if
WScript.Sleep(30)
Next
WScript.Echo "INFO: VFS Data import complete."& VBcrlf
End Sub
Sub ReadVFSData()
Dim i: i = 0
Dim oFSO, oFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.OpenTextFile(strTextFile, 1 )
Do Until oFile.AtEndOfStream
Redim Preserve g_arrFileLines(i)
g_arrFileLines(i) = oFile.ReadLine
i = i + 1
Loop
oFile.Close
End Sub
'Checks whether the folder has subfolder or not.
'If the folder has "" appended to it then it contains the sub folder
function hasSubFolders(ByVal sFolderName)
if sFolderName <> "" then
if Right(sFolderName, 1) = """" then
hasSubFolders = true
end if
end if
End function
'User-defined IIf function to perform ternary operation i.e. expression? true_value : false_value
Function IIf(bCondition, sTrueValue, sFalseValue)
if bCondition Then
If IsObject(sTrueValue) Then
Set IIf = sTrueValue
Else
IIf = sTrueValue
End If
Else
If IsObject(sFalseValue) Then
Set IIf = sFalseValue
Else
IIf = sFalseValue
End If
End If
End Function
'==============================================================================
' Syntax
' Show the command-line syntax
'==============================================================================
public function Syntax
wscript.echo "Purpose: Import VFS tree permissions from a text file " & vbCrLf & _
"Usage: " & wscript.scriptname & " <arguments>" & vbCrLf & _
"Required Arguments:" & vbCrLf & _
" -s EFT Server" & vbCrLf & _
" -u Admin username for EFT Server" & vbCrLf & _
" -p Admin password" & vbCrLf & _
" -site Site name on the server we are manipulating. Defaults to first site" & vbCrLf & _
" -f Path of text file to retrieve data " & vbCrLf & _
vbCrLf & _
"Optional Arguments: " & vbCrLf & _
" -? This help" & vbCrLf & _
" -port Admin port on EFT server. Defaults to 1100" & vbCrLf & _
"Example: " & wscript.scriptname & " -s localhost -port 1100 -u admin -p secret -site SiteName -f c:\migrate.txt"
end function ' Syntax

BIN
vbs/64.vbs Normal file

Binary file not shown.

BIN
vbs/72.vbs Normal file

Binary file not shown.

68
vbs/AddIPAccessRules.vbs Normal file
View File

@ -0,0 +1,68 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
siteName = "GS2"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
'To create an entry use the line below
Dim isAllowEntry : isAllowEntry = True
For index = 1 To 4
For index2 = 1 To 255
selectedSite.AddIPAccessRule "192.168." & index & "." & index2, isAllowEntry, 0
Next
Next
'Remove IPAccessRule at position
'For index = 1 To 9408
'selectedSite.RemoveIPAccessRule(1)
'Wscript.echo "Removing IP Access Rule: " & index
'Next
'Old functions:
'allowedIPs = SFTPServer.GetAllowedMasks
'For each ip in allowedIPs
' WScript.Echo "Allowed: " + ip
'Next
'deniedIPs = SFTPServer.GetDeniedMasks
'For each ip in deniedIPs
' WScript.Echo "Denied: " + ip
'Next
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,40 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
strEmailList = SFTPServer.SMTPAddressBook
For j = 0 to 1000
If strEmailList <> "" Then
strEmailList = strEmailList + "; "
End If
strEmailList = strEmailList + Cstr(j) +"<" + Cstr(j) + "@SomeServer.com>"
Next
SFTPServer.SMTPAddressBook = strEmailList
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

53
vbs/Create20Users.vbs Normal file
View File

@ -0,0 +1,53 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
siteName = "gs"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
SFTPServer.RefreshSettings
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
For j = 0 To 19
Wscript.echo j
selectedSite.CreateUserEx Cstr(j),Cstr(j),0,Cstr(j),Cstr(j),True,False,"Default settings"
Next
SFTPServer.AutoSave = TRUE
SFTPServer.ApplyChanges
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

87
vbs/CreateNewAdmin.vbs Normal file
View File

@ -0,0 +1,87 @@
'
' FILE: CreateNewAdmin.vbs
' AUTHOR: Brian Arriaga
' CREATED: 2 June 2016
' MODIFIED: 2 June 2016
' ORIGINALLY CREATED FOR: EFT Server 6.5-7.3
' PURPOSE: This script can create a new admin user or group within EFT Server by using the CreateAdmin method.
' This script was created as a workaround to add Universal Groups and Domain Local Groups as admins into EFT Server.
' In EFT Server 7.2.x and prior, these groups are outside of visible scope for the admin portion of AD viewer.
' To use this script, modify the connection details and the AdminAccountType, isGroup, NewAdminPassword,
'
' NOTE: The creation and modification of COM API scripts is not within the standard scope of Support.
' All COM API scripts are supplied as a courtesy "AS IS" with no implied or explicit guarantee of function.
' GlobalSCAPE is not responsible for any damage to system or data as a result of using supplied COM API scripts.
' Further information and usage instruction on COM API methods can be found online within the help file: http://help.globalscape.com/help/
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Modify the below connection details to reflect your own environment.
txtServer = "localhost"
txtPort = "1110"
txtAdminUserName = "a"
txtAdminPassword = "a"
'Modify the below 4 entries to configure the admin account/settings you desire.
'AdminAccountType:
' EFTAccount = 0,
' LocalComputerAccount = 1,
' ADAccount = 2,
AdminAccountType = 2
'group:
' True = Admin being added is a group
' False = Admin being added is not a group
isGroup = True
'NewAdminPassword
' Enter the desired Name for the new adminUser
' If AD group is being used (AdminAccountType=2) make sure to specify the domain in Domain\Group format.
NewAdmin = ""
'NewAdminPassword
' Enter the desired password for the new adminUser
' If group is being used, can be set to anything
NewAdminPassword= "P@ssWord!"
Call ConnectToServer()
Call CreateNewAdmin()
SFTPServer.Close
Set SFTPServer = nothing
'==========================================
'This sub connects to the server
'=========================================
Sub ConnectToServer()
SFTPServer.Connect txtServer, txtPort, txtAdminUserName, txtAdminPassword
If Err.Number = 0 Then
WScript.Echo "Connected to EFT Server: " & txtServer
End If
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & txtServer & ":" & txtPort & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
End If
End Sub
'==========================================
'This sub create a new Admin User or Group into EFT Server using the "CreateAdmin" method in format CreateAdmin(Admin Name, Admin Pass, Admin Type, Admin is Group)
'=========================================
Sub CreateNewAdmin()
Set adminUser = SFTPServer.CreateAdmin(NewAdmin, NewAdminPassword, AdminAccountType, isGroup)
WScript.Echo "Admin login " + adminUser.Login + " created."
End Sub

34
vbs/CreateSSHKey.vbs Normal file
View File

@ -0,0 +1,34 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "Administrator"
txtPassword = "Tester!1"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
SFTPServer.CreateSSHKey 1024, "passphrase", "C:\Private", "C:\Public.pub", False, 0, ""
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

23
vbs/CreateUsers.vbs Normal file
View File

@ -0,0 +1,23 @@
ServerAddress = "192.168.102.28"
ServerUsername = "eftadmin"
ServerPassword = "a"
ExcelFile = "R:\jhulme\COM Scripts\usersGlobalscape.xlsx"
Set SFTPServer = CreateObject("SFTPCOMInterface.CIServer")
SFTPServer.Connect ServerAddress,1100,ServerUsername,ServerPassword
Set sites=SFTPServer.Sites
Set site = sites.Item(0)
SFTPServer.RefreshSettings
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(ExcelFile)
objExcel.Visible = True
i = 1
Do Until objExcel.Cells(i, 1).Value = ""
site.CreateUserEx objExcel.Cells(i, 1).Value, objExcel.Cells(i, 2).Value, 0, objExcel.Cells(i, 4).Value, objExcel.Cells(i, 5).Value,True,True,objExcel.Cells(i, 6).Value
i = i + 1
Loop
objExcel.Quit
SFTPServer.AutoSave=True
SFTPServer.ApplyChanges

124
vbs/Create_user_ex.vbs Normal file
View File

@ -0,0 +1,124 @@
'
' FILE: CreateUserEX2.vbs
' AUTHOR: Brian Arriaga
' CREATED: 17 MAR 2015
' MODIFIED: 17 MAR 2015
' ORIGINALLY CREATED FOR: EFT Server 6.5-7.0.3
' PURPOSE: This script creates a specified user using the CreateUserEX2 method.
'
' NOTE: The creation and modification of COM API scripts is not within the standard scope of Support.
' All COM API scripts are supplied as a courtesy "AS IS" with no implied or explicit guarantee of function.
' GlobalSCAPE is not responsible for any damage to system or data as a result of using supplied COM API scripts.
' Further information and usage instruction on COM API methods can be found online within the help file: http://help.globalscape.com/help/
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
'Modify the below connection details to reflect your own environment.
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtAdminPassword = "a"
txtSiteName = "GS"
' This is the username that will be created
txtLogin = "TestUser15"
' This specifies the password of the user.
txtPassword = "Password_321!"
' This specifies the full name of the user (account details).
txtFullName = "Test User"
' This specifies the email of the user (account details).
txtEmail = "abaciu@iiroc.ca"
' This specifies whether or not a folder will be created for the user. If "true", a user home folder will be created with the Login name, example: /Usr/UserA.
'If false, it will not create a folder for the user and it will instead inherit the folder from the template
txtCreateHomeFolder = "false"
'This specifies whether or not the user will have full permissions to the home folder.
txtFullPermissionsForHomeFolder = "true"
Dim theSite
Call ConnectToServerEx()
Call FindSite()
Call RunCreateUserEX2()
SFTPServer.Close
Set SFTPServer = nothing
'==========================================
'This sub connects to the server with AD authentication
'=========================================
Sub ConnectToServerEx()
SFTPServer.ConnectEx txtServer, txtPort, 1, "", ""
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub connects to the server
'=========================================
Sub ConnectToServer()
SFTPServer.Connect txtServer, txtPort, txtAdminUserName, txtAdminPassword
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub finds the specified site
'=========================================
Sub FindSite()
set Sites=SFTPServer.Sites
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
exit for
End if
Next
WScript.Echo "Connected to site: " & theSite.Name
End Sub
'==========================================
'This sub Initializes the CINewUserData property, sets the variables and then creates a user account using the CreateUserEX2() method.
'=========================================
Sub RunCreateUserEX2()
Set NewUserData = WScript.CreateObject("SFTPCOMInterface.CINewUserData")
NewUserData.Login = txtLogin
NewUserData.FullName = txtfullName
NewUserData.Email = txtemail
NewUserData.Password = txtpassword
NewUserData.CreateHomeFolder = txtCreateHomeFolder
NewUserData.FullPermissionsForHomeFolder= txtFullPermissionsForHomeFolder
WScript.Echo ""
WScript.Echo "Creating user with Login: " & NewUserData.Login
WScript.Echo "Creating user with Password: " & NewUserData.Password
WScript.Echo "Creating user with Full Name (account detail): " & NewUserData.FullName
WScript.Echo "Creating user with Email (account detail): " & NewUserData.Email
' The below lines will output whether or not a home folder will be created for the user
if (NewUserData.CreateHomeFolder = false) Then
WScript.Echo "The user will inherit the Default Settings Template Home folder"
else
WScript.Echo "A folder /" & NewUserData.Login & " will be created in the Settings Template Root Folder"
end if
' The below line will output whether or not the user will receive full permission to their home folder.
if (NewUserData.FullPermissionsForHomeFolder = false) Then
WScript.Echo "The user will not receive full permission to their home folder"
else
WScript.Echo "The user will receive full permission to their home folder"
end if
theSite.CreateUserEX2(NewUserData)
End Sub

View File

@ -0,0 +1,124 @@
'
' FILE: CreateUserEX2.vbs
' AUTHOR: Brian Arriaga
' CREATED: 17 MAR 2015
' MODIFIED: 17 MAR 2015
' ORIGINALLY CREATED FOR: EFT Server 6.5-7.0.3
' PURPOSE: This script creates a specified user using the CreateUserEX2 method.
'
' NOTE: The creation and modification of COM API scripts is not within the standard scope of Support.
' All COM API scripts are supplied as a courtesy "AS IS" with no implied or explicit guarantee of function.
' GlobalSCAPE is not responsible for any damage to system or data as a result of using supplied COM API scripts.
' Further information and usage instruction on COM API methods can be found online within the help file: http://help.globalscape.com/help/
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
'Modify the below connection details to reflect your own environment.
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtAdminPassword = "a"
txtSiteName = "GS"
' This is the username that will be created
txtLogin = "TestUser15"
' This specifies the password of the user.
txtPassword = "Password_321!"
' This specifies the full name of the user (account details).
txtFullName = "Test User"
' This specifies the email of the user (account details).
txtEmail = "abaciu@iiroc.ca"
' This specifies whether or not a folder will be created for the user. If "true", a user home folder will be created with the Login name, example: /Usr/UserA.
'If false, it will not create a folder for the user and it will instead inherit the folder from the template
txtCreateHomeFolder = "false"
'This specifies whether or not the user will have full permissions to the home folder.
txtFullPermissionsForHomeFolder = "true"
Dim theSite
Call ConnectToServerEx()
Call FindSite()
Call RunCreateUserEX2()
SFTPServer.Close
Set SFTPServer = nothing
'==========================================
'This sub connects to the server with AD authentication
'=========================================
Sub ConnectToServerEx()
SFTPServer.ConnectEx txtServer, txtPort, 1, "", ""
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub connects to the server
'=========================================
Sub ConnectToServer()
SFTPServer.Connect txtServer, txtPort, txtAdminUserName, txtAdminPassword
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub finds the specified site
'=========================================
Sub FindSite()
set Sites=SFTPServer.Sites
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
exit for
End if
Next
WScript.Echo "Connected to site: " & theSite.Name
End Sub
'==========================================
'This sub Initializes the CINewUserData property, sets the variables and then creates a user account using the CreateUserEX2() method.
'=========================================
Sub RunCreateUserEX2()
Set NewUserData = WScript.CreateObject("SFTPCOMInterface.CINewUserData")
NewUserData.Login = txtLogin
NewUserData.FullName = txtfullName
NewUserData.Email = txtemail
NewUserData.Password = txtpassword
NewUserData.CreateHomeFolder = txtCreateHomeFolder
NewUserData.FullPermissionsForHomeFolder= txtFullPermissionsForHomeFolder
WScript.Echo ""
WScript.Echo "Creating user with Login: " & NewUserData.Login
WScript.Echo "Creating user with Password: " & NewUserData.Password
WScript.Echo "Creating user with Full Name (account detail): " & NewUserData.FullName
WScript.Echo "Creating user with Email (account detail): " & NewUserData.Email
' The below lines will output whether or not a home folder will be created for the user
if (NewUserData.CreateHomeFolder = false) Then
WScript.Echo "The user will inherit the Default Settings Template Home folder"
else
WScript.Echo "A folder /" & NewUserData.Login & " will be created in the Settings Template Root Folder"
end if
' The below line will output whether or not the user will receive full permission to their home folder.
if (NewUserData.FullPermissionsForHomeFolder = false) Then
WScript.Echo "The user will not receive full permission to their home folder"
else
WScript.Echo "The user will receive full permission to their home folder"
end if
theSite.CreateUserEX2(NewUserData)
End Sub

View File

@ -0,0 +1,119 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
siteName = "GS"
set siteToRemove = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set siteToRemove = site
Exit For
End If
Next
'EventType:
'OnTimer = 4097,
'OnLogRotate = 4098,
'OnServiceStopped = 4099,
'OnServiceStarted = 4100,
'MonitorFolder = 4101,
'OnMonitorFolderFailed = 4102,
'OnSiteStarted = 8193,
'OnSiteStopped = 8194,
'OnIPAddedToBanList = 8195,
'OnClientConnected = 12289,
'OnClientConnectionFailed = 12290,
'OnClientDisconnected = 12291,
'OnClientDisabled = 16385,
'OnClientQuotaExceeded = 16386,
'OnClientLoggedOut = 16387,
'OnClientLoggedIn = 16388,
'OnClientLoginFailed = 16389,
'OnClientPasswordChanged = 16390,
'OnClientCreated = 16391,
'OnClientLocked = 16392,
'OnFileDeleted = 20481,
'OnFileUpload = 20482,
'BeforeFileDownload = 20483,
'OnFileDownload = 20484,
'OnFileRenamed = 20485,
'OnFolderCreated = 20486,
'OnFolderDeleted = 20487,
'OnUploadFailed = 20489,
'OnDownloadFailed = 20490,
'OnChangeFolder = 20491,
'OnFileMoved = 20492,
'OnVerifiedUploadSuccess = 20493,
'OnVerifiedUploadFailure = 20494,
'OnVerifiedDownloadSuccess = 20495,
'OnVerifiedDownloadFailure = 20496,
'AS2InboundTransactionSucceeded = 24577,
'AS2InboundTransactionFailed = 24578,
'AS2OutboundTransactionSucceeded = 24579,
'AS2OutboundTransactionFailed = 24580,
If Not siteToRemove Is Nothing Then
Set rules = site.EventRules(4101)
Set objParams = WScript.CreateObject("SFTPCOMInterface.CIFolderMonitorEventRuleParams")
objParams.Name = "TestFolderMon13"
objParams.Enabled = true
objParams.Description = "This is a test event rule"
objParams.Path = "C:\wd\monitor"
'Recurrence:
' Recurrence_Continually = 0,
' Recurrence_Daily = 1,
' Recurrence_Weekly = 2,
' Recurrence_Monthly = 3,
' Recurrence_Yearly = 4,
' Recurrence_Once = 5,
' Recurrence_Calendar = 6,
Set eventRule = rules.Add(rules.Count(), objParams)
'Add "If File name matches "*.txt" or "*.exe"" condition:
dim cond
set cond = eventRule.AddIfStatement(0, 5005, 16, Array("*.txt", "*.exe"), -1)
Set mail = WScript.CreateObject("SFTPCOMInterface.CIMailActionParams")
mail.Body = "Test email"
mail.Subject = "Test"
mail.TOAddresses = "youremail@youdomain.com"
cond.ifSection.Add 0, mail
End If
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

50
vbs/Generate_Complex.vbs Normal file
View File

@ -0,0 +1,50 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
userName = "test"
siteName = "GS"
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
password = selectedSite.CreateComplexPassword()
wscript.echo(password)
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

60
vbs/IPAccessExport.vbs Normal file
View File

@ -0,0 +1,60 @@
Const ForAppending = 8, AutobanIPRule = 0, ManualIPRule = 1
Const txtMyOutputFileName = "TESTOut.csv" 'Output file CSV File can be opened with MS Excel
Dim SFTPServer, CRLF, txtServer, txtPort, txtAdminUserName, txtPassword, SiteName, myFSO, WriteStuff, selectedSite, i, Key, Key2
Set SFTPServer = CreateObject("SFTPCOMInterface.CIServer")
CRLF = Chr(13) & Chr(10) 'Use the built-in vbCrLf constant instead!
'***************************************************
'***Modify the following to match your EFT Server***
'***************************************************
txtServer = "192.168.102.28" 'input server ip or localhost
txtPort = "1100" 'input port used
txtAdminUserName = "insight" 'input server admin credentials - username
txtPassword = "a" 'input server admin credentials - password
SiteName = LCase("MySite") 'input sitename in the ""
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then WScript.Quit 0
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile(txtMyOutputFileName, ForAppending, True)
Set selectedSite = Nothing
'Move through sites to find the one you're looking for
For i = 0 To SFTPServer.Sites.Count - 1
With SFTPServer.Sites.Item(i)
If LCase(.Name) = SiteName Then
count = 1
For Each Key In .GetIPAccessRules
Select Case Key.Type
Case ManualIPRule
WriteStuff.WriteLine Join(Array(Key.Address, Key.Allow, count)
End Select
Next
Else 'LCase(SFTPServer.Sites(i).Name) <> SiteName
'WriteStuff.WriteLine "Manual Added," & key1.Address & "," & key1.added & ",,,,"
End If 'Why write "Manual Added, ..." to the .csv file here?
End With 'The Else branch is executed when the current site isn't
Next 'the one you're looking for, so why have an Else branch?
WriteStuff.Close
Set WriteStuff = Nothing
Set myFSO = Nothing
SFTPServer.Close
Set SFTPServer = Nothing
MsgBox "Banned IPs can be found in the file """ & txtMyOutputFileName & """", vbInformation
Function Connect(serverOrIpAddress, port, username, password)
On Error Resume Next
SFTPServer.Connect serverOrIpAddress, port, username, password
Connect = (Err.Number = 0)
If Not Connect Then
MsgBox "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & _
Err.Description & " [" & CStr(Err.Number) & "]", vbInformation, "Error"
End If
End Function

7850
vbs/IPAccess_Import.vbs Normal file

File diff suppressed because it is too large Load Diff

73
vbs/IPBanExport.vbs Normal file
View File

@ -0,0 +1,73 @@
Const ForAppending = 8, AutobanIPRule = 0, ManualIPRule = 1
Const txtMyOutputFileName = "C:\path\TESTOut.csv" 'Output file CSV File can be opened with MS Excel
Dim SFTPServer, CRLF, txtServer, txtPort, txtAdminUserName, txtPassword, SiteName, myFSO, WriteStuff, selectedSite, i, Key, Key2
Set SFTPServer = CreateObject("SFTPCOMInterface.CIServer")
CRLF = Chr(13) & Chr(10) 'Use the built-in vbCrLf constant instead!
'***************************************************
'***Modify the following to match your EFT Server***
'***************************************************
txtServer = "localhost" 'input server ip or localhost
txtPort = "1100" 'input port used
txtAdminUserName = "test" 'input server admin credentials - username
txtPassword = "test" 'input server admin credentials - password
SiteName = LCase("MySite") 'input sitename in the ""
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then WScript.Quit 0
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile(txtMyOutputFileName, ForAppending, True)
'Header row for CSV file
'Type: AutoBan or Manually Added to List
'Address: IP that is in the list
'Banned: Dated added to banlist
'Permanent: True for permanent addition, False for expiring address
'Expires: Date that non-permanent address in Auto Banlist will drop from list.
'Reason: Reason IP was added to AutoBan list.
WriteStuff.WriteLine "Type,Address,Banned,Permanent,Expires,Reason"
Set selectedSite = Nothing
'Move through sites to find the one you're looking for
For i = 0 To SFTPServer.Sites.Count - 1
With SFTPServer.Sites.Item(i)
If LCase(.Name) = SiteName Then
For Each Key In .GetIPAccessRules
Select Case Key.Type
Case AutobanIPRule
For Each Key2 In Key.BannedIPs
WriteStuff.WriteLine Join(Array("AutoBanned", Key2.Address, CStr(Key2.Banned), CStr(Key2.Permanently), CStr(Key2.Expires), Key2.Reason), ",")
Next
Case ManualIPRule
If Not Key.Allow Then WriteStuff.WriteLine Join(Array("Manually Added", Key.Address, Key.Added, "", "", ""), ",")
End Select
Next
Else 'LCase(SFTPServer.Sites(i).Name) <> SiteName
'WriteStuff.WriteLine "Manual Added," & key1.Address & "," & key1.added & ",,,,"
End If 'Why write "Manual Added, ..." to the .csv file here?
End With 'The Else branch is executed when the current site isn't
Next 'the one you're looking for, so why have an Else branch?
WriteStuff.Close
Set WriteStuff = Nothing
Set myFSO = Nothing
SFTPServer.Close
Set SFTPServer = Nothing
MsgBox "Banned IPs can be found in the file """ & txtMyOutputFileName & """", vbInformation
Function Connect(serverOrIpAddress, port, username, password)
On Error Resume Next
SFTPServer.Connect serverOrIpAddress, port, username, password
Connect = (Err.Number = 0)
If Not Connect Then
MsgBox "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & _
Err.Description & " [" & CStr(Err.Number) & "]", vbInformation, "Error"
End If
End Function

46
vbs/IsFolderVirtual.vbs Normal file
View File

@ -0,0 +1,46 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
set Sites=SFTPServer.Sites
set oSite = Sites.Item(0)
WSCript.Echo oSite.Name
dim folders
'folders = oSite.GetFolderList("/")
if True = oSite.IsFolderVirtual("/wd") then
WSCript.Echo "/wd is virtual."
end if
if True = oSite.IsFolderVirtual("/Usr") then
WSCript.Echo "/Usr is virtual."
end if
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,56 @@
'
' FILE: ListUserInfo.vbs
' CREATED: 6-8-2012 (dransom@globalscape.com)
' UPDATED: 6-5-2014 (jhulme@globalscape.com)
' VERSION: 1.1 *added Settings template membership | Test against 6.5.x
' PURPOSE: Modified script that creates CSV file for users
' Tested against EFT Server Versions 6.3.x / 6.4.x / 6.5.x
' Provides the following information:
' Username, Description, Email,Account Creation, Disk Quota, Used space, Home Directory, Settings template membership, Last Connection Time
' **This script is provided AS IS to our customers as a courtesy no support is provided in modifying or debugging this script.
'
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Modify the following variables to match your environment
txtServer = "localhost"
txtPort = "1100"
txtUserName = "eftadmin"
txtPassword = "a"
txtSiteName = "GS"
txtMyOutputFileName = "EFT-Users.csv"
SFTPServer.Connect txtServer, txtPort, txtUserName, txtPassword
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & txtServer & ":" & txtPort & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quite(255)
Else
WScript.Echo "Connected to " & txtServer
End If
set Sites=SFTPServer.Sites
'open output file
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile(txtMyOutputFileName, 8, True)
'write data to a file
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
WriteStuff.WriteLine("Users for " & theSite.Name & ":")
WriteStuff.WriteLine("Username,Description,Email,Account Creation, Disk Quota, Used space, Home Directory, Settings Template, Last Connection Time, Enabled")
arUsers = theSite.GetUsers()
For j = LBound(arUsers) to UBound(arUsers)
set userSettings = theSite.GetUserSettings(arUsers(j))
WriteStuff.WriteLine(arUsers(j) & ", " & userSettings.GetDescription & ", " & userSettings.Email & ", " & userSettings.AccountCreationTime & ", " & userSettings.GetMaxSpace & ", " & userSettings.GetUsedSpace & ", " & userSettings.GetHomeDirString & ", " & theSite.GetUserSettingsLevel(arUsers(j)) & ", " & userSettings.LastConnectionTime & ", " & userSettings.GetEnableAccount)
Next
end if
Next
'Close all variables
WriteStuff.Close
SFTPServer.Close
Set theSite = nothing
Set SFTPServer = nothing
SET WriteStuff = NOTHING
SET myFSO = NOTHING

View File

@ -0,0 +1,34 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
strEmailList = ""
SFTPServer.SMTPAddressBook = strEmailList
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,71 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
welcomeMsg = "The script you are running is used to return the date and time which a user's password is going to expire."
msgTitle = "Globalscape EFT Server"
serverMessage = "Enter EFT Server IP..."
portMessage = "Enter EFT Server Port..."
adminMessage = "Enter EFT Admin username..."
passMessage = "Enter EFT Admin password..."
siteMessage = "Enter the site name where the user is located..."
userMessage = "Enter the Username for which you would like to retrieve the expiration date and time..."
'Display welcome message
Call MsgBox (welcomeMsg, , msgTitle)
'Input Prompts
txtServer = InputBox (serverMessage, msgTitle)
txtPort = InputBox (portMessage, msgTitle)
txtAdminUserName = InputBox(adminMessage, msgTitle)
txtPassword = InputBox(passMessage, msgTitle)
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
userName = InputBox (userMessage, msgTitle)
siteName = InputBox (siteMessage, msgTitle)
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
set userSettings = selectedSite.GetUserSettings(userName)
'getting pass expiration date
If userSettings.IsPasswordAgeLimited(pDate) Then
dtAccPssExp = Cstr(pDate)
Wscript.Echo "User " +userName + "'s Password Expires on " + dtAccPssExp
Else
Wscript.Echo "User " + userName + "'s Password does not expire"
End If
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,69 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
welcomeMsg = "The script you are running is used to return the date and time for which all user's passwords expire for a particular site."
msgTitle = "Globalscape EFT Server"
serverMessage = "Enter EFT Server IP..."
portMessage = "Enter EFT Server Port..."
adminMessage = "Enter EFT Admin username..."
passMessage = "Enter EFT Admin password..."
siteMessage = "Enter the site name..."
txtMyOutputFileName = "EFT-PasswordExpirations.csv"
'Display welcome message
Call MsgBox (welcomeMsg, , msgTitle)
'Input Prompts
txtServer = InputBox (serverMessage, msgTitle)
txtPort = InputBox (portMessage, msgTitle)
txtAdminUserName = InputBox(adminMessage, msgTitle)
txtPassword = InputBox(passMessage, msgTitle)
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
siteName = InputBox (siteMessage, msgTitle)
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile(txtMyOutputFileName, 8, True)
set theSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(siteName)) then
WriteStuff.WriteLine("Users password expiration for " & theSite.Name & ":")
WriteStuff.WriteLine("Username,Password Expiration date")
arUsers = theSite.GetUsers()
For j = LBound(arUsers) to UBound(arUsers)
set userSettings = theSite.GetUserSettings(arUsers(j))
If userSettings.IsPasswordAgeLimited(pDate) Then
dtAccPssExp = Cstr(pDate)
Else
dtAccPssExp = "Does not expire"
End If
WriteStuff.WriteLine(arUsers(j) & ", " & dtAccPssExp)
Next
end if
Next
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

52
vbs/Return Reg State.vbs Normal file
View File

@ -0,0 +1,52 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
welcomeMsg = "The script you are running is used to retrieve registration status"
msgTitle = "Globalscape EFT Server"
serverMessage = "Enter EFT Server IP..."
portMessage = "Enter EFT Server Port..."
adminMessage = "Enter EFT Admin username..."
passMessage = "Enter EFT Admin password..."
moduleMessage = "Enter Integer for Module You want to Check"
txtMyOutputFileName = "RegistrationStatus.csv"
'Display welcome message
Call MsgBox (welcomeMsg, , msgTitle)
'Input Prompts
txtServer = InputBox (serverMessage, msgTitle)
txtPort = InputBox (portMessage, msgTitle)
txtAdminUserName = InputBox(adminMessage, msgTitle)
txtPassword = InputBox(passMessage, msgTitle)
txtModuleInt = InputBox(moduleMessage, msgTitle)
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile(txtMyOutputFileName, 8, True)
dim RegState
RegState = SFTPServer.ModuleRegistrationState(txtModuleInt)
MsgBox RegState
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

31
vbs/SSHSSL-passphrase.vbs Normal file
View File

@ -0,0 +1,31 @@
'
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
txtServer = "localhost"
txtPort = "1100"
txtUserName = "test"
txtPassword = "test"
' On Error Resume Next
SFTPServer.Connect txtServer, txtPort, txtUserName, txtPassword
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & txtServer & ":" & txtPort & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quite(255)
Else
WScript.Echo "Connected to " & txtServer
End If
set Sites=SFTPServer.Sites
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
SFTPhrase = theSite.SFTPKeyPassphrase
SSLPassphrase = theSite.GetPassPhrase()
Wscript.Echo theSite.Name & "SFTP Passphrase " & SFTPhrase
Wscript.Echo theSite.Name & "SSL Passphrase " & SSLPassphrase
Next
Set theSite = nothing
Set SFTPServer = nothing
SET WriteStuff = NOTHING
SET myFSO = NOTHING

101
vbs/SetGroupPermissions.vbs Normal file
View File

@ -0,0 +1,101 @@
'
' FILE: ExportUsersAndGroupMembership.vbs
' AUTHOR: Brian Arriaga
' CREATED: 9 JAN 2015
' MODIFIED: 9 JAN 2015
' ORIGINALLY CREATED FOR: EFT Server 6.5-7.0.3
' PURPOSE: This script loops through all Users of a specified site and performs the GetPermissionGroupsOfUser() COM API method along with
' objLogFile.WriteLine() to record the data in "username,group" format to an output file
' The output text file can be used with ImportUsersAndGroupMembership.vbs to import the user+group memberships.
' Can be used to backup group memberships in scenarios were Group membership settings are being lost.
'
' NOTE: The creation and modification of COM API scripts is not within the standard scope of Support.
' All COM API scripts are supplied as a courtesy "AS IS" with no implied or explicit guarantee of function.
' GlobalSCAPE is not responsible for any damage to system or data as a result of using supplied COM API scripts.
' Further information and usage instruction on COM API methods can be found online within the help file: http://help.globalscape.com/help/
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
'Modify the below connection details to reflect your own environment.
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtAdminPassword = "a"
txtSiteName = "GS"
'Folder to apply group/user permissions to
txtVFSName = "/usr/grouptesting"
'Group to add to folder
txtGroup = "testGroup"
'The below values specify each permission and whether or not the client has it
boolDirCreate = True
boolDirDelete = False
boolDirList = True
boolDirShowHidden = False
boolDirShowInList = True
boolDirShowReadOnly = False
boolFileAppend = True
boolFileDelete = False
boolFileDownload = True
boolFileRename = False
boolFileUpload = True
Dim theSite
g_strBuffer =""
Call ConnectToServer()
Call FindSite()
Call ListUsersAndGroups()
'==========================================
'This sub connects to the server
'=========================================
Sub ConnectToServer()
SFTPServer.Connect txtServer, txtPort, txtAdminUserName, txtAdminPassword
End Sub
'==========================================
'This sub finds the specified site
'=========================================
Sub FindSite()
set Sites=SFTPServer.Sites
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
exit for
End if
Next
End Sub
'==========================================
'This Sub adds specified group/user to specified VFS folder
'=========================================
Sub ListUsersAndGroups()
set oPerm = theSite.GetBlankPermission(txtVFSName, txtGroup)
oPerm.DirCreate = boolDirCreate
oPerm.DirDelete = boolDirDelete
oPerm.DirList = boolDirList
oPerm.DirShowHidden = boolDirShowHidden
oPerm.DirShowInList = boolDirShowInList
oPerm.DirShowReadOnly = boolDirShowReadOnly
oPerm.FileAppend = boolFileAppend
oPerm.FileDelete = boolFileDelete
oPerm.FileDownload = boolFileDownload
oPerm.FileRename = boolFileRename
oPerm.FileUpload = boolFileUpload
theSite.SetPermission(oPerm)
End Sub
SFTPServer.Close
Set SFTPServer = nothing

View File

@ -0,0 +1,56 @@
'
' FILE: SetUserHomeFolders.vbs
' Modified: 6-04-2014 (dransom@globalscape.com)
' PURPOSE: Modified script that will set a user's home folder.
' Required parameters: SetUserHomeFolder.vbs <username> <VFS Home Folder>
' Example: SetUserHomeFolder.vbs dransom "/usr/dransom"
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Modify the following variables to match your environment
txtServer = "localhost"
txtPort = "1100"
txtUserName = "test"
txtPassword = "test"
txtSiteName = "MySite"
SFTPServer.Connect txtServer, txtPort, txtUserName, txtPassword
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & txtServer & ":" & txtPort & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quite(255)
Else
WScript.Echo "Connected to " & txtServer
End If
set Sites=SFTPServer.Sites
txtEFTUser = WScript.Arguments.Item(0)
txtHomeFolder = WScript.Arguments.Item(1)
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
set userSettings = theSite.GetUserSettings(txtEFTUser)
userSettings.setHomeDirIsRoot(1)
userSettings.SetHomeDir(1)
userSettings.SetHomeDirString(txtHomeFolder)
Set oFolderPerm = theSite.GetBlankPermission(txtHomeFolder, txtEFTUser)
oFolderPerm.FileUpload = TRUE
oFolderPerm.FileDownload = TRUE
oFolderPerm.FileDelete = TRUE
oFolderPerm.FileRename = TRUE
oFolderPerm.FileAppend = TRUE
oFolderPerm.DirCreate = TRUE
oFolderPerm.DirDelete = TRUE
oFolderPerm.DirList = TRUE
oFolderPerm.DirShowInList = TRUE
oFolderPerm.DirShowHidden = TRUE
oFolderPerm.DirShowReadOnly = TRUE
Call theSite.SetPermission(oFolderPerm, false)
end if
Next
'Close all variables
SFTPServer.Close
Set theSite = nothing
Set SFTPServer = nothing

View File

@ -0,0 +1,53 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1111"
txtAdminUserName = "eftadmin"
txtPassword = "a"
siteName = "GS"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
arUsers = selectedSite.GetUsers()
For j = LBound(arUsers) to UBound(arUsers)
set userSettings = selectedSite.GetUserSettings(arUsers(j))
userSettings.SetForcePasswordResetOnNextLogin(false)
next
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

160
vbs/VFSCheck.vbs Normal file
View File

@ -0,0 +1,160 @@
'This script is provided AS IS. Back up Server configuration before attempting to run.
'FILENAME: VFSCheck.vbs
'DATE: 31 JAN 2012
'USE: This will list all the folders of a site and display their corresponding physical paths.
'Notes: There is some logic for error checking, but I never got it to work correctly
' There is additional logic that will delete folders from VFS if they do not have a matching Physical path.
'**** run cmd "cscript (script location)****
'Modify the section "CONSTANTS/PARAMETERS
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
'Get File Object
Set objFSO = CreateObject("Scripting.FileSystemObject") 'Output file Object
Set objFSO2 = CreateObject("Scripting.FileSystemObject") 'Check foler existince object
Set objFSO3 = CreateObject("Scripting.FileSystemObject") 'Error Log
'Create/overwrite log file
Set objLogFile = objFSO.CreateTextFile("virtual_folders.txt", True)
'Set objErrorLogFile = objFSO3.CreateTextFile("virtual_folders_errors.log", True)
'On Error Resume Next 'Added Error Capture instructions for some steps beyond this point.
'CONSTANTS/PARAMETERS:
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "test"
txtPassword = "test"
txtSiteName = "MySite"
'***WARNING BACKUP CONFIG FILES BEFORE MODIFYING THE NEXT LINE!!
delFlag="False" 'Set to True to actually delete the VFS entry from EFT. ***WARNING BACKUP CONFIG FILES BEFORE DOING THIS!!
objLogFile.WriteLine("VFS Path, Physical Path, Folder Status")
'objErrorLogFile.WriteLine("Folder, Error, Hex, Source, Description")
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
set Sites=SFTPServer.Sites
SitesTotal = Sites.count
For iCount=0 to Sites.count - 1
Set Site = Sites.Item(iCount)
if LCase(Trim(Site.Name)) = LCase(Trim(txtSiteName)) then
exit for
End if
Next
'The following step was used for debugging.
'Msgbox Site.GetRootFolder()
'This step kicks off the whole process. I used "" as the root since the recursion logic adds the / to the path.
GetNextFolder "", Site
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function GetNextFolder (CurrFolder,objSite)
CurrFolder = CurrFolder & "/"
folderList = objSite.GetFolderList(CurrFolder)
if Err.Number <> 0 Then
objLogFile.WriteLine(CurrFolder & ", " & ", ERROR-FOLDER NOT FOUND IN VFS")
DisplayErrorInfo CurrFolder
else
arVFolders = Split(folderlist, CRLF)
recurseFlag=0
For Each fl in arVFolders
WScript.Echo "Exporting info for folder: " & CurrFolder & fl
'if the folder name has " at the end of it there are additional folders and we need to recurse to next level
if instr(fl,chr(34)) > 0 then
'strip " from the folder path
fl = Left(fl,len(fl)-1)
'set flag to recurse
recurseFlag=1
End if
'strip of the EFT Virtual informaiton
f2 = fl
fl = StripVirtualPortion(fl)
'WScript.Echo "Exporting info for folder: " & CurrFolder & fl
'Get the physical path
StrPhysical = objSite.GetPhysicalPath(CurrFolder & fl)
IF objFSO2.FolderExists(strPhysical) THEN
folderStat = "The folder exists"
ELSE
folderStat = "Sorry this folder does not exist"
'If Delete Flag is set remove VFS Entries where Physical folder does not exist
if delFlag = "True" then
objSite.RemoveFolder(CurrFolder & fl)
folderStat = folderStat & " and has been removed from VFS"
recurseFlag = 0
end if
END IF
'output infomaion to logfile
objLogFile.WriteLine(CurrFolder & fl & ", " & StrPhysical & ", " & folderStat)
'if the recurseFlag is set, call GetNextFolder again.
if recurseFlag > 0 then
GetNextFolder CurrFolder & fl,objSite
End if
Next
'if Err.Number <> 0 Then
' objLogFile.WriteLine(CurrFolder & fl & ", " & ", ERROR-FOLDER NOT FOUND IN VFS")
' DisplayErrorInfo (CurrFolder & fl)
' folderStat = "ERROR-FOLDER NOT FOUND IN VFS"
' else
' IF objFSO2.FolderExists(strPhysical) THEN
' folderStat = "The folder exists"
' ELSE
' folderStat = "Sorry this folder does not exist"
' 'If Delete Flag is set remove VFS Entries where Physical folder does not exist
' if delFlag = "True" then
' objSite.RemoveFolder(CurrFolder & fl)
' end if
' END IF
' 'output infomaion to logfile
' End IF 'error2
end if 'No Error
End Function
Function StripVirtualPortion(ByVal sPath)
Dim iPos , sVirtualFolderPath,bIsVirtual
iPos = InStr(1, sPath, " - Virtual", 1 )
If ( iPos > 0 ) Then
'WScript.Echo "-->Stripping VIRTUAL portion of folder name"
sVirtualFolderPath = sPath
sPath = Left( sPath, iPos -1 )
End If
StripVirtualPortion = sPath
End Function
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function
Sub DisplayErrorInfo (CurrFolder)
objErrorLogFile.WriteLine(CurrFolder & ", " & Err & ", " & Hex(Err) & ", " & Err.Source & ", " & Err.Description)
WScript.Echo "Folder : " & CurrFolder
WScript.Echo "Error: : " & Err
WScript.Echo "Error (hex) : &H" & Hex(Err)
WScript.Echo "Source : " & Err.Source
WScript.Echo "Description : " & Err.Description
Err.Clear
End Sub

17
vbs/a.vbs Normal file
View File

@ -0,0 +1,17 @@
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
' Define source file name.
sourceFile = "C:\Users\jbranan\Desktop\source\Report File.xml"
' Define target file name.
destinationFile = "C:\Users\jbranan\Desktop\destination\Report File.xml"
'opy source to target.
FSO.CopyFile sourceFile, destinationFile
'Function UnicodeFileCopy(src As String, dst As String) As String
' On Error Resume Next
' FileCopy src, dst
' UnicodeFileCopy = Err.Description
'End Function
'Sub Main
' Call UnicodeFileCopy"C:\Users\jbranan\Desktop\source\Report File.xml", "C:\Users\jbranan\Desktop'\destination\Report File.xml"
'End Sub

47
vbs/change_email.vbs Normal file
View File

@ -0,0 +1,47 @@
'
' FILE: ListUserInfo.vbs
' CREATED: 6-8-2012 (dransom@globalscape.com)
' UPDATED: 6-5-2014 (jhulme@globalscape.com)
' VERSION: 1.1 *added Settings template membership | Test against 6.5.x
' VERSION: 1.2 *added Added enabled/disabled
' PURPOSE: Modified script that creates CSV file for users
' Tested against EFT Server Versions 6.3.x / 6.4.x / 6.5.x
' Provides the following information:
' Username, Description, Email,Account Creation, Disk Quota, Used space, Home Directory, Settings template membership, Last Connection Time
' **This script is provided AS IS to our customers as a courtesy no support is provided in modifying or debugging this script.
'
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
'Modify the following variables to match your environment
txtServer = "localhost"
txtPort = "1100"
txtUserName = "eftadmin"
txtPassword = "a"
txtSiteName = "GS"
userName = "test"
SFTPServer.Connect txtServer, txtPort, txtUserName, txtPassword
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & txtServer & ":" & txtPort & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
WScript.Quite(255)
Else
WScript.Echo "Connected to " & txtServer
End If
set Sites=SFTPServer.Sites
'chnage email
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
set userSettings = theSite.GetUserSettings(userName)
userSettings.Email = "jhulme@globalscape.com"
end if
Next
'Close all variables
SFTPServer.Close
Set theSite = nothing
Set SFTPServer = nothing
SET WriteStuff = NOTHING
SET myFSO = NOTHING

54
vbs/changepassword.vbs Normal file
View File

@ -0,0 +1,54 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.39"
txtPort = "1111"
txtAdminUserName = "eftadmin"
txtPassword = "a"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
userName = "test"
siteName = "GS"
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
'selectedSite.ChangeUserPassword userName, "abcd", 0
selectedSite.ChangeUserPassword userName, "test1", 0
'$1$abcdefg$M72mUVrUAZrOg1C7Nl1qM.
set userSettings = selectedSite.GetUserSettings(userName)
'userSettings.MaxInactivePeriod = 30
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,54 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
'Input boxes **do not modify**
msgTitle = "Globalscape EFT Server"
siteMessage = "Enter the site name:"
groupMessage = "Enter the name of the new group"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
siteName = InputBox (siteMessage, msgTitle)
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
'physical or virtual?
txtGroup = InputBox (groupMessage, msgTitle)
selectedSite.CreatePermissionGroup(txtGroup)
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,75 @@
'
' FILE: CreateUserEX2.vbs
' AUTHOR: Brian Arriaga
' CREATED: 17 MAR 2015
' MODIFIED: 17 MAR 2015
' ORIGINALLY CREATED FOR: EFT Server 6.5-7.0.3
' PURPOSE: This script creates a specified user using the CreateUserEX2 method.
'
' NOTE: The creation and modification of COM API scripts is not within the standard scope of Support.
' All COM API scripts are supplied as a courtesy "AS IS" with no implied or explicit guarantee of function.
' GlobalSCAPE is not responsible for any damage to system or data as a result of using supplied COM API scripts.
' Further information and usage instruction on COM API methods can be found online within the help file: http://help.globalscape.com/help/
'
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
'Modify the below connection details to reflect your own environment.
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtAdminPassword = "a"
txtSiteName = "GS"
createdFolder = "/Usr/created"
Dim theSite
Call ConnectToServerEx()
Call FindSite()
Call CreatePhysical()
SFTPServer.Close
Set SFTPServer = nothing
'==========================================
'This sub connects to the server with AD authentication
'=========================================
Sub ConnectToServerEx()
SFTPServer.ConnectEx txtServer, txtPort, 1, "", ""
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub connects to the server
'=========================================
Sub ConnectToServer()
SFTPServer.Connect txtServer, txtPort, txtAdminUserName, txtAdminPassword
WScript.Echo "Connected to EFT Server: " & txtServer
End Sub
'==========================================
'This sub finds the specified site
'=========================================
Sub FindSite()
set Sites=SFTPServer.Sites
For i = 0 to SFTPServer.Sites.Count-1
set theSite=Sites.Item(i)
if LCase(Trim(theSite.Name)) = LCase(Trim(txtSiteName)) then
exit for
End if
Next
WScript.Echo "Connected to site: " & theSite.Name
End Sub
'==========================================
'This sub Initializes the CINewUserData property, sets the variables and then creates a user account using the CreateUserEX2() method.
'=========================================
Sub CreatePhysical()
theSite.CreatePHysicalFolder(createdFolder)
End Sub

64
vbs/createVFSFolder.vbs Normal file
View File

@ -0,0 +1,64 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "localhost"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
siteName = "GS"
'Input boxes **do not modify**
msgTitle = "Globalscape EFT Server"
isPhysMessage = "Is the folder physical or virtual? (Type p for physical and v for virtual"
physFolderMessage = "Enter the full path of the physical folder...."
aliasMessage = "Enter the full path of the alias..."
physRefMessage = "Enter the physical path reference for the virtual folder..."
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
'physical or virtual?
txtIsPhys = InputBox (isPhysMessage, msgTitle)
if txtIsPhys = "p" then
txtPhysPath = InputBox (physFolderMessage, msgTitle)
selectedSite.CreatePhysicalFolder(txtPhysPath)
end if
if txtIsPhys = "v" then
txtAliasPath = InputBox (aliasMessage, msgTitle)
txtPhysRef = InputBox (physRefMessage, msgTitle)
Call selectedSite.CreateVirtualFolder(txtAliasPath, txtPhysRef)
end if
WScript.Echo "Done"
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,63 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
welcomeMsg = "The script you are running is used to create a new settings tempalte for a specified site"
msgTitle = "Globalscape EFT Server"
serverMessage = "Enter EFT Server IP..."
portMessage = "Enter EFT Server Port..."
adminMessage = "Enter EFT Admin username..."
passMessage = "Enter EFT Admin password..."
siteMessage = "Enter the site name where the user is located..."
templateMessage = "Enter New Template Name"
'Display welcome message
Call MsgBox (welcomeMsg, , msgTitle)
'Input Prompts
txtServer = InputBox (serverMessage, msgTitle)
txtPort = InputBox (portMessage, msgTitle)
txtAdminUserName = InputBox(adminMessage, msgTitle)
txtPassword = InputBox(passMessage, msgTitle)
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
siteName = InputBox (siteMessage, msgTitle)
templateName = InputBox (templateMessage, msgTitle)
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
selectedSite.CreateSettingsLevel(templateName)
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

View File

@ -0,0 +1,51 @@
Set SFTPServer = WScript.CreateObject("SFTPCOMInterface.CIServer")
CRLF = (Chr(13)& Chr(10))
txtServer = "192.168.102.28"
txtPort = "1100"
txtAdminUserName = "eftadmin"
txtPassword = "a"
boolEncrypt = true
folderPath = "/somefolder"
If Not Connect(txtServer, txtPort, txtAdminUserName, txtPassword) Then
WScript.Quit(0)
End If
userName = "test"
siteName = "GS"
set selectedSite = Nothing
set sites = SFTPServer.Sites()
For i = 0 To sites.Count -1
set site = sites.Item(i)
If site.Name = siteName Then
set selectedSite = site
Exit For
End If
Next
If Not selectedSite Is Nothing Then
'Encrypt or unencrypt folder
selectedSite.EncryptFolder "/BAPI", boolEncrypt
End If
SFTPServer.Close
Set SFTPServer = nothing
Function Connect (serverOrIpAddress, port, username, password)
On Error Resume Next
Err.Clear
SFTPServer.Connect serverOrIpAddress, port, username, password
If Err.Number <> 0 Then
WScript.Echo "Error connecting to '" & serverOrIpAddress & ":" & port & "' -- " & err.Description & " [" & CStr(err.Number) & "]", vbInformation, "Error"
Connect = False
Exit Function
End If
Connect = True
End Function

19
vbs/excel.vbs Normal file
View File

@ -0,0 +1,19 @@
Dim objXL
Dim objWB
Dim objWS
Set objXL = CreateObject("Excel.Application")
Set objWB = objXL.Workbooks.Open("C:\wd\scripts\blahblah.xls")
Set objWS = objWB.Worksheets("sheet1")
objWS.Rows(1).EntireRow.Delete
objWB.Save
objWB.Close
objXL.Quit
Set objXL = Nothing
Set objWB = Nothing
Set objWS = Nothing

Some files were not shown because too many files have changed in this diff Show More