PowerShell Core–Updated setup OpenSSH in Windows and Linux

It’s been over a year since my last post on “PowerShell Open Source – Windows PSRemoting to Linux with OpenSSH”. A lot has change, so here’s the updated version.

Linux OpenSSH installation

In Linux (Ubuntu), open a terminal (Bash) session.

Install the following *packages:

sudo apt install openssh-server
sudo apt install openssh-client

*Note: The system will let you know if they already exist.

Need to configure the OpenSSH config file:

sudo gedit /etc/ssh/sshd_config

The, add following line in the “subsystem” area:

Subsystem powershell pwsh.exe -sshs -NoLogo -NoProfile

Proceed to save the file.

Now, execute the following lines:

sudo ssh-keygen –A

Restart the ‘ssh’ service by executing the following command:

sudo service ssh restart

Windows OpenSSH installation

In *Windows Client or Server, open Services to ‘Stop‘/’Disable‘ both SSH Broker and SSH Proxy.

*Note: Latest Windows Insider Builds having the following services previously installed: SSH Broker and SSH Proxy

Open PowerShell Core Console (Run as Administrator):

[sourcecode language=”powershell”]
pwsh

[/sourcecode]

First thing, make sure Chocolatey is installed in PowerShell Core: https://chocolatey.org/install

[sourcecode language=”powershell”]
iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’)

[/sourcecode]

*note: Chocolatey Install instructions will run ‘Set-ExecutionPolity Bypass’. The problem is, it won’t change it back to the previous setting.
Make sure to run “Get-ExecutionPolicy” to verify current settings.

Installing OpenSSH package from Chocolatey:

[sourcecode language=”powershell”]
choco install openssh

[/sourcecode]

Close/Reopen PowerShell Core (Run as Administrator), and execute the following command:

[sourcecode language=”powershell”]
refreshenv

[/sourcecode]

Change Directory to the OpenSSH folder:

[sourcecode language=”powershell”]
cd ‘C:\Program Files\OpenSSH-Win64\’

[/sourcecode]

Now, we need to make changes to the sshd_config file with Notepad:

[sourcecode language=”powershell”]
Notepad sshd_config

[/sourcecode]

Need to enabled the following commented out lines:

[sourcecode language=”text”]
Port 22
PasswordAuthentication yes
PubkeyAuthentication yes

[/sourcecode]

Finally, add the subsystem line to include PowerShell Core path:

[sourcecode language=”text”]
Subsystem     powershell    C:/Program Files/PowerShell/6.0.0-rc.2/pwsh.exe -sshs -NoLogo –NoProfile

[/sourcecode]

Save the file and we are ready to configure the firewall rule for port 22.

Windows Firewall Port 22 Setup

Next, confirm that there are no other TCP ports using port 22:

[sourcecode language=”powershell”]
netstat -anop TCP

[/sourcecode]

Now, add the SSH firewall rule for using port 22:

[sourcecode language=”powershell”]
netsh advfirewall firewall add rule name=SSHPort22 dir=in action=allow protocol=TCP localport=22

[/sourcecode]

Open Firewall app and verify it’s added.

Completing Windows OpenSSH Installation

The following steps are essential for the sshd service to start without any issues. Make sure to be at the OpenSSH folder:

[sourcecode language=”powershell”]
## – Generate SSH keys:
ssh-keygen -A

## – Execute both fix permissions scripts:
.\FixHostFilePermissions.ps1 -confirm:$false
.\FixUserFilePermissions.ps1

## – Install both ssh services: sshd and ssh-agent:
.\install-sshd.ps1

[/sourcecode]

Then, set both sshd and ssh-agent services set to start automatically.

[sourcecode language=”powershell”]
Set-Service sshd -StartupType Automatic
Set-Service ssh-agent -StartupType Automatic

[/sourcecode]

At this point, only start service sshd which will turned on the ssh-agent service.

[sourcecode language=”powershell”]
Start-Service sshd
#Start-Service ssh-agent (optional)

[/sourcecode]

Must important, open the *Services MMC console and verify that all running.

*Note: On the server will be needed to set the credential as Local System (see below).

Now, proceed to test connectivity between two system using PowerShell Core.  To test connectivity could use the following command:

Enter-PSSession -hostname systemname -username UsenameHere

Additional Note:

I found an issue when been a member of a domain but the Domain is Off. Trying to restart ssh service, I get the following error:

[sourcecode language=”powershell”]
PS C:\Program Files\OpenSSH-Win64> Start-Service sshd
Start-Service : Failed to start service ‘sshd (sshd)’.
At line:1 char:1
+ Start-Service sshd
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

