Category Archives: Powershell

PowerShell Remoting in Multi-Platform Environments – Use Cases

In our previous post we discussed how to implement OpenSSH (the plumbing) as the transport layer for PowerShell remoting. In this post, we’re going to leverage that configuration and look at some common remoting use cases. This is one of the core things I use everyday when I work with PowerShell. Remoting gives me the ability to administer scale up and administer large collections of systems. So like I said in my very first post about my PowerShell journey, it’s become a part of my every day life and techniques like this are at the core of how I use PowerShell. So let’s get started…

We’re going to look at the following

  • Entering a remote command line interface on a server
  • Using sessions
  • Executing commands against one remote system
  • Executing commands on a collection of remote systems

This is going to be awesomeness…Yep, I said awesomeness, when I’m finished you’ll agree that’s about the only way to describe this.

I do want to point out that we’re using Beta software here, things change. The version of PowerShell I’m using here is Version 6 Beta 2.

Remote Command Line Interface

Up first, let’s cover the simplest remoting case, where we use remoting to get a command line interface to a remote system.

Nothing special here, simple syntax, but the seasoned PowerShell remoting pro will notice that we’re using a new parameter here -HostName. Normally on Windows PowerShell you have the -ComputerName parameter. Now, I don’t know exactly why this is different, but perhaps the PowerShell team needed a way to differentiate between OpenSSH and WinRM based remoting. Further, Enter-PSSession now has a new parameter -SSHTransport which at the moment doesn’t seem to do much since remoting cmdlets currently use OpenSSH by default. But if you read the code comments here, it looks like WinRM will be the default and we can use this switch parameter to specify SSH as the transport.

Once we execute this command, you’ll have a command prompt to the system that passed as a parameter to -HostName. The prompt below indicates you’re on a remote system by putting the server name you’re connected to in square brackets then your normal PowerShell prompt. That’s it, you now have a remote shell. Time to get some work done on that server, eh? Want to get out of the session, just type exit.

Using Sessions

So, in PowerShell, when you exit from a remoting session your session goes away. So any work, variables or program state you had will disappear. But what if we wanted to keep our session’s state, log out and log back into that session again? We can leverage sessions to help us persist our remote sessions. We can create a session connect and disconnect from it at will. So let’s check that out.

We create a new session by calling New-PSSession. This will start up the remoting session just like we did with Enter-PSSession, via SSH, but we won’t attach to the remote terminal. The output we do get from New-PSSession shows us the details of the session created. We use Get-PSSession to get a list of all current sessions.

We can connect to an existing session with Enter-PSSession. If there are multiple entries in your session list…just use the correct Id from the session list to identify the session you want to connect to.
Now, when you exit from this session with the exit command, your session will persist. Let’s use Get-PSSession to see.
Cool, our session is still there, let’s reuse it. This time we’re going to assign it to a variable this time. This will keep our command line syntax simple in the upcoming examples.

Executing Commands Against One Remote System

We can use PowerShell remoting to execute a command against a remote system, so let’s look at the simplest case…just one command. Here you can see, we’re using the Invoke-Command cmdlet to execute the Get-Process command on the remote system and it’s output returns to our console. Here we have the top 5 processes by CPU on the remote system.

Executing Commands Against a Collection of Remote Systems

Now, let’s add one more session to our list of sessions. With a new session to server2.
New-PSSession just returns the session created, so let’s get a list of all of the sessions with Get-PSSession. There you can see our two remoting sessions are currently opened the new session has a new Id.
This time, let’s take both our sessions and save them to a variable. We’re going to reuse $s.
Now to the amazing part…let’s run a command against a collection of remote systems.
This example brings up a very interesting point in PowerShell remoting, everything inside the curly braces of the Invoke-Command call happens on the remote system. This means, all the sorting and processing is remote, the remote systems deal with all the computational aspects and less data has to traverse the network. There’s a deeper topic of serialized objects we’ll cover in a later post. Now the output from these systems comes back to your console as fast as it comes back, so there’s really no order here. So you might get a list of data that’s all commingled. But we can control that by sorting locally. Let’s look at that.
Now, let’s say you want to get the top 5 processes across all the systems in your sessions list, easy enough.

