Troubleshout SQL Server

Find the PID of the SQL server

$sqlpid=((netstat -ano | sls ":143[34] ") -replace ' $','' -replace '^. ','' | select -Unique); echo "PID of SQL is $sqlpid"

After the above you can also find other ports that the SQL listens to

echo "PID of SQL is $sqlpid, ports that it listens to:"; netstat -ano | sls ".* $sqlpid *$"

About the Instance name

How to find the Instance name

If you can source the script found below and run this command from a client that can connect to the SQL server (NOT FROM THE SERVER ITSELF)
Query-SQLServer -Computer COMPUTER_NAME_OR_IP

Or do it manualy:

Open up SQL Server Configuration Manager Click on SQL Server Services. The instance name of SQL Server is in parenthesis inline with SQL Server service. If it says MSSQLSERVER, then it's the default instance.

enter image description here

How to connect to the default or other instance

To connect to the default instance from SQL Management Studio, just type . (dot) OR (local) and click Connect.

To connect to a non default instance (AKA named instance) use .\[instance name] to connect to it (for example if the instance name is SQL2008, connect to .\SQL2008).

In both cases make sure SQL Server and SQL Server Browser services are running, otherwise you won't be able to connect.

How to configure SQL Express 2012 to accept remote connections

A) Configure SQL express server to listen on static port.
1. SQL Server Configuration Manager > SQL Server Network Configuration
i. right-click TCP/IP protocol > Enable.
ii. right-click TCP/IP protocol > Properties > IP Address tab > IPALL section. TCP Dynamic Ports, EMPTY the value (do not enter Zero 0 !!!). TCP Port enter 1433.
2. Restart SQL Server service and identify the process ID assigned to SQL service.

B) Enable the SQL Server Browser service.
1. SQL Server Configuration Manager > SQL Server Services > right-click SQL Server Browser service > Properties.
2. Service tab > Start Mode option > change it to Automatic.
3. In the same tab click the "Start" button

Important note: According to SQL server hardening best practices the SQL Server Browser service should be disabled. This service, which typically isn't required, responds to requests for SQL Server resources and redirects the caller to the correct port. Keeping the Browser service disabled will remove the redirector as an attack vector, helping to obscure the correct entry ways into your SQL Server components.

C) Configure the firewall

Three exceptions must be configured in Windows Firewall to allow access to SQL Server:
1. Allow incoming connections to TCP Port 1433 run this in powershell or cmd "netsh advfirewall firewall add rule name="SQL" protocol=TCP dir=in localport=1433 action=allow"
2. Allow incoming connections to UDP Port 1434 run this in powershell or cmd "netsh advfirewall firewall add rule name="SQL" protocol=UDP dir=in localport=1434 action=allow"
3. A program exception for sqlservr.exe. (Firewall > New Rule > Program > Browse for 'sqlservr.exe') (C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\Binn)

D) Enable remote connections
1. Open SQL Management Studio > right-click server name in > Properties > Connections > Allow remote connections to this server: Checked.

Troubleshouting SQL server connectivity issues

1) run the script below (it defines 2 functions you will use below)

2) run this to get basic information
Query-SQLServer -Computer 10.1.11.5341
ServerName;W10SRV;InstanceName;MSSQLSERVER;IsClustered;No;Version;15.0.2000.5;tcp;1433

Sometimes this returns nothing at all but if you find the Instance name clients can still connect (and the following test with Test-SQLServer works).

3) Run one of these to connect to the SQL server and run a default SQL command that will list the DBs
  Use Windows authentication Use Username/password authentication
Connect to
Default instance
Test-SQLServer -server SERVER_NAME
Test-SQLServer -server SERVER_NAME -user USER_NAME
Connect to
Specific instance
Test-SQLServer -server SERVER_NAME -instance INSTANCE_NAME
Test-SQLServer -server SERVER_NAME -user USER_NAME -instance INSTANCE_NAME
4) Optional: the Test-SQLServer function can also run any other SQL query you like by adding these two options
Test-SQLServer ...  -sql SQL_TO_RUN -database DATABASE_NAME

