PHP 利用wake on lan 喚醒電腦
這是非常好用的工具,對於系統維護管理很便利,目前的電腦主機板均都支援網路喚醒開機,這次用PHP簡單寫一個程式來喚醒電腦主機,萬一主機因為停電、或者是癱瘓了,還可以利用wake on lan的方式來喚醒,前提是電腦主機板要設定好wake on lan。
index.php
<?php
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
ob_start('mb_output_handler');
$_targets = array(
'ore-pc-1' => 'D8CB8AF1DBB4',
);
?>
<html lang="ja">
<head>
<title>Wake On LAN</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Wake On LAN</h1>
<?php if (array_key_exists('pc', $_GET) && array_key_exists($_GET['pc'], $_targets)): ?>
<h2><?php echo h($_GET['pc']) ?>MagicPacket送出成功</h2>
<?php wake('255.255.255.255', $_targets[$_GET['pc']], 9); ?>
<?php endif; ?>
<ul>
<?php foreach ($_targets as $name => $mac): ?>
<li><a href="?pc=<?php echo urlencode($name) ?>"><?php echo h($name) ?></a></li>
<?php endforeach; ?>
</ul>
</body>
</html>
<?php
function h($html) {
return htmlspecialchars($html);
}
function wake($ip, $mac, $port) {
$nic = fsockopen("udp://" . $ip, $port);
if ($nic) {
$packet = "";
for ($i = 0; $i < 6; $i++) {
$packet .= chr(0xFF);
}
for ($j = 0; $j < 16; $j++) {
for ($k = 0; $k < 6; $k++) {
$str = substr($mac, $k * 2, 2);
$dec = hexdec($str);
$packet .= chr($dec);
}
}
$ret = fwrite($nic, $packet);
fclose($nic);
if ($ret) {
return true;
}
}
return false;
}
?>
index.php
<?php
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
ob_start('mb_output_handler');
$_targets = array(
'ore-pc-1' => 'D8CB8AF1DBB4',
);
?>
<html lang="ja">
<head>
<title>Wake On LAN</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Wake On LAN</h1>
<?php if (array_key_exists('pc', $_GET) && array_key_exists($_GET['pc'], $_targets)): ?>
<h2><?php echo h($_GET['pc']) ?>MagicPacket送出成功</h2>
<?php wake('255.255.255.255', $_targets[$_GET['pc']], 9); ?>
<?php endif; ?>
<ul>
<?php foreach ($_targets as $name => $mac): ?>
<li><a href="?pc=<?php echo urlencode($name) ?>"><?php echo h($name) ?></a></li>
<?php endforeach; ?>
</ul>
</body>
</html>
<?php
function h($html) {
return htmlspecialchars($html);
}
function wake($ip, $mac, $port) {
$nic = fsockopen("udp://" . $ip, $port);
if ($nic) {
$packet = "";
for ($i = 0; $i < 6; $i++) {
$packet .= chr(0xFF);
}
for ($j = 0; $j < 16; $j++) {
for ($k = 0; $k < 6; $k++) {
$str = substr($mac, $k * 2, 2);
$dec = hexdec($str);
$packet .= chr($dec);
}
}
$ret = fwrite($nic, $packet);
fclose($nic);
if ($ret) {
return true;
}
}
return false;
}
?>
留言
張貼留言