We move the sorting to the pipeline on our local system, notice the Invoke-Command call is going to return the entire process list from all machines, then it will sort the data locally and output to the local console. So you can see in this list here we have the top 5 processes across our two systems. Imagine you had a web farm of servers and you needed to chase down a bad process fast, this would be useful, right?

When we’re all finished, you’ll want to clean up your sessions. We can do that a by passing the $s variable into Remove-PSSession

And that’s it, so like I said in my very first post about my PowerShell journey, it’s become a part of my every day life and techniques like this are at the core of how I use PowerShell.

PowerShell Remoting in Multi-Platform Environments using OpenSSH

So in my last post I told you about how I started my journey on learning PowerShell, let’s keep going down that path together. In this post I’m going to introduce PowerShell Remoting in Multi-Platform Environments, specifically using OpenSSH. We’ll discuss WinRM in multi-platform systems in an upcoming post.

Have you ever had to execute a command against one system or a collection of systems? Have you ever wanted a remote shell on a Windows system? Using Remoting you can you can do all of these things, very, very easily.

The Plumbing

So for our first stop, let’s talk about how remoting works. Essentially what’s occurring under the hood is a PowerShell process on one system is sending commands to a PowerShell process on another system then the remote system sends the output back. Easy enough, right? Let’s dig into to how it exchanges information.

The PowerShell processes exchange messaged defined in the PowerShell Remoting Protocol (PSRP). PSRP defines semantics of the communication and types of message being exchanged. Now these messages need a transport layer, for that we have WinRM and OpenSSH. Let’s look at both.

By default, Windows PowerShell systems Remoting connections communicate using WinRM which uses HTTP/S endpoints. WinRM is an implementation of the WS-Management industry standard. WS-Man defines the semantics of the interactions between the systems and data transfer. PowerShell encapsulates its PSRP messages and uses WinRM to transport them between systems.

On Linux systems, well…they don’t communicate with WinRM, by default, so we need something else…that’s where OpenSSH comes in. PowerShell encapsulates it’s inputs and outputs as PSRP messages and it uses SSH to securely exchange the messages between systems.

The PowerShell team has implemented WinRM over HTTP remoting on Linux and already has a port of OpenSSH on Windows. The key idea going forward is…we will have a choice, we can use WinRM (HTTPS) or we can use SSH regardless of OS. For the rest of this post, we’re going to talk remoting over OpenSSH, even on the Windows side of things. We’ll discuss WinRM in multi-platform systems in an upcoming post.

The Installation

For starters, go ahead and install PowerShell Core your systems if you haven’t already, its pretty straightforward check out this link here.

Next, on Windows we need to install OpenSSH and the PowerShell team has developed a Win32 port of OpenSSH. So go check that out here. I’m going to be honest, the installation isn’t easy. But I’m going to let you in on a secret, Darwin Savoy wrote a killer Chocolatey package that does the hard work for you. Check that out here. You’ll want to use the following syntax to install OpenSSH as a service.

If you’re on Windows verify OpenSSH is up and running

Now on Linux, just about every distribution includes an OpenSSH installation their default setup…so we’re not going to cover that here.

The Configuration

Wether it’s Windows or Linux, we need to tell OpenSSH about PowerShell and we can do that with a subsystem configuration.

On a Windows system we’ll need a line like this in SSH daemon configuration file C:\Program Files\OpenSSH\sshd_config. Find the subsystem section and add this line.

On a Linux system we’ll need a line like this one in /etc/ssh/sshd_config. Find the subsystem section and add this line.

Basically what’s going on here is we’re telling OpenSSH to invoke a PowerShell process when it receives a message from a remote system that’s says it’s going to use the PowerShell subsystem. So SSH is just the conduit for these two PowerShell processes to communicate their inputs and outputs.

