[AutoIt] Заметки на тему WOL (с форума autoitscript.com)

Включаем компьютер по сети:

; Target PC Info
$IP = "192.168.1.255"
$MAC = "000D8787E226"

UDPStartUp()
$sock = UDPOpen($IP, 7)
UDPSend($sock, BinaryString('0xFFFFFFFFFFFF' & _Repeat($MAC, 16)))
UDPCloseSocket($sock)
UDPShutdown()

Func _Repeat( $str, $reps )
   Local $ret = ''
   For $i = 1 to $reps
      $ret &= $str
   Next
   Return $ret
EndFunc

Узнаем MAC-адрес по IP через WMI:

Func _IP2MAC( $sIP )
    Local $oWMI = ObjGet("winmgmts:\\" & $sIP & "\root\CIMV2")
    If @error Then Return SetError(1, @error, "")
    Local $oNet = $oWMI.ExecQuery("SELECT IPAddress,MACAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled != 0", "WQL", 48)
    If @error Then Return SetError(2, @error, "")
    For $o In $oNet
        If $o.IPAddress(0) = $sIP Then Return StringReplace($o.MACAddress, ":", "")
    Next
    Return SetError(3, @error, "")
EndFunc

Пример с вычислением широковещательного адреса:

#Region AutoIt3Wrapper directives section
#AutoIt3Wrapper_Prompt=y
#AutoIt3Wrapper_Run_Debug_Mode=n
#AutoIt3Wrapper_UseUpx=y
#AutoIt3Wrapper_Allow_Decompile=n
#AutoIt3Wrapper_UseAnsi=y
#AutoIt3Wrapper_Res_Comment=send wake on lan packet to a mac address
#AutoIt3Wrapper_Res_Description=wake on lan packet generator
#AutoIt3Wrapper_Res_Fileversion=1.0.0.30
#AutoIt3Wrapper_Res_FileVersion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=CopyLeft 2007 - psadac
://////=__==http://www.gnu.org/copyleft/gpl.html)
#EndRegion

#NoTrayIcon

#include >String.au3<

Opt("MustDeclareVars", 1)
Opt("RunErrorsFatal", 0)

Const $wbemFlagReturnImmediately = 0x10
Const $wbemFlagForwardOnly = 0x20

; Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
Func ip2long($ip_str)
    Local $ip_arr = StringRegExp($ip_str, "(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", 1)
    If @error Then
        SetError(1) ; incorrect address
        Return 0
    EndIf
    Return BitOR( _
            BitShift($ip_arr[0], -24), _
            BitShift($ip_arr[1], -16), _
            BitShift($ip_arr[2], -8), _
            $ip_arr[3])
EndFunc   ;==>ip2long


; Converts an (IPv4) Internet network address into a string in Internet standard dotted format
Func long2ip($ip)
    Return BitAND(BitShift($ip, 24), 255) & "." & _
            BitAND(BitShift($ip, 16), 255) & "." & _
            BitAND(BitShift($ip, 8), 255) & "." & _
            BitAND($ip, 255)
EndFunc   ;==>long2ip


; sends a wake-on-lan packet on the broadcast address
Func wol($macAddr, $broadcastAddr)
    UDPStartup()
    Local $conn = UDPOpen($broadcastAddr, 7)
    Local $packet = _HexToString("FFFFFFFFFFFF" & _StringRepeat(StringUpper($macAddr), 16))
    UDPSend($conn, $packet)
    If @error Then
        SetError(@error)
        Return False
    EndIf
    UDPCloseSocket($conn)
    UDPShutdown()
    Return True
EndFunc   ;==>wol


If $cmdline[0] <> 1 Then
    MsgBox(48, "Error", "usage" & @TAB & ": " & @ScriptName & "  mac_address" & @CRLF & _
            "example" & @TAB & ": " & @ScriptName & "  005056C00001")
    Exit
EndIf

Local $macAddr = $cmdline[1]
If StringRegExp($macAddr, "[[:xdigit:]]{12}", 0) = 0 Then
    MsgBox(48, "Error", "the mac address must be 12 hex digits.")
    Exit
EndIf

; send wake on lan packet on each ip enabled local interface
Local $objWMIService = ObjGet("winmgmts:\\.\root\CIMV2")
Local $colItems = $objWMIService.ExecQuery ("SELECT IPAddress, IPSubnet FROM Win32_NetworkAdapterConfiguration " & _
        "WHERE IPEnabled<>0", "WQL", BitOR($wbemFlagReturnImmediately, $wbemFlagForwardOnly))

If IsObj($colItems) Then
    For $objItems In $colItems
        With $objItems
            Local $ip = ip2long(.IPAddress (0))
            If $ip <> 0 Then
                Local $subnet = ip2long(.IPSubnet (0))
                Local $broadcast_str = long2ip(BitOR($ip, BitNOT($subnet)))
                If wol($macAddr, $broadcast_str) Then
                    MsgBox(64, "Info", "Wake on lan packet sent to MAC address '" & $macAddr & _
                            "' using broadcast address '" & $broadcast_str & "'.")
                Else
                    MsgBox(48, "Error", "Failed to send Wake on lan packet") 
                EndIf
            EndIf
        EndWith
    Next
EndIf

Добавить комментарий

Filtered HTML

  • Адреса страниц и электронной почты автоматически преобразуются в ссылки.
  • Разрешённые HTML-теги: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Syntax highlight code surrounded by the <pre class="brush: lang">...</pre> tags, where lang is one of the following language brushes: autoit, bash, csharp, cpp, delphi, erlang, php, plain, powershell, sql.
  • Строки и параграфы переносятся автоматически.

Plain text

  • HTML-теги не обрабатываются и показываются как обычный текст
  • Syntax highlight code surrounded by the <pre class="brush: lang">...</pre> tags, where lang is one of the following language brushes: autoit, bash, csharp, cpp, delphi, erlang, php, plain, powershell, sql.
  • Адреса страниц и электронной почты автоматически преобразуются в ссылки.
  • Строки и параграфы переносятся автоматически.
11 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.