Using PowerShell through SSH

Introduction

Windows PowerShell is a new command-line shell and task-based scripting technology that provides comprehensive control and automation of system administration tasks. Windows PowerShell allows Windows administrators to be more productive by providing numerous system administration utilities, consistent syntax, and improved navigation of common management data such as the registry or Windows Management Instrumentation (WMI). Windows PowerShell also includes a scripting language which enables comprehensive automation of Windows system administration tasks. The Windows PowerShell language is intuitive and supports existing scripting investments. Exchange Server 2007 and System Center Operations Manager 2007 will be built on Windows PowerShell.

Windows Server 2003 Technologies - PowerShell

I come from UNIX, where the text shell is the preferred way to do system administration. I’ve been following Powershell née Monad for some time. Windows has needed a powerful shell since before MS-DOS (not sure what the default shell in Xenix was). The PowerShell team seems to be laying out some of the architecture that will be needed to bring Microsoft forward on this front. I’ve argued before that one of the reasons Google is beating Microsoft is the easy scriptability and command line interface on Google’s Platform, Linux. If Microsoft wants to play seriously with admins like me and compete with Apple and Google, they will have to continue building on PowerShell.

One of the key components of System Administration is remote access. It would be absurd to have to physically walk up to every machine you were responsible for and use the keyboard and mouse to configure or install anything. There are some pretty good tools for working with Windows remotely, but most of them require a video card and mouse. I can type upwards to 100 words a minute, anytime I have to move my hands off the home row to the mouse, I am losing productivity. Anytime I have to stream video, I am wasting bandwidth. I can administer a UNIX box from a palmtop device like a Sidekick over a slow cell phone connection.

One of the first things that an admin wants to do with PowerShell is run remotely. To do this securely, you must encrypt your data. SSH has been the proven way to do this. So the question becomes, how do I connect SSH and PowerShell together? With a little bit of kludge, it is possible. Why this wasn’t included by default in version 1.0, I have no idea. My advice and plea to the Microsoft developers is to just use SSH. Please don’t invent a proprietary Microsoft only tool to do this. Please please please please!

Note: The following assumes that you have logged in as a local admin and this account has a password.

Download and Install Cygwin

Fire up Firefox (or your favorite browser) and choose a Cygwin Mirror.

  • Select a mirror
  • Download setup.exe
  • Run setup.exe
  • Most of the defaults can be left as is

However, make sure to select SSH under the Network category. It will select the other required dependencies for you.

Configure Cygwin

Right click My Computer, select Properties -> Advanced -> Environment Variables.

Next, click the New button and add:

name: CYGWIN value: ntsec

Select the Path variable and click Edit then append ;c:\cygwin\bin (assuming you installed Cygwin here) at the end of the existing string.

Download and Install Microsoft Tools

Note: The following requires Microsoft Passport aka Live ID

Unzip the downloads and run their respective setup. I used all the defaults.

Run Cygwin

  • Either click the green Cygwin icon or run c:\cygwin\cygwin.bat
  • Run ssh install script: $ ssh-host-config
  • Answer “yes” to every question except for the last one, which should be ntsec

Should privilege separation be used? (yes/no) yes
Should this script create a local user ’sshd’ on this machine? (yes/no) yes
Do you want to install sshd as service?
(Say “no” if it’s already installed as service) (yes/no) yes

Which value should the environment variable CYGWIN have when
sshd starts? It’s recommended to set at least “ntsec” to be
able to change user context without password.
Default is “ntsec”. CYGWIN=ntsec

Start SSHD

$ net start sshd
The CYGWIN sshd service is starting.
The CYGWIN sshd service was started successfully.

Run Powershell

Start -> Programs-> Windows Powershell. Choose to always accept Microsoft signed code. Close PowerShell

Test SSH and Powershell

Run Putty or your favorite ssh client and connect to localhost. Accept the hash and login. If everything works, you should be at a bash prompt in Cygwin.