When you’re finished editing these files, you’ll want to restart the SSH daemons on your system…Windows or Linux.

On Windows that’s Restart-Service -name sshd on Linux that’s systemctl restart sshd

Now here’s the thing…before you move on…test your SSH connections. You will absolutely go crazy if there’s an issue with your SSH configuration and you try using PowerShell Remoting right away. If there’s an issue, PowerShell will happily swallow OpenSSH’s errors and you’ll get no feedback. Simply grab your favorite SSH client and try to connect to the systems right now and verify you can connect and get a command line. Things will be a lot easier for you before you try to use remoting.

Up next in this series we’ll look at some remoting use cases, specifically using a command line interface, executing commands against remote a remote system and executing commands against a collection of remote systems.

Why PowerShell?

Why do I use PowerShell?

Well, here’s a little back story…last year I was involved in a Pluralsight Play by Play with Jason Helmick and Jeffrey Snover for launch of Open PowerShell on Linux and Mac. Before this video, I didn’t take PowerShell seriously. Basically, if I Google’d a problem and found a solution in PowerShell I would grind my teeth and copy and paste the text into the foreign blue console and cross my fingers.

Fast forward a bit to PowerShell Summit this year, Jason and I were slated to do a session together on…PowerShell on Linux. I had to miss the trip to Seattle this year, but during the session Jason told a story a story about me learning PowerShell…check it out here around 28:27. Its pretty funny. 

Pipelines similar but different

If you don’t want to listen to Jason’s story, it goes like this. I needed to learn PowerShell…FAST. I had only a few weeks to build my skills enough so that I could sit at a table with the inventor of PowerShell and an industry recognized expert and have a meaningful conversation and oh yea, record a 5 hour training video. So as Jason says I “did the Don Jones/Jeff Hicks thing” (there’s a newer version available now) .

Well, having a UNIX background I understood the concepts of a pipeline. UNIX processes have had pipelines for a long time. Byte streams can move data from one command to the next allowing you to build more complicated commands. PowerShell can do the same, but it moves objects…rather than text/byte streams. 

Well, while learning PowerShell I built a PowerShell cmdlet pipeline to get the top 10 processes on a system sorted by CPU.

And to do the same in bash, we need to do something like this…

So, I worked through these examples and I fired up my email client and sent an email to Jason and said hey Jason…here’s two commands that do the same thing. One in PowerShell and one in native bash commands. I asked…hey, which one do you think I like better? 

As we learned in the PowerShell Summit video, he expected me to answer with my crotchety, suspenders wearing UNIX guy answer…well he was in for a surprise. I told him I liked the first one better…the PowerShell version.

I actually don't own suspenders...neckbeards are another story

Now hear me out, I’ve been using Linux/UNIX since 1997, I manage large internet commerce sites through the holiday season, I’ve done PhD level research on topics like IO, CPU scheduling and memory management…literally my fingers can type the bash commands to get the top 10 processes without even thinking…muscle memory to the max. BUT, the PowerShell version of this literally reads like a sentence. Get-Process, Sort-Object, Select-Object, pretty straight forward stuff here. No surprises. the commands do exactly what they say. This means, I can put stuff like this in a script, and other people can read it without 20 years of experience. 

What’s next?

Well, since the Play By Play, PowerShell isn’t the Google the answer…copy/paste solution anymore for me…I’ve decided to really take this seriously and PowerShell is now a go to tool in my toolbox. I’m not telling you this because I’m a Microsoft MVP, I’m not telling you this because I did a video with THE PowerShell gurus…I’m telling you this because I really use PowerShell now…every day.

This post is the first post in a series I plan on bring to you that will document my discovery process of using PowerShell on Linux. We’ll discuss the techniques and technologies I use to solve some real world problems in a multi-platform world!

Now, there’s two things I really consider special about my first go with PowerShell…asynchronous job posting via Remoting and Desired State Configuration (DSC). We’ll cover these topics in this series. 

Speaking at PowerShell Summit!

Speaking at PowerShell + DevOps Global Summit 2017!

I’m proud to announce that I will be speaking at PowerShell + DevOps Global Summit 2017 on the conference runs from April 9th 2017 through April 12th 2017. This is an incredible event packed with fantastic content and speakers. Check out the amazing schedule!

This year I have two sessions!

On Tuesday, April 10th at 10:00AM – My session is with none other the Jason Helmick. Our session is “Cross platform Management – Windows/Linux

Here’s the abstract

Let Jason Helmick and Anthony Nocentino take you through a fun filled, demo heavy adventure of how Windows and Linux admins can work together managing a heterogeneous environment. You will learn all you need to know from both sides of the aisle to get started!

On Wednesday, April 11th at 10:00AM – I’m presenting solo on “Linux Fundamentals for the PowerShell Expert

Here’s the abtract

PowerShell is now available on Linux and your management wants you to leverage this shift in technology to more effectively manage your systems, but you’re a Windows guy! Don’t fear, iIt’s just an operating system! It has all the same components Windows has and in this session we’ll show you that.

We will look at the Linux operating system architecture and show you how to interact with and manage Linux system! By the end of this session you’ll be ready to go back to the office and get started working with Linux In this session we’ll cover the following – Process control – Service control – Package installation – Configuration management – System resource management (CPU, disk and memory) – Using PowerShell to interact with Linux systems

PowerShell Summit

 

Using dbatools for automated restore and CHECKDB

OK, so if you haven’t heard of the dbatools.io project run by Chrissy LeMaire and company…you’ve likely been living under a rock. I strongly encourage you to check it out ASAP. What they’re doing will make your life as a DBA easier…immediately. Here’s an example…

One of the things I like to do as a DBA is backup my databases, restore them to another server and run CHECKDB on them. There are some cmdlets in the dbatools project, in particular the Snowball release, that really make this easy. In this post I’m going to outline a quick solution I had to throw together this week to help me achieve this goal. We’ve all likely written code to do this using any number of technologies and techniques…wait until you see how easy it is using the dbatools project.

Requirements

  1. Automation – Complete autopilot, no human interaction.
  2. Report job status – Accurate reporting in the event the job failed, the CHECKDB failed or the restore failed.

Solution

  1. Use dbaltools cmdlets for restore and CHECKDB operations
  2. Use SQL Agent Job automation, logging and alerting

So let’s walk through this implementation together.

Up first, here’s the PowerShell script used to restore and CHECKDB the database. Save this code into a file named restore_databses.ps1

Let’s what through what’s going on here. First the line with $ErrorActionPreference = “Stop” that’s crucial because it will tell our script to stop when it encounters and error. Yes, that’s what I want. The job stops and the error from the cmdlets will reach the SQL Agent job we have driving the process. Using this, the job will fail, and I’ll have a nice log telling me exactly what happened.

Next we have some variables set, including the backup path and the location of the data and log files on the destination system.

Now, here’s the Restore-DbaDatabase cmdlet from the dbatools project, this cmdlet will traverse the backup path defined in -Path parameter, find all the backups and build the restore sequence for you. Yes…really! If you don’t define a parameter defining a point in time it will build a restore sequence using the most recent backups available in the share. The next few parameters define the destination data and log directories and tell the restore to overwrite the database if the database exists on the destination server. That next parameter tells the job to ignore using log backups. This is sufficient in my implementation because I’m running full backups daily, I don’t need the point in time recovery. You might, so give it a try. CHECKDB can take a long time…the final parameter, tells Invoke-SqlCmd2 not to timeout while running its query.

Now, I need to run some T-SQL to clean up the databases, for example, I change the recovery model, then shrink the log. This is so I don’t have a bunch of production sized log files laying around on the destination system I do this after each restore, this way I can save a little space. And finally, I run CHECKDB against the database.

If you want to do this for more than one database, you could easily parameterize this code and drive the process with a loop. You’re creative…give it a try.

Now, I take all this and wrap it up in a SQL Agent job.

SQL Agent Job Step

 Figure 1: SQL Agent Job Step Definition

