Skip to content

Instantly share code, notes, and snippets.

@Nalorokk
Created April 18, 2020 06:35
Show Gist options
  • Save Nalorokk/f458f68c43ab76d08c73378228a6b1de to your computer and use it in GitHub Desktop.
Save Nalorokk/f458f68c43ab76d08c73378228a6b1de to your computer and use it in GitHub Desktop.
Keenetic RCI API PHP
#!/bin/php
<?php
ini_set('default_socket_timeout', 15);
ini_set('display_errors', 1);
error_reporting(E_ALL);
if(keen_auth('admin', 'password')) {
$metrics = keen_request('rci/', '{"show":{"interface":{"stat":[{"name":"GigabitEthernet1"},{"name":"Wireguard0"}]}}}');
$data = $metrics[2];
var_dump($data);
}
function keen_auth($login, $password) {
$r = keen_request('auth');
if($r[0]['http_code'] == 401) {
$headers = parse_http($r[1]);
$md5 = md5($login.':'.$headers['X-NDM-Realm'].':'.$password);
$sha = hash('sha256', $headers['X-NDM-Challenge'].$md5);
$r2 = keen_request('auth', json_encode(['login' => $login, 'password' => $sha]));
if($r2[0]['http_code'] == 200) {
return true;
}
} elseif ($r[0]['http_code'] == 200) {
return true;
}
return false;
}
function parse_http($http) {
$result = array();
$lines = explode("\n", $http);
foreach ($lines as $line) {
$line = trim($line);
if(strpos($line, ': ') !== false) {
$line = explode(': ', $line);
$result[$line[0]] = $line[1];
}
}
return $result;
}
function keen_request($query, $post = null) {
$url = 'http://192.168.1.1:81/'.$query;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__.'/keen_cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__.'/keen_cookie.txt');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
if($post) {
echo "\nPost data: ".var_export($post, true)."\n\n";
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$json = null;
$notheader = mb_strcut($data, $info['header_size']);
if($query == 'rci/') {
$json = json_decode($notheader, 1);
}
return [$info, $data, $json];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment