summaryrefslogtreecommitdiff
path: root/ansible/scripts/setup-websql.ps1
blob: 02e370b2b0e6cb761861003ab358a696e1f31cd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
param (
    [string]$DomainName  = "contoso.com",
    #[string]$SvcUsername = "svc_websql01",
    [string]$SvcUsername = "svc_mssql02",
    [string]$SvcPassword = "Svc1234!"
)

$scriptName = $MyInvocation.MyCommand.Name
$logFile = "C:\Logs\${scriptName}_log.txt"
$NetBiosName = $DomainName.Split(".")[0].ToUpper()
$wwwroot1 = "C:\inetpub\wwwroot"
$wwwroot2 = "C:\inetpub\wwwroot2"
$wwwroot3 = "C:\inetpub\wwwroot3"

Start-Transcript -Path $logFile -Append

try {
    New-Item -Path "C:\setup\media" -ItemType "Directory" -Force
    @"
;SQL Server Configuration File
[OPTIONS]
IACCEPTSQLSERVERLICENSETERMS="True"
ACTION="Install"
ENU="True"
QUIET="True"
QUIETSIMPLE="False"
UpdateEnabled="False"
ERRORREPORTING="False"
USEMICROSOFTUPDATE="False"
FEATURES=SQLENGINE,FULLTEXT
UpdateSource="MU"
HELP="False"
INDICATEPROGRESS="False"
X86="False"
INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
INSTANCENAME="SQLEXPRESS"
SQMREPORTING="False"
INSTANCEID="SQLEXPRESS"
RSINSTALLMODE="DefaultNativeMode"
INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
AGTSVCACCOUNT="NT AUTHORITY\NETWORK SERVICE"
AGTSVCSTARTUPTYPE="Automatic"
COMMFABRICPORT="0"
COMMFABRICNETWORKLEVEL="0"
COMMFABRICENCRYPTION="0"
MATRIXCMBRICKCOMMPORT="0"
SQLSVCSTARTUPTYPE="Automatic"
FILESTREAMLEVEL="0"
ENABLERANU="False"
SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
SQLSVCACCOUNT="NT AUTHORITY\NETWORK SERVICE"
SAPWD="$SvcPassword"
SQLSYSADMINACCOUNTS="BUILTIN\Administrators"
ADDCURRENTUSERASSQLADMIN="True"
TCPENABLED="1"
NPENABLED="0"
BROWSERSVCSTARTUPTYPE="Disabled"
RSSVCSTARTUPTYPE="manual"
FTSVCACCOUNT="NT Service\MSSQLFDLauncher"
"@ | Out-File "C:\setup\sql_conf.ini"

    Start-Process -FilePath "C:\setup\SQL2019-SSEI-Expr.exe" -ArgumentList "/configurationfile=C:\setup\sql_conf.ini /IACCEPTSQLSERVERLICENSETERMS /MEDIAPATH=C:\setup\media /QUIET /HIDEPROGRESSBAR" -Wait
    Set-ItemProperty -Path "HKLM:\Software\Microsoft\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQLServer\SuperSocketNetLib\Tcp\IPAll" -Name "TcpPort" -Value "1433" -Force
    Restart-Service -Name "MSSQL`$SQLEXPRESS"
    New-NetFirewallRule -DisplayName "SQLServer default instance" -Direction Inbound -LocalPort 1433 -Protocol TCP -Action Allow

    $env:Path += ";C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn"
    SqlCmd -E -Q "CREATE LOGIN [$NetBiosName\$SvcUsername] FROM WINDOWS"
    SqlCmd -E -Q "SP_ADDSRVROLEMEMBER '$NetBiosName\$SvcUsername', 'SYSADMIN'"

    SqlCmd -E -Q "ALTER LOGIN sa ENABLE"
    SqlCmd -E -Q "ALTER LOGIN sa WITH PASSWORD = '$SvcPassword', CHECK_POLICY=OFF"
    Write-Host "[inf] Added $NetBiosName\$SvcUsername as MSSQL login and sysadmin"
    Write-Host "[inf] Enabled SA login"
} catch {
    Write-Host "[err] SQL Server setup failed"
}

try {
    Install-WindowsFeature -Name Web-Server -IncludeManagementTools
    Install-WindowsFeature -Name Web-Asp-Net45
    Write-Host "[inf] Installed IIS and ASP.NET"
} catch {
    Write-Host "[err] Failed to install IIS and ASP.NET"
}

@"
using System;
using System.IO;
using System.Web.UI;