Using a SQL Agent job, we get automation, reporting and alerting. I’ll know average run times, if the job fails and have a log of why and it sends me an email with the job’s results.

The SQL Agent job type is set to Operating system (CmdExec), rather than PowerShell. We run the job this way because we want to use the latest version of PowerShell installed on our system. In this case its version 5.1. The SQL Agent PowerShell job step on SQL 2012 I believe uses version 4 and when I used it, it wasn’t able to load the dbatools modules.

We need to ensure we install the dbatools as administrator. This way the module is available to everyone on the system, including the SQL Agent user, not just the user installing the module. Simply run a PowerShell session as administrator and use Install-Module dbatools. If you need more assistance check out this for help.

From a testing standpoint I confirmed the following things…

  1. When a restore fails, it’s logged to the SQL Agent job’s log, I get an alert.
  2. When one of the Invoke-SqlCmd2 calls fails, it’s logged to the SQL Agent job’s log and I get an alert.
  3. When CHECKDB finds a corruption in a database, it’s logged to the SQL Agent job’s log, the SQL Server Error Log and I get an alert. For testing this I used Paul Randal’s corrupt databases which he has available here.

So in this post, we discussed a solution to common DBA problem, backup, restore and CHECKDB a set of databases. Using dbatools, you can do this with a very simple solution like I described here. I like simple. Simple is easier to maintain. Certainly there are some features I want to add to this. Specifically, I’d like to write some more verbose information into the SQL Agent job’s log or use the job step’s ability to log to a file. Using those logs I can easily review the exact runtimes of each restore and CHECKDB.

Give dbatools a try. You won’t be disappointed…really go there now!

TugaIT – Pre-conference workshop on PowerShell on Linux

Where – Thursday, May 18, 2017

Where – TUGA IT – Lisbon, Portugal

Full Day Session – “Open Source PowerShell on Linux – Skills to Manage Your Heterogenous Data Center“ 

Registration Link – https://app.weventual.com/detalheEvento.action?iDEvento=4011

  • Early Bird Price – before 03/18/2017 – 150€
  • Normal Price – before 05/01/2017 – 200€
  • Late Registration – 05/18/2017 – 250€

PowerShell is now available on Linux and Mac and you want to use it to manage your multi-platform data center. In this workshop we will introduce Open Source PowerShell and learn why this is such a groundbreaking technology shift. Then we’ll get into the essentials of using PowerShell on Linux and Mac, we’ll start with installing Powershell and building PowerShell from source, work our way into using cmdlets and bash integration, building pipelines, remoting scenarios with heterogenous operating systems and discuss Desired State Configuration. 

You will learn how to

  • Set up your environment for multi-platform management
  • Bash and PowerShell scripting fundamentals
  • Building command pipelines in Bash and PowerShell
  • Toolmaking in Powershell
  • Configure remoting in multi-platform environments
  • Configuration management basics with Desired State Configuration

Topics

  • Setting up your OpenSource PowerShell environment
  • Working with PowerShell cmdlets and bash integration
  • Comparing the PowerShell pipeline and a UNIX style text-based pipeline
  • PowerShell concepts for building more general toolmaking
  • Remoting in multi-platform environments
  • Leveraging OpenSource PowerShell in your data centers with Desired State Configuration
  • What’s next and limitations

Prerequisites 

This is a fundamentals level workshop. This workshop’s intent is to introduce you to the technologies and get you started. Attendees should have basic understanding of the Windows and Linux operating systems.

Registration Link – https://app.weventual.com/detalheEvento.action?iDEvento=4011


Speaking at PowerShell Virtual Group of PASS

This month I’ll be speaking to the PowerShell Virtual Chapter of PASS. The session is on Linux OS Fundamentals for the SQL Admin. At the core of the session we will introduce you to OS concepts like managing files and file systems, installation packages, using PowerShell on Linux, managing system services, commands and processes and system resource management. This session is intended for those who have never seen or have very little exposure to Linux but are seasoned Windows or SQL administrators. Things like processes, memory utilization and writing scripts should be familiar to you but are not required.

Sign up now! https://attendee.gotowebinar.com/register/4762712017177605123

Wednesday, February 1, 12:00PM-1:00PM Eastern (GMT-5)

NewImage

Abstract

PowerShell and SQL Server are now available on Linux and management wants you to leverage this shift in technology to more effectively manage your systems, but you’re a Windows admin!  Don’t fear! It’s just an operating system! It has all the same components Windows has and in this session we’ll show you that. We will look at the Linux operating system architecture and show you how to interact with and manage Linux system. By the end of this session you’ll be ready to go back to the office and get started working with Linux with a fundamental understanding of how it works.

Interested in growing your knowledge about database systems, sign up for our newsletter today!

Building Open Source PowerShell

Open Source PowerShell is available on several operating systems, that really what’s special about the whole project! To get PowerShell to function on these various systems we need to build (compile) the software in that environment. This is what will produce the actual executable program that is powershell.

To facilitate the build process the PowerShell team has documented how to do this for the currently available platforms, Linux, MacOS and Windows. In this post I want to talk about why this is important, point you to the resources available online to help you build Open Source PowerShell and tell you my experiences building PowerShell on the Windows, macOS and Linux!

Why would one want to build PowerShell?

Well for me, I’m and internals geek and I want to be able to debug running PowerShell code so I can follow the flow of control during program execution. This will enable me to learn the internals of certain commands. A great way to see what’s happening on the inside.

Another reason is perhaps you want to contribute, you yourself can download the code…make a change and submit it to the PowerShell team for review. Pretty cool stuff at the “New Microsoft”. Following these steps you’ll be able to have a functioning environment to develop in.

Getting Started with building PowerShell

In general building complex software projects is not a trivial task, but the PowerShell team has done an exceptional job making this as easy as possible for everyone. The documented build processes leverage PowerShell scripts for installing the appropriate dependencies on your system and then managing the build process itself. At a high level, it’s really five easy steps. For more details on building for your platform, check out the links at the bottom of this post.

  1. Download the code from GitHub
  2. Install PowerShell
  3. Import the build module – build.psm1
  4. Install the build dependencies (toolchain setup) with Start-PSBootStrap
  5. Build PowerShell with Start-PSBootBuild (once this is finished, you’ll have a powershell executable)

My notes on building PowerShell

  • On the Linux side of things, it was VERY easy. The PowerShell team includes installation of all build dependencies and package installation for things like make and g++ inside Start-PSBootStrap then built powershell with Start-PSBootBuild
     
  • Well Windows was pretty easy too, but I had to install a few things manually. First I installed Visual Studio 2015, added the required C++ components, installed Chocolatey, installed cmake, downloaded the PowerShell source, ran Start-PSBootStrap to get the build dependencies, then built PowerShell with  Start-PSBootBuild
     
  • macOS was a little tougher, updated my installation of XCode, I installed Brew, installed cmake, downloaded the source, ran Start-PSBootStrap to get the build dependencies, then built PowerShell with Start-PSBootBuild. It failed with this error (which has since been corrected)
     
    •       deprecated in macOS 10.12 – syscall(2) is unsupported; please switch to a supported interface. For SYS_kdebug_trace use kdebug_signpost().

            [-Werror,-Wdeprecated-declarations]

          tid = syscall(SYS_thread_selfid);

                ^

      /usr/include/unistd.h:733:6: note: ‘syscall’ has been explicitly marked deprecated here

      int      syscall(int, …);

               ^

    • Basically what’s going on here is there’s a deprecated system call on macOS 10.12 which causes the completion to fail. To get the build to work, I changed the function to just return 0. Doing this will likely break something, so I’m not suggesting you do this. I just did this to get the build to work.  I’ve submitted this issue to the PowerShell team via GitHub here

What’s next?

Well, now that I’m able to get Open Source PowerShell built on three major operating systems I’m going to take some time using debugging techniques on each to see what’s going on under the hood inside of PowerShell when I execute certain commands. And of course, up first…Get-Process ;)