[/sourcecode]

Or trying to manually start the “sshd” service using the Services MMC:

This error was due to missing a step in the installation:

Resolution: Thanks to Github Win32-OpenSSH @bagajjal provided the following steps:

[sourcecode language=”powershell”]
## – Fixing sshd service not starting with the NET Service credentials:
.\FixHostFilePermissions.ps1 -Confirm:$false
.\uninstall-sshd.ps1
.\install-sshd.ps1
[/sourcecode]

This resolved the sshd start failure. (see below)

Streamlining SQL Server Management Objects (SMO) in PowerShell Core

I’ve been recently posting about getting SQL Server Management Objects (SMO) Framework to work in PowerShell Core in both Windows and Linux Systems. So, here’s the revised blog post as the method has kept improving. This way you can start creating some cross-platform SMO PowerShell Core scripts in your environments.

It will works the following way:
1. Windows connecting to Windows SQL Server.
2. Windows connecting to Linux SQL Server.
3. Linux connecting to Linux SQL Server.
4. *Linux connecting to Windows SQL Server.

*Note: Any issues with firewall connecting from Linux to Windows, can be solved by creating the inbound rule for Linux in Windows Firewall.

How to get the SMO for PowerShell Core?

It’s easy! You can get it from NuGet Gallery using PowerShell Core Console. Just make sure you open PowerShell Core as an Administrator to avoid any installation issues.

You could use the following one-liners to find and install the recent SMO package. The following “if-else” code snippet can execute in either Windows or Linux PowerShell Core console.

[sourcecode language=”powershell”]

# Register NuGet package source, if needed
# The package source may not be available on some systems (e.g. Linux)
if (-not (Get-PackageSource | Where-Object{$_.Name -eq ‘Nuget’}))
{
Register-PackageSource -Name Nuget -ProviderName NuGet -Location https://www.nuget.org/api/v2
}else{
Write-Host “NuGet Already Exist! No Need to install.”
}

[/sourcecode]

Installing SMO from NuGet Gallery

After we verified NuGet Package Management is already installed in our system, then we can proceed in Find/Install “SQL Server Management Objects (SMO) Framework“. The current version is “140.17199.0”.

Execute the following one-liner by using the Find-Package to make sure is available. Then, do the install-package command

[sourcecode language=”powershell”]

## – Check that the NuGet feed is available and has the SMO package:
Find-Package -Name Microsoft.SqlServer.SqlManagementObjects

## – Install latest SMO package from NuGet:
Install-Package -Name Microsoft.sqlserver.SqlManagementObjects -Scope CurrentUser

## – Next Line Confirmed Installation:
Get-Package Microsoft.SqlServer.SqlManagementObjects

[/sourcecode]

As of today (November 6th, 2017), the current version of Microsoft.SqlServer.SqlManagementObjects is 140.17199.0. And, it can be installed on either Windows and Linux systems from NuGet.

For more NuGet information about the SMO package, click on the following link: https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects

Locating SMO Assemblies and connect to SQL Server

In order to use SMO in PowerShell, we need to know where they are installed. The next one-liner gets the NuGet location to build the path of the SMO installed assemblies.

[sourcecode language=”powershell”]