public partial class UploadPage : Page
{
    protected void UploadFile(object sender, EventArgs e)
    {
        if (fileUpload.PostedFile != null && fileUpload.PostedFile.ContentLength > 0)
        {
            try
            {
                string filename = Path.GetFileName(fileUpload.PostedFile.FileName);
                fileUpload.PostedFile.SaveAs(Server.MapPath(filename));
                lblMessage.Text = "File uploaded successfully!";
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
        else
        {
            lblMessage.Text = "Please select a file to upload.";
        }
    }
}
"@ | Out-File "$wwwroot1\upload.aspx.cs" -Force

@"
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="UploadPage" %>
<!DOCTYPE html>
<html>
<head><title>File Upload Page</title></head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="file" id="fileUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />
            <br />
            <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>
"@ | Out-File "$wwwroot1\upload.aspx" -Force

@"
<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.5"/>
        <httpRuntime targetFramework="4.5"/>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
"@ | Out-File "$wwwroot1\Web.config" -Force

try {
    New-WebSite -Name "MyASPXSite" -Port 80 -PhysicalPath $wwwroot1 -ApplicationPool "DefaultAppPool"
    Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name processModel -Value @{userName="$SvcUsername";password="$SvcPassword";identityType=3}
    New-NetFirewallRule -DisplayName "HTTP (80)" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
    Restart-WebAppPool -Name "DefaultAppPool"
    Write-Host "[inf] Site 1 created on port 80"
} catch {
    Write-Host "[err] Failed to create site 1"
}

try {
    $svcRule = New-Object System.Security.AccessControl.FileSystemAccessRule("$DomainName\$SvcUsername", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl = Get-Acl $wwwroot1
    $acl.SetAccessRule($svcRule)
    Set-Acl -Path $wwwroot1 -AclObject $acl
    Write-Host "[inf] ACL set for $wwwroot1"
} catch {
    Write-Host "[err] Failed to set ACL for $wwwroot1"
}

try {
    Copy-Item $wwwroot1 -Destination $wwwroot2 -Recurse -Force
    New-WebAppPool -Name "DefaultAppPool2"
    New-WebSite -Name "MyASPXSite2" -Port 8080 -PhysicalPath $wwwroot2 -ApplicationPool "DefaultAppPool2"
    Set-ItemProperty "IIS:\AppPools\DefaultAppPool2" -Name processModel -Value @{identityType=2}
    New-NetFirewallRule -DisplayName "HTTP (8080)" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow
    $acl = Get-Acl $wwwroot2
    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS_IUSRS", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl.SetAccessRule($rule)
    Set-Acl -Path $wwwroot2 -AclObject $acl
    Restart-WebAppPool -Name "DefaultAppPool2"
    Write-Host "[inf] Site 2 created on port 8080"
} catch {
    Write-Host "[err] Failed to create site 2"
}

try {
    Copy-Item $wwwroot1 -Destination $wwwroot3 -Recurse -Force
    New-WebAppPool -Name "SqlQueryAppPool"
    New-WebSite -Name "SqlQuerySite" -Port 9090 -PhysicalPath $wwwroot3 -ApplicationPool "SqlQueryAppPool"
    Set-ItemProperty "IIS:\AppPools\SqlQueryAppPool" -Name processModel -Value @{userName="$SvcUsername";password="$SvcPassword";identityType=3}
    New-NetFirewallRule -DisplayName "HTTP (9090)" -Direction Inbound -Protocol TCP -LocalPort 9090 -Action Allow

    @"
<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            string query = txtQuery.Value;

            string connStr = "Server=localhost\\SQLEXPRESS;Database=master;Integrated Security=true;";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(query, conn);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    litResults.Text = "<table border='1'><tr>";
                    foreach (DataColumn col in dt.Columns)
                    {
                        litResults.Text += string.Format("<th>{0}</th>", col.ColumnName);
                    }
                    litResults.Text += "</tr>";

                    foreach (DataRow row in dt.Rows)
                    {
                        litResults.Text += "<tr>";
                        foreach (var item in row.ItemArray)
                        {
                            litResults.Text += string.Format("<td>{0}</td>", item);
                        }
                        litResults.Text += "</tr>";
                    }
                    litResults.Text += "</table>";
                }
                catch (Exception ex)
                {
                    litResults.Text = "<span style='color:red;'>Error: " + ex.Message + "</span>";
                }
            }
        }
    }
</script>
<html>
<head><title>SQL Query Tester</title></head>
<body>
    <h2>Enter a SQL Query</h2>
    <form id="form1" runat="server">
        <textarea id="txtQuery" runat="server" rows="5" cols="80">SELECT GETDATE()</textarea><br /><br />
        <asp:Button ID="btnRun" runat="server" Text="Run Query" OnClick="Page_Load" /><br /><br />
        <asp:Literal ID="litResults" runat="server" />
    </form>
</body>
</html>
"@ | Out-File "$wwwroot3\sqlquery.aspx" -Force

    Restart-WebAppPool -Name "SqlQueryAppPool"
    Write-Host "[inf] Site 3 created on port 9090 with SQL query page"
} catch {
    Write-Host "[err] Failed to create SQL query site"
}

Stop-Transcript