The functions :
function Query-SQLServer{
# From: # http://sqlserverio.com/2013/02/27/finding-sql-server-installs-using-powershell/
   [cmdletbinding(
        DefaultParameterSetName = '',
        ConfirmImpact = 'low'
    )]
    Param(
        [Parameter(
            Mandatory = $True,
            Position = 0,
            ParameterSetName = '',
            ValueFromPipeline = $True)]
        [string]$Computer
    )
    Begin {
        $ErrorActionPreference = 'SilentlyContinue'
        $Port = 1434
        $ConnectionTimeout = 1000
        $Responses  = @();
    }
    Process {

          $IPAddress = [System.Net.Dns]::GetHostEntry($Computer).AddressList[0].IPAddressToString
        $ToASCII = new-object system.text.asciiencoding
      $UDPEndpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
        $UDPPacket = 0x02,0x00,0x00

        $UDPClient = new-Object system.Net.Sockets.Udpclient
        $UDPClient.client.ReceiveTimeout = $ConnectionTimeout
        $UDPClient.Connect($IPAddress,$Port)
      $UDPClient.Client.Blocking = $True

      [void]$UDPClient.Send($UDPPacket, $UDPPacket.length)
      $BytesRecived = $UDPClient.Receive([ref]$UDPEndpoint)
      [string]$Response = $ToASCII.GetString($BytesRecived)

      If ($Response) {
         $Response = $Response.Substring(3,$Response.Length-3).Replace(';;','~')
         $Response.Split('~') | ForEach {
            $Responses += $_
         }
         $UDPClient.close()
      }
    }
    End {
        return ,$Responses
    }
} 
function Test-SQLServer {
    param(
        [Parameter(Mandatory = $True)] [string] $SERVER, 
      [string] $instance, 
      [string] $user,
      [string] $pass,
      [string] $database,
      [string] $sql
      )
    
   if ($server -match '[0-9][0-9.]*') {
      echo "You specified the IP of the server. If nothing works you may try with the server name"
   } else {
      echo "You specified the name of the server. If nothing works you may try with the server IP"
   }
   If (!($user)) {
       $cred="Integrated Security=true"
      echo "No user specified so I will try to connect with Windows Integrated Security"
      echo "  (if this fails consider retrying with -user SOME_USERNAME)"
   } else {
      echo "A user was specified so I will try to connect with username/password"
      echo "  (if this fails consider retrying without -user and I will use Windows Integrated Security)"
      if (!($pass)) {
         $secret = Read-Host -assecurestring "Please enter password for $user"
         $pass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret))
      } else {
         echo "Using supplied password"
      }
      $cred='User ID={0};Password={1};' -f $user,$pass 
   }
   if ($instance) {
      $server_instance='{0}\{1}' -f $Server,$INSTANCE
      echo "An instance was specified ($INSTANCE) so I will try to connect to it"
      echo "  (if this fails consider retrying without -instance and I will try to connect to the default one)"
   } else {
      $server_instance=$server
      echo "No instance specified so I will try to connect to the default one"
      echo "  (if this fails consider retrying with-instance SOME_INSTANCE and I will try to connect to that one)"
   }
   if (($sql) -and ($database)) {
      echo "You specified DB, SQL so I will try to execute it"
      echo "  (if this fails consider running me without -sql ... -db ... and I will try to just list available databases)"
      $connstring = 'Data Source={0};database={1};{2}' -f $Server_instance, $database, $cred
   } else {
       $sql='SELECT name FROM sys.databases;'   
      echo "You did not specify DB &  SQL so I will try to list all databases with $SQL"
      echo "  (you can also try -db ... -sql ... and I will try to run the specified SQL"
      $connstring = 'Data Source={0};{1}' -f $server_instance, $cred
   }

   $printable = ($connstring -replace 'password=[^;]*','password=****'  -replace ';',' ; ')
   write-host "Testing with:"
   write-host -NoNewline "  Connection String: "
   write-host -ForegroundColor cyan  $printable
   write-host -NoNewline "  SQL:               "
   write-host -ForegroundColor cyan  $sql
   $connectionString = $connstring 
   
   $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
   $command = new-object system.data.sqlclient.sqlcommand($sql,$connection)
   $connection.Open()
   if ($connection.State -eq "Open") {
      $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
      $dataset = New-Object System.Data.DataSet
      $adapter.Fill($dataSet) | Out-Null
      $connection.Close()
      $dataSet.Tables | select -First 10 |  ft   
   }

}
Topic revision: r14 - 08 Jun 2024, NickDemou
Copyright © enLogic