Resources for building Open Source PowerShell 

Here are some resources for you to get started working with the PowerShell Projects. 

Configuring Passwordless PowerShell Remoting over SSH

Open Source PowerShell has been on fire, getting tons of community support and really making people think about what’s to come with a single language to manage a heterogenous data center.

To highlight this point, in my recent Pluralsight Play By Play Microsoft Open Source PowerShell on Linux and Mac with Jason Helmick and Jeffrey Snover I did a demo on using PowerShell remoting where I connected from a Linux machine to three other machines and retrieved lists of top processes from each…two Linux and one Windows. I used one script to accomplish this and no passwords. A simple implementation highlighting a very big idea. After, some people have asked…how did I do this without passwords? 

Open Source PowerShell Remoting uses SSH as its communication protocol, so when we connect to a remote system using PowerShell Remoting we’ll need to enter a password. Normally SSH requires passwords to log into remote systems but it also allows for what’s called passwordless authentication, which means users can log into remote systems without having to key in a password. It does this, securely, by using a key pair to authenticate the user to the server. Basically you generate a key pair, copy the public key to the remote server and there you have it…you no longer have to enter a password when you SSH into the remote system. Let’s see how this is done.

You need a couple things to set up this demo

  1. A user account with the same name on each computer – create a user on each machine, Linux and Windows, with the same username.
  2. OpenSSH configured on all hosts – easy on Linux. It’s there by default. On Windows check out this link. Once you complete the installation of OpenSSH on your Windows system, test logging into that system from a remote computer with SSH. This will use the password for a user on that Windows system (likely the one you just created in step 1). If that doesn’t work, you won’t be able to proceed.
  3. Open Source PowerShell installed on all hosts – check out this link here
  4. Enable PowerShell Remoting over SSH – check out this link here. Once you have this configured, be certain to test PowerShell remoting, using passwords. Test Linux to Linux and also Linux to Windows. 

Now once we have the ability to connect to our hosts with SSH and we’ve confirmed we can use PowerShell SSH Remoting, we can move on to configuring passwordless authentication. 

First, on your Linux machine (I’m using a Mac, but there literally is no difference here) you can use your existing public key if you have one, which is stored in your home directory in .ssh/id_rsa.pub or you can generate a new one. 

To generate a new SSH key pair on your Linux machine

  1. Type sshkeygen
  2. The program will ask you for a file name, just press enter
  3. It will then ask you for a passphrase, press enter again and once more to confirm
You should get output that looks like this:

Demo-MacBook-Pro:.ssh demo$ ssh-keygen 

Generating public/private rsa key pair.

Enter file in which to save the key (/Users/demo/.ssh/id_rsa): 

Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 

Your identification has been saved in /Users/demo/.ssh/id_rsa.

Your public key has been saved in /Users/demo/.ssh/id_rsa.pub.

The key fingerprint is:

SHA256:g5SyXmke+OAmYSl4nxc4wcRnsyeDO6RE9/Q9FKlcpKY demo@demo-MacBook-Pro.local

The key’s randomart image is:

+—[RSA 2048]—-+

|   ..    .oo     |

|  .oo =. .+      |

| . .+*o=o=       |

|. ..oB=== o      |

|o.=o*.E+S  .     |

| +.=oO o .       |

|  . *.+          |

|   o .           |

|                 |

+—-[SHA256]—–+

 
Copy the public key from the Linux machine to the Windows Server

Now copy the contents of the id_rsa.pub file you just created to C:\Users\username\.ssh\authorized_keys on your Windows machine. Where username is the user you want to use for Remoting. You’ll likely copy and paste the contents of this file to the remote computer…if you do this ensure the contents are all on one line. I’m not going to go into how to configure this on Linux as there are plenty of blogs about how to do this on Linux – check it out here.
 
You’ll want to make sure you copy the same public key to all the hosts you’d like to authenticate with from this private key. In our case, the two Linux machines and the Windows machine have the same public key in the authorized_keys file on each server, inside user accounts with the same name.
 
Confirm you have Authorized Keys configured on your Windows SSH server
 
Now on the Windows machine in C:\Program Files\OpenSSH\sshd_config verify that this line is uncommented, which it should be by default. If not, uncomment it and restart the ssh service. This is the place SSH will look for keys when a user logs into the system via…SSH.

AuthorizedKeysFile .ssh/authorized_keys

Make sure that if you’re running SSH as a service, the account the service is running as had the ability to read this file. In my case the account NT SERVICE\SSHD needed read access.

Confirm SSH passwordless access from Linux (or Mac) to Windows

With that you should be able to connect from your Linux (or Mac) to your Windows machine from the machine where you generated your SSH key without any password. Likewise for your Linux machines.

Demo-MacBook-Pro:~ demo$ ssh demo@172.16.94.9

Microsoft Windows [Version 10.0.14393]

(c) 2016 Microsoft Corporation. All rights reserved.

 

demo@DESKTOP C:\Users\demo>

Let that sink in for a second, I just SSH’d into a Windows machine…

…and finally connect via PowerShell remoting over SSH with passwordless authentication

OK now we’re in the home stretch…we can now create a PowerShell remoting session over SSH with passwordless authentication. 

PS /Users/demo> Enter-PSSession-HostName 172.16.94.9 -UserName demo                                       

[172.16.94.9]: PS C:\Users\demo\Documents>

And there we have it we’re able to connect to using PowerShell Remoting over SSH without a password.

Questions about Linux? PowerShell? Please feel free to ask aen@centinosystems.com or on Twitter @nocentino

 

Open Source PowerShell – Play by Play

What’s going on here?

So last week you may have seen this picture on Twitter…it went a little crazy…and you may have been wondering what are we up to? Well, last week I had the pleasure of filming a Pluralsight Play By Play. A Play By Play is a course on Pluralsight but in a slightly different format than you may be used to. A Play By Play bring together industry experts to discuss and demonstrate an emerging technology. This Play by Play is on “Microsoft Open Source PowerShell – PowerShell on Linux and Mac” and is available now and is FREE! You do not have to be a subscriber!

Open Source PowerShell

Jason, Jeffrey and Anthony (me)

A Motley Crew

The purpose of this Play By Play is to bring to you insider knowledge of Open Source PowerShell. We discuss why this is important and also how it works. To do that Pluralsight pulled together a team to bring this to you.

What’s Covered in the Course

We dive deep into PowerShell’s architecture, the reasoning behind going Open Source, and also how you can leverage this in your data center. It’s not just talk, we show you with many live demos highlighting how really things work. The course is broken into 7 modules and since we’re all computer scientists, we start with Module 0…naturally.

  • Module 0Introduction
  • Module 1Open Source PowerShell – Architecture, concepts and getting started
  • Module 2PowerShell on Linux and Mac – An overview for the Linux pro of how PowerShell works
  • Module 3PowerShell Remoting – An overview for the Linux pro of how PowerShell Remoting works
  • Module 4Common Management Tasks – Common operations in Linux that can be done with PowerShell
  • Module 5Advanced Functions – Building higher level tooling with PowerShell
  • Module 6Desired State Configuration – What is DSC and how it works

The course is now available at Pluralsight

Personal Note

This was an incredible experience. I had to buckle down and learn PowerShell in about 6 weeks…I certainly didn’t want to make a fool of myself in front of the inventor of PowerShell and an industry recognized expert. The shoot lasted literally all day from 9-6PM. There’s a ton of material…you all will be very pleased. The key point to all of this is opening up PowerShell to multi-platform environments which is huge…TITANIC. This enables you to have one tool to manage a heterogenous data center. I’m taking this seriously and will continue to learn PowerShell. Thanks to Jason for guiding me along the way and sharing his knowledge with me you made this easy(er)! Thanks to Jeffrey for sharing your insight and vision. It was truly a pleasure. 

Behind the scenes!

Behind the scenes – Jason and Jeffrey