Wake on LAN

Wake on LAN with ASP.Net and Magic Packets

Many props have to go out to this individual:  http://devinfra-us.blogspot.com/2011/02/using-powershell-20-from-aspnet-part-1.html

After reading this post, I was able to do something quick and dirty that helped me a lot.  I wanted an Intranet page that I could use to remotely wake up servers on the LAN. Bassicaly, you’re sending a magic packet to a server and asking it to wake up. To do that, you need to configure that server to wake up, usually in the BIOS, wake on ethernet or something similar.

Running Processes PowerShell OutputWhat I do like about powershell is being able to combine so much into simple one liners…it makes it very easy to construct the required magic packet (first 6 bytes are FF hex/255 int followed by 16 repetitions of the target MAC address for the spec’s required 102 bytes). Here’s a snapshot of how I used it to grab a list of running processes.

Anyhow, here’s the skinny:

1.  Add a reference in your project to System.Management.Automation in your Visual Studio project

2.  Front-end code (you can take out all that Jquery stuff)

<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="PowerShellApp._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script src="Scripts/jquery-1.4.1.min.js" language="javascript" type="text/javascript"></script>
    <script type="text/javascript">
        function SetScript() {
            document.getElementById('MainContent_PowerShellCodeBox').value = "get-process|out-string"
        }
        function ClearScript() {
            document.getElementById('MainContent_PowerShellCodeBox').value = ""
        }
    </script>
    <center>
        <div>
            <table border="0">
                <tr><td><h1>PowerShell Tool</h1></td></tr>
                <tr><td><h3>PowerShell Script (Script runs on Intranet Server)</h3></td></tr>

                <tr><td>
                    <asp:TextBox ID="PowerShellCodeBox" runat="server" TextMode="MultiLine" BackColor="DarkBlue" ForeColor="White" Width="700" Height="100"></asp:TextBox>
                </td></tr>

                <tr><td>
                    <asp:Button ID="ExecuteCode" runat="server" Text="Run It" Width="200" onclick="ExecuteCode_Click" /><asp:Button ID="TestCode" runat="server" Text="Test Me" Width="200" onclick="ExecuteCode_Click" />
                </td></tr>

                <tr><td><h3>Result</h3></td></tr>
        
                <tr><td>
                    <asp:TextBox  ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" BackColor="DarkBlue" ForeColor="White" runat="server"></asp:TextBox>
                </td></tr>

            </table>
        </div>
        <div id="sampletext" style="text-align:left;width: 75%">
                $mac = [byte[]]("F4-CE-46-B6-1C-2C".split('-') |% {[int]"0x$_"})<br />
                $UDPclient = new-Object System.Net.Sockets.UdpClient<br />
                $UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)<br />
                $packet = [byte[]](,0xFF * 102)<br />
                6..101 |% { $packet[$_] = $mac[($_%6)]}<br />
                $UDPclient.Send($packet, $packet.Length)<br />
        </div>
        <div id="defaultspinner"></div>
    </center>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#sampletext").show();
            $("#defaultspinner").hide();
        });
        $("#MainContent_TestCode").click(function (event) {
            $("#sampletext").hide();
            $("#defaultspinner").show();
            $("#defaultspinner").load("DefaultSpinner.aspx");
        });
    </script>
</asp:Content>

3. Back-end code (remember, quick and dirty here, no separation of presentation, no exception handling, etc…)

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class _Default

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        TestCode.Attributes.Add("onmouseover", "SetScript();")
        TestCode.Attributes.Add("onmouseout", "ClearScript();")

    End Sub

    Protected Sub ExecuteCode_Click()

        ' Clean the Result TextBox
        ResultBox.Text = ""

        ' Validate there was something in the box
        If (PowerShellCodeBox.Text.Length <= 0) Then             ResultBox.Text = "You need to give me a script so I can run it."             Exit Sub         End If         ' Initialize PowerShell engine         Dim shell As PowerShell         shell = PowerShell.Create         ' Add the script to the PowerShell object         shell.Commands.AddScript(PowerShellCodeBox.Text)         ' Execute the script         Dim results = shell.Invoke         ' display results, with BaseObject converted to string         ' Note : use |out-string for console-like output         If (results.Count > 0) Then

            ' We use a string builder ton create our result text
            Dim builder = New StringBuilder

            Dim psOjbect As PSObject
            For Each psOjbect In results

                ' Convert the Base Object to a string and append it to the string builder.
                ' Add \r\n for line breaks
                builder.Append(psOjbect.BaseObject.ToString() + "\r\n")

            Next

            ' Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
            ResultBox.Text = Server.HtmlEncode(builder.ToString())

        Else

            ResultBox.Text = "The command did not produce results or there was a syntax error."

        End If

    End Sub

End Class
Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: