LoginSignup
1
2

More than 5 years have passed since last update.

外部から社内のパソコンへWake on lanを実装したときのまとめ(サーバー側)

Last updated at Posted at 2017-07-07

外部からリモートデスクトップするためのwake on lanを実装したときのサーバー側のまとめ

前提資料

必要事項

・外部から見れるサイトを社内にサーバーを立てれること
※Web UIとかログイン認証、sslは別途でやってね

概要

前提として下記の設定が必要になります。(マシンによって異なる)

8e70e928d849800df74cd206b0d90d74.png

今回はphpでWake on lanを実施する部分のみ

wakeonlanにはMAC Addressが必要だが、Ip Addressしかわからない人がいるのでコマンドを使って探す処理を実装

***.php

//ip address → mac address
if(isset($ip_address && $ip_address != ""){
    $mac = "";
    $pcs = shell_exec("nmap -sP {$ip_address} ");
    $pcs = shell_exec("arp -a");
    $pcss = explode("\n",$pcs);

    foreach($pcss as $value){
        if(strripos($value,$ip_address !== false){
            if(preg_match("/([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}/",$value,$match) === 1){
                $mac = $match[0];
                break;
            }
        }
    }
    if($mac != ""){
        $ping = " {$ip_address} → MAC address {$mac}";
    }else{
        $ping = "get faild";
    }
}

その逆

***.php
//mac address → ip address 
if(isset($mac_address) && $mac_address != ""){
    $ip = "";
    #Need to change *.*.*. (192.168 or 172.16 or ....)
    $pcs = shell_exec("nmap -sP 192.168.6.* ");
    $pcs = shell_exec("arp -a");
    $pcss = explode("\n",$pcs);

    foreach($pcss as $value){
        if(strripos($value,$mac_address) !== false){
            if(preg_match("/\(([a-zA-Z0-9.]+)\)/",$value,$match) === 1){
                $ip = substr(substr($match[0],1),0,-1);
                break;
            }
        }
    }
    if($ip != ""){
        $ping = "MAC address {$mac_address} → IP address {$ip}";
    }else{
        $ping = "get failed";
    }
}

また上記で参照できないことがあるので下記をcronで走らせる
*.*.*.は192.168.1や192.168.2、172.16.3等に環境に応じて変える

***.php
for a in `seq 1 254`; do ping -c 1 -w 0.5 *.*.*.$a > /dev/null && arp -a *.*.*.$a | grep ether; done

MAC Addressがわかったら下記でバッチに引き数を渡す

※batchの実行ユーザーに気を付ける事、この場合はapacheのユーザーを使用して実行

***.php
#run user apache
shell_exec("wakeonlan.sh ".$mac_address);
wakeonlan.sh
#!/bin/sh
echo 'apache' | sudo -S ether-wake $1
echo "$1 start"

その後の起動確認は下記で実装

***.php
$res = shell_exec("ping -c 4 -W 5 ".$ip_address);
$array = explode("\n",$res);
if(strripos($res,'0 received') === false){
    $ping = "boot success";
}else{
    $ping = "boot failed";
}

まとめgithub:https://github.com/abotkugyu/wakeonlan

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2