Next run PowerShell. Due to the limitations of PowerShell v1.0 we have to tell it that we are redirecting the input. Note that you won’t get any output from PowerShell indicating that it started up, including a command prompt!

$ /cygdrive/c/Program Files/Windows PowerShell/v1.0/powershell.exe -Command -

Try a PowerShell one-liner:

  • [System.Net.Dns]::GetHostbyAddress(”207.46.198.30″)
  • [System.Net.Dns]::GetHostAddresses(”www.msn.com”)
  • dir | where {$_.PsIsContainer}

Links

Credits

Big shout out and thanks to Lee Holmes for answering my e-mail and pointing me in the right direction, and PigTail Cygwin SSHD Instructions for clearing up some of the finer points in the SSH install.

26 Responses to “Using PowerShell through SSH”

  1. Lee says:

    Glad that it worked out for you. When I was playing with the same idea, connecting my Pocket PC phone to PowerShell via SSH from 200 miles away was truly a delightful experience.

    SSH won’t be our ultimate remoting model, though. As you might imagine, an object-based shell provides many opportunities to improve the remoting experience beyond what administrators are typically used to. It’s a top priority for our “V1 Refresh.”

  2. mmichie says:

    Well, I hope that Microsoft will at least make it easy to use SSH if an admin wants, even if you consider it “legacy” technology. :)

  3. Michael Dean says:

    Seriously, please include SSH access. Everytime I hear you guys say something “provides many opportunities to improve…” you go and make things worse and more difficult to use, rather than easier and better. Just like you claimed monad would be better than bash, yet I can’t even do something as simple as inline changing the text color in monad, whereas in bash this is easy and natural to do. How often do I actually do this in a bash script? All the time. I’ve learned how useful syntax highlighting is from programming for so many years, so I extend the concept to my scripts. Why should I have to specify new text colors on seperate lines? That’s absurd. Being that this is supposed to be an object oriented shell, it shouldn’t be hard to make this work. In C++, I would setup my streams classes to be able to do this:

    ostream

  4. Andrew Schulman says:

    The value of the CYGWIN environment variable should be “ntsec” (without quotes), not “netsec”.

  5. mmichie says:

    Thanks! Fixed the typo.

  6. Great article… Let’s wait the final version of PowerShell…

    []s,
    Vinicius Canto
    Brasil

  7. Jeffrey Snover says:

    > yet I can’t even do something as simple as inline changing the text color in monad, whereas in bash this is easy and natural to do.

    You are right. There are a number of things that should be a ton easier to do. A lot of that will get easier when we have a proper hosting environment (e.g. something other than the CONSOLE).

    Our plans for remoting are to leverage WS-MGMT the remoting protocol recently standardized through the DMTF. Withhold judgement for a while until you have a chance to see what we are doing with it - I think you’ll like it.

    Jeffrey Snover [MSFT]
    Windows PowerShell/Aspen Architect
    Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
    Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

    PSMDTAG:FAQ: SSH - can I use it with WIndows PowerShell?

    :

  8. [...] » Read more at hivearchive.com (tags: windows powershell ssh) [...]

  9. [...] Read the full article at source. [...]

  10. Tony says:

    How do you think of my powershell remoting?

    Tony

  11. Asking for help:

    I am trying to teach myself C programming. After buying two compilers I heard about Cygwin. I think I have it running. I get the prompt window and enter the program called cg.c in C:\cygwin\home\janice (after getting the added gcc added to my upload). I get a message that says the program should end with a newline. Also this ‘ld’ message as shown below.

    cg.c:

    #include
    main()
    {
    printf (”2345\n”);
    }

    janice@D97FQP91 ~
    $ gcc cg.c
    collect2: cannot find `ld’

    could you please help me get over this “compile it” hurdle?

    Thanks, SUPER THANKS,

    Happy

  12. Jeremy says:

    A more natural way to do this on WinXP/Server is with WinSSHD (http://www.bitvise.com/winsshd.html), which I was able to get working with Powershell in a matter of minutes.

    It’s not free, no, but at $40 for personal and $100 for business, it’s not bad at all.

  13. [...] PowerShell está disponible desde hace unos meses y puede usarse, previa descarga e instalación, en sistemas XP SP2, 2003 Server y ahora en Vista (que raro que no venga preinstalado con este…). Sin embargo no es lo que yo esperaba. Llevo unas semanas probándolo en una máquina virtual con XP y aprendiendo un poco de él a través del Script Centre y es cierto que amplía las posibilidades de administración sin depender del entorno gráfico y posibilitando la automatización de tareas. No obstante, tiene una terrible carencia para que pueda ser considerado una herramienta útil en entornos reales de producción: no permite una conexión remota a través de un canal seguro. Para solventar esta carencia existen al menos dos soluciones válidas (ambas externas a Microsoft), un tutorial para usar powershell a través de ssh mediante la intermediación de Cygwin y el proyecto PowerShell Remoting aún en fase beta. Estoy seguro de que Microsoft solucionará este problema en próximas versiones de la herramienta pero este “pequeño detalle” te da mucho que pensar acerca de las consideraciones de diseño que la empresa de Redmon está tomando a la hora de acometer este producto. ¿No hay administradores de sistema “reales” en el equipo para decirles que sin esta posibilidad no sirve absolutamente de nada? [...]

  14. [...] Of course, you can also install something like winSSHD (not free) from Bitvise and use Bitvise Tunnelier (ssh client) to get a remote command prompt. The Bitvise software works well as there are no limitations as described here. So when I connect to winSSHD with Tunnelier and then execute powershell.exe I get a prompt and can start to work with it. Command completion works as expected. [...]

  15. [...] pretty much any configuration. Sources for this article include my friend influx’s post about Powershell and SSH in Vista (used to point out a step I foolishly missed on the next source), pigtail’s OpenSSH/Cygwin [...]

  16. It’s always buy, buy, buy. Why not free:

    http://freesshd.com/index.php

  17. Lance says:

    /n software’s PowerShell Remoting product:
    http://www.nsoftware.com/powershell/download.aspx

  18. [...] The Hive Archive » Blog Archive » Using PowerShell through SSH Windows PowerShell : Announced: PowerShell to Ship in Windows This entry was written by stefan and posted on 30. September 2007 at 18:40 and filed under Windows, Software. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL. « KDE 4 for Microsoft Windows [...]

  19. chris says:

    How about the reverse? execute a ssh command from powershell and handle the output? Otherwise as and ESX server admin I am stuck writing on two plats

  20. [...] blog post from 2006 is currently the #1 Google Result for PowerShell SSH, but finally there is a good [...]

  21. mario says:

    this doesn’t seem to work that well. i tried running a script remotely and nothing. this configuration seems to work better:

    http://gotmvc.net/?p=3

  22. Lo0m says:

    another way how to combine SSH and Powershell (without need to use Cygwin) is here: http://lo0m.blogspot.com/2008/04/powershell-over-ssh.html

  23. Jeff says:

    I haven’t had much success with this yet. I can execute commands like ‘dir’ but not any of the powershell ‘get-*’ commands. The latter give the message “access is denied”. I can run powershell just fine interactively in either a cmd.exe or cygwin shell. Passwordless ssh also works fine otherwise. I’m using a Linux client, would that make a difference? I also tried:

    powershell -command “”

    This works in cmd.exe but not in cygwin. Any ideas what could be wrong?

    What would be really useful is to put the above in a ssh command:

    ssh administrator@win_server powershell -command “”

    With passwordless login, this command could be part of a script that could, e.g., perform the same command on a large number of windows servers almost simultaneously. (Such things are routinely done for Linux servers.) Has anybody tried this?

  24. Trevor says:

    Hi Jeff

    I have the exact same problem, I’ve tried with linux SSH and Tectia for windows if I ssh interactively I can run powershell scripts fine. If I try and run them from command line it just waits, until I hit CTR+C then it runs the script.

    Have you had any luck?

    Thanks

Leave a Reply