## – Help find and save the location of the SMO dll’s in a PowerShell variable:
$smopath = Join-Path ((Get-Package Microsoft.SqlServer.SqlManagementObjects).Source `
| Split-Path) (Join-Path lib netcoreapp2.0)

[/sourcecode]

The SMO path is saved. We are ready to load the needed SMO assemblies, to connect and work with SQL Server. The code snippet below will load the SMO assemblies, connect to SQL Server providing necessary credentials:

[sourcecode language=”powershell”]

# Add types to load SMO Assemblies only:
Add-Type -Path (Join-Path $smopath Microsoft.SqlServer.Smo.dll)
Add-Type -Path (Join-Path $smopath Microsoft.SqlServer.ConnectionInfo.dll)

## – Prepare connection and credential strings for SQL Server:
## – (Connection to Linux SQL Server single instance sample)
$SQLServerInstanceName = ‘lxSql00’; $SQLUserName = ‘sa’; $sqlPwd = ‘$Pswrd1!’;

## – (Connection to Windows SQL Server multi-instance sample)
$SQLServerInstanceName = ‘winSql01,1450’; $SQLUserName = ‘sa’; $sqlPwd = ‘$Pswrd1!’;

## – Prepare connection passing credentials to SQL Server:
$SQLSrvConn = New-Object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($SQLServerInstanceName, $SQLUserName, $SqlPwd);
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn);

[/sourcecode]

In the previous code sample, I included some variance in providing the SQl Server instance for cross-platform use:
1. In Linux, either using the “SqlServername” or, “IP-Address“.
2. In Windows, either using the “SqlServerName“, or “IP-Address“, or in the case of mutliple instance “SqlServerName,Port“.

Now that the SMO connection to the SQL Server has been established, then we can continue to explore our options using .NET SMO Framework. The Code snippet below shows how to display some of the SQL Server SMO information .NET properties:

[sourcecode language=”powershell”]
## – SMO Get SQL Server Info:

$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;

## – End of Code

[/sourcecode]

More SMO Options…

There are additioanl sources providing SMO dll’s:
1.NuGet SMO: https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects/#
2.GitHub SQLToolService: https://github.com/Microsoft/sqltoolsservice
3.Installing SQL Server mssql-scripter(Python-based): https://github.com/Microsoft/sql-xplat-cli

I’ve been using GitHub “SqlToolsService” for some time now and it works closs-platform. At the same time, I’ve been keeping it up-to-date:
https://github.com/Microsoft/sqltoolsservice/releases

Conclusion

I dare to say! Using .NET SQL Server Management Objects (SMO) Framework, let you be flexible adding control over your scripting. Keep in mind, this is well documented in Microsoft MSDN site: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/sql-server-management-objects-smo-programming-guide

My number one choice is to use NuGet Package Management. Although, you can play around with the GitHub SqlToolsService version as it gets frequent updates. The trick in using the GitHub version, is to add the path to where the Dll’s are stored and you’re good to go.

Just Dare to Experiment! Keep learning PowerShell!

Special Thanks to Microsoft: Matteo Taveggia and  David Shiflet for providing me with Nuget PowerShell code piece. I just change it a little!

SAPIEN PowerShell Tools at Orlando Microsoft Ignite Conference 2017

As I started a new role working for SAPIEN Technologies as their Technology Evangelist in September, I had the opportunity to be working with them a the Microsoft Ignite Conference in Orlando.

Greatly appreciate this opportunity and the chance the meet everyone interested in PowerShell as well as our SAPIEN PowerShell Tools at the event.

Feel free to reach out, keep asking about our product, product services, and must important, give us feedback on how to make it better.

Don’t forget to check out our blog posts, support forums, YouTube videos, and specially the “Information Center” under the following link: https://www.sapien.com/support

 

 

PowerShell Core Stable SQL Server SMO Assemblies and DataRow objects

Yes! Just recently I downloaded the latest SQL Server SMO assemblies that can be use with PowerShell Core in both Linux and Windows. You can find them in Github under Microsoft SqlToolsService. But, you’ll need to extract only the necessary DLL’s before you can start creating your PowerShell Core SMO scripts. There’s no installation program, as this is installed manually.

There’s one requirement I would suggest to do. Download and install .NET Core 2.0.
To download click this link: https://www.microsoft.com/net/download/core

Manual SMO Installation

The latest SqlToolsService version can be found at this Github link: https://github.com/Microsoft/sqltoolsservice/releases
I’m currently using is V1.1.0-alpha.31.

Just download the file for the OS you’re working:

1. In Windows, download the zip file “Microsoft.SqlTools.ServiceLayer-win-x64-netcoreapp2.0.zip
a. Open the zip file.
b. In the zip app, select only the following dll’s:

Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Dmf.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Management.SmoMetadataProvider.dll
Microsoft.SqlServer.Management.SqlScriptPublishModel.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll
Microsoft.SqlServer.SqlEnum.dll
Microsoft.SqlServer.SqlParser.dll
NetCoreGlobalization.dll

c. Extract all selected dll’s into your *PowerShell Core Beta folder “C:\Program Files\PowerShell\6.0.0-beta.x”.

2. In Ubuntu Linux, download the tar file “Microsoft.SqlTools.ServiceLayer-ubuntu16-x64-netcoreapp2.0.tar.gz“.
a. To open the file, use either Desktop Nautilus, or use the command-line tar command.
b. In your home folder, create a folder for the dll’s you’re going to extract (for example: mkdir sqltoolsservice).
c. In the tar app, Select only the following dll’s:

Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Dmf.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Management.SmoMetadataProvider.dll
Microsoft.SqlServer.Management.SqlScriptPublishModel.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll
Microsoft.SqlServer.SqlEnum.dll
Microsoft.SqlServer.SqlParser.dll
NetCoreGlobalization.dll

d. Extract the files into the folder you created.

Definitely, using the GUI tar or zip application seems better as you can use the Ctrl key to individually highlight the files to extract.

*Note: Keep in mind, when you add these dll’s into the PowerShell Core folder, uninstalling PowerShell beta won’t removed them. You must manually delete them and the folder.

Verifying SMO Works

In order to test SQLServer Management Objects working with PowerShell Core, we are going to use the following PowerShell Core script snippet:

[sourcecode language=”powershell”]
# – Windows Hack:
cd ‘C:\Program Files\PowerShell\6.0.0-beta.x’

# – Linux Hack:
cd /home/username/SqlToolsServices

# – Loading necessary SMO Assemblies:
$Assem = (“Microsoft.SqlServer.Management.Sdk.Sfc”, `
“Microsoft.SqlServer.Smo”, `
“Microsoft.SqlServer.ConnectionInfo”,
“Microsoft.SqlServer.SqlEnum”);
Add-Type -AssemblyName $Assem

# – Prepare variables for connection strings to SQL Server using SQL Authentication:
$SQLServerInstanceName = ‘Sql01,1451’;
$SQLUserName = ‘sauser’; $sqlPwd = ‘$MyPwd99!’;

## – Prepare connection to SQL Server:
$SQLSrvConn = new-object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($SQLServerInstanceName, $SQLUserName, $SqlPwd);
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn);

## – SMO sample 1
## -> Get SQL Server Info:
$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;

## – SMO sample 2
## -> To execute T-SQL Query:

# – Prepare query string variable:
$SqlQuery = “SP_WHO2”;

# – Execute T-SQL Query:
[array]$result = $SQLSrvObj.Databases[‘master’].ExecuteWithResults($SqlQuery);

# – Display T-SQL Query results:
$result.tables.Rows | Select-object -first 10 $_ | Format-Table -AutoSize;

[/sourcecode]

When executing the code both Windows and Linux, make sure you are in the folder you installed the dll’s files or it won’t execute.

In Window, in PowerShell Core console stays in folder: “C:\Program Files\PowerShell\6.0.0-beta.x”.

In Ubuntu Linux, in PowerShell Core console, change directory to “SqlToolsService”.

The above script will verify your manual installation of the SMO dll’s in PowerShell Core was successful. Now, you can use SMO in PowerShell Core in both Linux and Windows. And, most important, the previous issue I describe in my previous blog post “PowerShell Core – Getting SQL Server using ADO.NET Data provider” about the DataRow object has been cleared. So, there’s no need for adding code to fix the object to display data columns and values correctly.

Please, go ahead the give it a try! It’s great that now we can use PowerShell Core in Linux to create .NET object we can use and take advantage of this technology.

FLPSUG goes live at Keiser University Port St. Lucie

Yes, its finally happening! Thanks to Leslie Haviland (Director of Student Services), Dewan Persaud (Program Chair Information Technology), and staff to help me setting this meeting at their Port St. Lucie location.

Everyone is welcome to attend no matter what’s your skill level. I’m hoping that this will be first of many upcoming meetings as this technology is finally On-Demand in the industry. Keep in mind, PowerShell is also available Open Source running on Linux and Mac OS’s.

Most important! Is never too late to start learning about PowerShell.

Please, come over or register at: bit.ly/2u6unrs

Event Address:
Keiser University – Port St. Lucie
9400 SW Discovery Way
(Room 106)
Port St. Lucie, FL 34987

Hope to see you all there!

FLPSUG – Next Online meeting July 26th 2017

I’m working on getting a meeting with Keiser University to allow me to host my Florida PowerShell User Group Monthly meetings at their Port St. Lucie Campus location.  But, in the meantime, I setup July’s Online meeting for Wednesday 26th at 6:30pm (EST).

This month topic:

Working with SQL Server for Linux Cross-Platform

You’re welcome to explore the latest build of SQL Server for Linux, including everything you need to install and connect to SQL Server. He will also look into the tools that are available to use from Linux and / or Windows. Maximo will provide samples on querying for database information using Python/Java and PowerShell between two environments. This will be a demo intensive session you will not want to miss!

To register, click on the following Eventbrite link: https://www.eventbrite.com/e/florida-powershell-user-group-monthly-meeting-july-2017-tickets-36113308879?ref=estw

I hope you can joined me in this exciting session!

Using Linux SQL Server SMO in PowerShell Core

Yes! It’s possible. Here’s the information in how to set it up and start doing some PowerShell scripting. But, first understand that everything posted here is still a Work-In-Progress. And, the good news, it’s all Open Source.

I hope you find the following information essential as there’s no really any instruction in how to install these components. So, let’s get started!

Where To Get It!

The Microsoft SQL Tools Service is a set of API that provided SQL Server Data Management capabilities on all system cross-platforms. It provide a small set for SMO dll’s enough to get started.

You can download the file from following Github link: https://github.com/Microsoft/sqltoolsservice 

Here’s the list of available SMO DLL’s currently include in the “SqlToolsService – ServiceLayer” file:

[sourcecode language=”text”]
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Dmf.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Management.SmoMetadataProvider.dll
Microsoft.SqlServer.Management.SqlScriptPublishModel.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll
Microsoft.SqlServer.SqlEnum.dll
Microsoft.SqlServer.SqlParser.dll
[/sourcecode]

Keep in mind, this list will continue to grow and we hopefully expect more SMO DLL’s added.

Installation pre-requisites

In my case, I got various systems setup: Windows and Ubuntu 16.04. So, I make sure I download correct *zip or *tar.gz file

As, pre-requisite, you will needed to have already installed *”.NET Core 2.0 Preview 1” for the SQL Service Tools to work and remember this need to be installed in all systems.

Just in case, here’s the link to download “.NET Core 2.0 Preview 1“: https://www.microsoft.com/net/core/preview#windowscmd
https://www.microsoft.com/net/core/preview#linuxubuntu

Now, because we are working with PowerShell Core, don’t forget to install the latest build found at:
https://github.com/PowerShell/PowerShell/releases

Windows Installation

You need to get the file from the latest release. At the time I writing this blog, it’s Pre-release “v1.0.0-alpha.34 – .Net Core 2.0 build“.

To make *”Sql Tools Services” to work in PowerShell Core, I had to extract all content in the file into the “C:\Program Files\PowerShell\6.0.0-Beta.x” folder. Remember, this will replace any existing DLL’s on that folder.

*Caution: This steps should be done on a test machine as there’s always a possibility that it could PowerShell Core DLL’s.

Don’t forget that all these components are still in development but this should stopped us from trying and even contributing.

The file you’ll need to download for Windows is: microsoft.sqltools.servicelayer-win-x64-netcoreapp2.0.zip

Please, for now ignore the *microsoft.sqltools.credentials*.  If you install the Credentials DLL’s in the PowerShell Beta folder, PowerShell will not work.

Linux Installation

Now, for Linux is a different story as there’s no need to add the DLL’s in the PowerShell Core folder. You need to get the file from the latest release. At the time I writing this blog, it’s Pre-release “v1.0.0-alpha.34 – .Net Core 2.0 build“.

I would recommend doing the following steps in the Bash Console:

1. At your /home/user-name location, create the sqltoolsservice folder:

[sourcecode language=”bash”]
maxt@MyUbuntu01:~$ mkdir sqltoolsservice
[/sourcecode]

2. Change directory and Download the file for Ubuntu:

[sourcecode language=”bash”]
maxt@MyUbuntu01:~$ cd sqltoolsservice/
maxt@MyUbuntu01:~/sqltoolsservice$ wget https://github.com/Microsoft/sqltoolsservice/releases/download/v1.0.0-alpha.34/microsoft.sqltools.credentials-ubuntu16-x64-netcoreapp2.0.tar.gz
[/sourcecode]

3. Continue extract the *tar.gz into the folder:

[sourcecode language=”bash”]
maxt@MyUbuntu01:~$ tar -xzvf microsoft.sqltools.credentials-ubuntu16-x64-netcoreapp2.0.tar.gz
[/sourcecode]

That’s it for Linux. Now, you are ready to work with SMO and PowerShell.

Testing SMO in PowerShell Core

This is changing my way I script SMO in PowerShell. As my normal way I’ve been scripting SMO in PowerShell doesn’t work in PowerShell Core. Basically, a few more lines need to be added and now I will use the Add-Type to get the SMO assemblies loaded.

Loading SMO Assemblies

The first step is to load the SMO assemblies needed to start working with SQL Server. So, the following line is finally depricated and won’t work:

[sourcecode language=”powershell”]
[system.reflection.assembly]::LoadWithPartialName(“Microsoft.SQLServer.Smo”)
[/sourcecode]

The old method I’ve been using for a long time will failed because is expecting the “Property Login …” to be set.

The updated way, has been replaced by the Add-Type with the following essential three assemblies:

[sourcecode language=”powershell”]
## – Loadind SQL Server SMO assemblied needed:
$Assem = (
“Microsoft.SqlServer.Management.Sdk.Sfc”,
“Microsoft.SqlServer.Smo”,
“Microsoft.SqlServer.ConnectionInfo”
); Add-Type -AssemblyName $Assem;
[/sourcecode]

The above assemblies are required in order to work since SQL Server SMO 2012 and greater. You can have limited use when connecting to SQL Servers version 2005, and possibly 2000.

Prepare connection parameters for Windows Systems

In Windows systems, we use ‘Integrated Authentication‘. But, here’s where things change a bit since SQL Server 2012 SMO. You will need to prepare the connection parameters, and set the *.UseIntegratedSecurity property to ‘true‘ (the default is ‘false‘). At the same time, you’ll need to set the password to ‘null’ in order to connect successfull.

[sourcecode language=”powershell”]
## – Prepare connection strings and connect to a Windows SQL Server:
$SQLServerInstanceName = ‘sqlsvrinst01,1439’;
$SQLUserName = ‘winUsername’;
$SQLSrvConn = new-object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($SQLServerInstanceName, $SQLUserName, $null);
$SQLSrvConn.UseIntegratedSecurity = $true;
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn)
[/sourcecode]

Now, you can query the PowerShell Object $SQLSrvObj.

[sourcecode language=”powershell”]
## – Query PowerShell Object:
$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;
[/sourcecode]

Prepare connection parameters for Linux Systems

For Linux systems, we use ‘SQL Authentication’. Here we add the SQL User password, then passing the value to the SqlConnectionInfo class.  And, the *.UseIntegratedSecurity property by the default is ‘false‘.

[sourcecode language=”powershell”]
## – Prepare connection strings and connect to a Linux SQL Server:
$SQLServerInstanceName = ‘sqlsvrinst01,1439’;
$SQLUserName = ‘sqluser01’; $sqlPwd = ‘$usrpwd01!’;
$SQLSrvConn = new-object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($SQLServerInstanceName, $SQLUserName, $SqlPwd)
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn)
[/sourcecode]

Again, you can proceed to query the PowerShell Object $SQLSrvObj.

[sourcecode language=”powershell”]
## – Query PowerShell Object:
$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;
[/sourcecode]

Please notice in the above image, the Windows 10 Insider Build 16215 Bash Console is running PowerShell Core. This list insider release made it possible for PowerShell Core to be functional again.

Conclusion

As we can see, this opens new opportunities to build cross-platform PowerShell scripts solutions working with SQL Servers in Linux, Windows, and others.

This is very exciting to start experiencing first hand these upcoming changes. I can’t deny that’s it’s challenging but you can’t turn down an opportunity to gain more skills.

Please, take advantage and subscribe to Microsoft Azure. Build, test, and start deploying solutions. Don’t be afraid to be creative. We all learn thru trial and errors!

This is a good time to keep up with what’s going on with technology.

Additional References:

Microsoft Azure: https://azure.microsoft.com/en-us/
Github: https://github.com/
Ubuntu: https://www.ubuntu.com/
Microsoft Windows Bash Shell: https://msdn.microsoft.com/en-us/commandline/wsl/about
Microsoft Academy: https://mva.microsoft.com/
Microsoft Channel 9: https://channel9.msdn.com/
Microsoft MVP Blog: https://blogs.msdn.microsoft.com/mvpawardprogram/
Microsoft SQL Server Docs: https://docs.microsoft.com/en-us/sql/sql-server/sql-server-technical-documentation
Microsoft PowerShell Blog: https://blogs.msdn.microsoft.com/powershell/

PowerShell, and SQL Server Working with Anaconda

On my previous blog “PowerShell – Working with Python and SQL Server“, I show how to install Python 3.5 so we can be build python scripts to connecting to SQL Server and use them with PowerShell.

Now, since the release of SQL Server 2017 and the integration of Anaconda (ie. Python 3.6), we need to know what it takes to successfully install Anaconda on your developer system(s) both Windows and Linux.

Installing Anaconda in Windows

In Windows the installation is simply done through the SQL Server 2017 setup process. During the SQL Server installation process, select the “Machine Learning Services (In-Database)” option and this will automatically install both “R” and *”Anaconda” on your system.

*Note: Installing Anaconda (Python 3.6) will redirect any previous version of Python to version 3.6. So, you may need to manually revert back to use older version.

Installing Anaconda in Linux (Ubuntu)

There are few more steps to complete the installation on *Linux. First, verify which is the latest version available by going to the following link: https://www.continuum.io/downloads

Then follow these steps in bash console:

1. Change directory to where you want to store the installation file:

[sourcecode language=”bash”]
$ cd Downloads
[/sourcecode]

2. The “curl” command for the latest version available:

[sourcecode language=”bash”]
$ curl -O https://repo.continuum.io/archive/Anaconda3-4.3.1-Linux-x86_64.sh
[/sourcecode]

3. Run the installation command:
[sourcecode language=”bash”]
$ bash Anaconda3-4.3.1-Linux-x86_64.sh
[/sourcecode]

4. Enter “Yes” to Accept the license agreement.

6. Then, you can select the location where Anaconda will be installed. The default is the user home folder.

5. Add the Anacona path to user profile in the “.bashrc” file by answering “Yes” and this will force to open Python on version 3.6.

6. Finally, to activate Anaconda, type the following command:

[sourcecode language=”bash”]
$ source ~/.bashrc
[/sourcecode]

If you want to use any previous version, then you’ll need to manually type the PythonX.x executable. Try the following commands to open other versions of python previously installed in Ubuntu: python3.5, python2, or python2.7.

*Note: These steps can be applied to WSL Windows 10 Bash.

Using “update-alternatives” Linux Command

You could also setup the “update alternatives” command to swapt between the different versions of Python. This command need to be executed under super-user privilege “sudo su“.

Below is the series of commands use with “update-alternatives“:
[sourcecode language=”bash”]
##-> Install python for ‘update-alternatives’ command use:
$ sudo su
# update-alternatives –list python # will not display python

##-> To setup to use different versions:
# update-alternatives –install /usr/bin/python python /usr/bin/python2.7 5
# update-alternatives –install /usr/bin/python python /usr/bin/python3.5 1
# update-alternatives –install /usr/bin/python python /home/Username/anaconda3/bin/python3.6 2

##-> To list all installed pythons:
# update-alternatives –list python

##-> To change Python version, then select which version
# update-alternatives –config python

##-> You can use the –remove parameter to get rid of any lines added:
# update-alternatives –remove python /usr/bin/python3.5
[/sourcecode]

Remember, in Ubuntu Linux, the system default version of Python is 2.7.

It would be a bad routine, when using the “update-alternatives” command, to change back to the default version as all running scripts during the system updates will need run on Python 2.7.

Additional Package for SQL Server

During the Anaconda installation, you’ll notice that it will load lots of python packages for data science and including “tk” which provide the ability to create GUI applications.

But, there’s one package missing, “pyodbc” will be needed in order to create python scripts to connect with SQL Server.

I did install PYODBC in both Windows and Linux, run the following command at the console:

[sourcecode language=”bash”]
conda install pyodbc
[/sourcecode]

Then, to test this package was loaded, open *python and type:

[sourcecode language=”python”]
import pyodbc
## – Connect to database:
cnxn = pyodbc.connect(‘DRIVER={ODBC Driver 13 for SQL Server};SERVER=MTRINIDADLT2,51417;DATABASE=master;UID=sa;PWD=$SqlPwd01!’)
cursor = cnxn.cursor()
[/sourcecode]

Unfortunately, in Ubuntu Linux, the connection string will fail giving the following error:

[sourcecode language=”python”]
cnxn = pyodbc.connect(‘DRIVER={ODBC Driver 13 for SQL Server};SERVER=MTRINIDADLT2,51417;DATABASE=master;UID=sa;PWD=$SqlPwd01!’)
Traceback (most recent call last):
File “”, line 1, in
pyodbc.Error: (‘01000’, “[01000] [unixODBC][Driver Manager]Can’t open lib ‘/opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.6.0’ : file not found (0) (SQLDriverConnect)”)
>>>
[/sourcecode]

Strangely enough, this error is only on Ubuntu Linux and not Windows installation. So, Python 3.6 will work on Windows to build your scripts to work with SQL Server while Microsoft and/or Anaconda figured this one out.

*Note: This sample connection string to SQL Server is done thru SQL Server Authentication.

Configuring Anaconda in SQL Server 2017

This is only available in SQL Server 2017 and SQL Server Management Studio v17 with the feature of integrating Anaconda (Python 3.6) with SQL Server is to be able to execute the python script(s) from SQL Server Stored-Procedure.

The following steps need to be complete to enable SQL Server to execute Python scripts as an external script from SSMS SQL Query or within a stored-procedure.

1. Execute the following T-SQL command:

[sourcecode language=”sql”]
sp_configure ‘external scripts enabled’, 1
reconfigure
[/sourcecode]

2. Then, SQL Server Service will need to be restarted for the changes to take place.

3. Proceed to execute a python script from SSMS SQL Query panel:

[sourcecode language=”sql”]
execute sp_execute_external_script
@language = N’python’,
@script = N’
import sys
print(“Hello SQLServer, I am Python Version:”)
print(sys.version)

[/sourcecode]

Unfortunately, I haven’t been successful to run the SSMS SQL query connected to a SQL Server on Linux. So, apparently there’s still a limitation in Linux.

What with PowerShell!

So the main purpose of integrating Anaconda (Python 3.6) with SQL Server is to be able to execute the script from SQL Server Stored-Procedure. But, one of Anaconda installed packages is ‘tk‘.

The ‘tk‘ package allows you to create GUI application in Python. This opens opens opportunities to develope and integrating some solution with PowerShell. For example, PowerShell v6 Alpha doesn’t have the Out-GridView command available yet.

So, here’s a raw with limited functionality of a python Out-GridView look-a-like. The following sample code will access some data from SQL Server, use PowerShell to manipulate the information, and then use Python ‘tk’ component to display it in a GUI datagrid.

[sourcecode language=”powershell”]
$runpy = @’
import pyodbc
from tkinter import *

cnxn = pyodbc.connect(‘DRIVER={ODBC Driver 13 for SQL Server};SERVER=MTRINIDADLT2,1738;DATABASE=master;UID=sa;PWD=$Adm1n!’)
cursor = cnxn.cursor()

#Execute T-SQL Query:
trecord = []
tsql = ‘SELECT Name, Location, Hire, HireDate FROM SampleDB1.dbo.HolidayEmployees;’
if cursor.execute(tsql):
row = cursor.fetchone()
while row:
datarow = [str(row[0]),str(row[1]),str(row[2]),str(row[3])]
trecord.append(datarow)
row = cursor.fetchone()

## – list to screen list of data and will get number of rows in the list:
i = 0;
for i, rec in enumerate(trecord):
print(rec);

for i, rec in enumerate(trecord):
col = 0;
for c in rec:
Label(text=c, relief=RIDGE, width=15).grid(row=i, column=col)
col = col + 1;

mainloop()
‘@;

python -c $runpy;
[/sourcecode]

As you can image, there’s a lot of room to grow for integrating technologies such as PowerShell and Python. Just be creative!

Additional Tips

1. To edit, or commented out, the Anaconda Path, in the .bashrc file:

[sourcecode language=”bash”]
$ sudo gedit ~/.bashrc
[/sourcecode]

 

2. To find out all installed packages in Anaconda, use the following command:

[sourcecode language=”bash”]
$ conda list
[/sourcecode]

3. Upgrading Anaconda to newer version:

[sourcecode language=”bash”]
## – Windows:
conda update –prefix ‘C:\Program Files\Anaconda3’ anaconda
## – Linux:
$ conda update anaconda
[/sourcecode]

Additional Resources

* Don’t forget to check out Microsoft Data Amp Technical Sessions at: http://tinyurl.com/lmuquxu
* Check What’s new about SQL Server 2017? https://docs.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2017
* Getting started in SQL Server on Linux: https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-get-started-tutorial
* Download Anaconda: https://www.continuum.io/downloads

PowerShell, SQL Server, and Linux Oh My!

The South Florida Code Camp 2017 is ON! Come and join me in this event on Saturday, March 11th 2017 all day event.

Check out the event speaking agenda: http://www.fladotnet.com/codecamp/Agenda.aspx

I will be presenting the following 3 sessions:

1. 09:50am – 11:00amWorking with SQL Server for Linux Cross-platform:
I will be showing the latest build of SQL Server vNext for Linux. Everything you need to install and connect to SQL Server. Then, what tools are available to use from either Linux and Windows. Sample on querying for database information using Python and PowerShell between two environments. This will be a demo intensive session.

2. 11:10am – 12:20pm Using Windows 10 Bash with PowerShell Open Source:
We’ll be taking a tour into Windows 10 Bash Linux subsystem. I’ll be sharing some tips on how to work with Bash, and the workaround to make PowerShell in side BASH. This is the perfect environment to start learning about Linux while you work in windows. We’ll be take advantage of how-to use cross-platform Open source product(s). All this and more from Windows 10.

3. 01:20pm – 02:30pm Using PowerShell Open Source across multiple Platforms:
PowerShell is Open Source now! Come see how you could use PowerShell cross-platform between Windows and Linux sharing scripts to assist in admin task automation. I’ll be walking on how to make this work with existing tools. Also, interacting with SQL Server for Linux.

To register go to the following link: http://www.fladotnet.com/codecamp/

IDERA Geek Synch Webinar – Wednesday February 22nd, 2017

Topic: Using PowerShell with Python and SQL Server


Description: Just as PowerShell is argued as the main technology for automation in Windows Datacenters Infrastructure, it is equally important in other non-Windows Operating Systems. According to Maximo Trinidad, Windows Administrators have an advantage working with PowerShell just as Linux Administrators have an advantage with Bash / PHP / Python.

Webinar starts at: 11:00AM – 12:00PM (CDT) / 12:00pm – 01:00pm (EST)

Register at: https://www.idera.com/events/geeksync