SlideShare une entreprise Scribd logo
1  sur  20
The better PHP API
(По-доброто PHP API)
By Vasil Rangelov a.k.a. boen_robot
What is this “API” thing?
 In programming:
 “Application Programming Interface” - A set of operations, their
inputs and outputs, unified by common purpose, and available to
the programmer.
 In MikroTik RouterOS:
 Layer7 client/server protocol (ala HTTP, FTP, SSH, etc.)
 Intended for machines, not for humans
 Rigid, structured and lacking “human” conveniences
 To avoid confusion, the protocol will be referred to as
“RouterOS API”.
06 Nov 2014"The better PHP API" by Vasil Rangelov
2
What can it be used for?
 Creating custom management UI
 Integration of RouterOS with external applications, e.g.
 Billing systems
 Self-service applications
 Monitoring tools
 In a word: Automation.
06 Nov 2014"The better PHP API" by Vasil Rangelov
3
SSH vs. RouterOS API
 Both could be used for automation
 SSH is intended for human use
 “Cosmetic” changes from one RouterOS version to another can
cause problems with automation tools
 Renames/removal of commands/arguments/properties can cause
not just hard to detect failures, but potential damages too
 RouterOS API is intended for machine use
 Only changes to the protocol itself could possibly cause issues
 Easy to detect failures, and potential recovery without damages.
06 Nov 2014"The better PHP API" by Vasil Rangelov
4
Languages with general purpose
RouterOS API clients
 PHP (3)
 Java (2)
 .NET (C# (3), VB.NET (1))
 Python (2)
 Node.js (1)
 Perl (2)
 Ruby (1)
 Delphi (2)
 C/C++ (4)
 Erlang (1)
 ActionScript (1)
06 Nov 2014"The better PHP API" by Vasil Rangelov
5
Comparison of PHP RouterOS API clients
06 Nov 2014
6
"The better PHP API" by Vasil Rangelov
Client API PHP class
(Denis Basta)
RouterOS PHP class
(ayufan)
API PHP package
(boen_robot)
Requires PHP version 5.2+ 5.2+ 5.3+
Raw protocol I/O Yes No Yes
General purpose conveniences One method
(comm())
No Set of classes
CRUD and misc. conveniences No Yes Yes (1 class)
Asynchronous requests No Callbacks only Yes
Scripts No Pseudo Yes
Persistent connections No No Yes
Command line emulation No No Pseudo
Preparing the target router for RouterOS API
 For RouterOS earlier than v6.0, enable the protocol with
 /ip service enable api
 The protocol is enabled by default since RouterOS v6.0
 The RouterOS user needs to have the “api” policy
 Default user groups all have it; Take care when using custom groups
 If using the firewall’s “input” or “output” chains, ensure
incoming connections to TCP port 8728 are allowed, as are
outgoing connections from TCP port 8728.
06 Nov 2014"The better PHP API" by Vasil Rangelov
7
Preparing the client device for RouterOS API
 Install everything needed to create and run programs in
your language of choice
 For PHP, this means installing the PHP interpreter itself, and perhaps
plug it into a web server
Easiest with all-in-one solutions like XAMPP: http://apachefriends.org/
For command line applications, PHP itself from http://php.net/ is enough
 Allow all involved executables (“php” and maybe “httpd”)
to make outgoing connections to TCP port 8728
 For Windows, to get to the firewall, press Win+R, and run “wf.msc”.
06 Nov 2014"The better PHP API" by Vasil Rangelov
8
First use of the PHP RouterOS package (quick way)
 Download the PHAR file from https://pear2.github.io/Net_RouterOS/
 Create a file in Apache’s “htdocs” folder called f.e. “rostest.php”, with
the following contents:
06 Nov 2014"The better PHP API" by Vasil Rangelov
9
<?php
use PEAR2NetRouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';
try {
$client = new RouterOSClient('192.168.0.1', 'admin', 'password');
echo 'OK';
} catch (Exception $e) {
die($e);
}
 Adjust the path to the “.phar” file, the RouterOS IP and credentials as needed
 Open a web browser and run http://localhost/rostest.php.
Alternative installation methods
 Extract the TGZ or ZIP files from https://pear2.github.io/Net_RouterOS/
 Include “src/PEAR2/Autoload.php”
 Using Composer:
 composer require pear2/net_routeros
 Include “vendor/autoload.php”
 Using PEAR:
 pear channel-discover pear2.php.net
 pear install -a pear2/PEAR2_Net_RouterOS-alpha
 Include “PEAR2/Autoload.php”
 Using Pyrus:
 pyrus install -o PEAR2_Net_RouterOS-alpha
 Include “PEAR2/Autoload.php”.
06.11.2014"The better PHP API" от Васил Рангелов
10
Troubleshooting (step 1: environment issues)
 Open up the command line
 On Windows, Win+R, and run “cmd”
 Start the PHAR file with PHP
 Windows:
 "D:pathtophp.exe" "D:pathtoPEAR2_Net_RouterOS.phar“
 UNIX:
 "/the/path/to/php" "/the/path/to/PEAR2_Net_RouterOS.phar“
 Check the output for any warnings or errors
 Note: For brevity, “php PEAR2_Net_RouterOS.phar” will be used in
the following slides in place of full paths. Adjust accordingly.
06 Nov 2014"The better PHP API" by Vasil Rangelov
11
Troubleshooting (step 2: connection issues)
 Start the PHAR file with the router’s IP as an argument
 php PEAR2_Net_RouterOS.phar 192.168.0.1
 If using a different TCP port for the RouterOS API (e.g. 443):
 php PEAR2_Net_RouterOS.phar -p 443 192.168.0.1
 Check the output for any errors and possible solutions
 All is OK if you get nothing, and are allowed to type
Enter “/quit” (without the quotes), and press Enter twice to exit.
06 Nov 2014"The better PHP API" by Vasil Rangelov
12
Troubleshooting (step 3: login issues)
 Start the PHAR file with the RouterOS username and password
added at the end, e.g.
 php PEAR2_Net_RouterOS.phar 192.168.0.1 "admin" "password"
 Check the output for any errors and possible solutions
 All is OK if you get nothing, and are allowed to type
Enter “/quit” (without the quotes), and press Enter twice to exit.
06 Nov 2014"The better PHP API" by Vasil Rangelov
13
Example: Torch for 4 seconds
06 Nov 2014"The better PHP API" by Vasil Rangelov
14
<?php
use PEAR2NetRouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';
$client = new RouterOSClient('192.168.0.1', 'admin', 'password');
header('Content-Type: text/plain');
$torchRequest = new RouterOSRequest('/tool torch duration=4');
$torchRequest->setArgument('interface', $_GET['nic']);
foreach ($client->sendSync($torchRequest) as $response) {
foreach ($response as $name => $value) {
echo "{$name}: {$value}n";
}
echo "====n";
}
Example: Print RouterOS logs
06 Nov 2014"The better PHP API" by Vasil Rangelov
15
<?php
use PEAR2NetRouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';
$client = new RouterOSClient('192.168.0.1', 'admin', 'password');
header('Content-Type: text/plain');
$util = new RouterOSUtil($client);
foreach ($util->setMenu('/log')->getAll() as $item) {
echo $item('time') . ' ' . $item('topics') . ' ' . $item('message') . "n";
}
Example: Executing script with parameters
06 Nov 2014"The better PHP API" by Vasil Rangelov
16
<?php
use PEAR2NetRouterOS;
require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';
$client = new RouterOSClient('192.168.0.1', 'admin', 'password');
header('Content-Type: text/plain');
$util = new RouterOSUtil($client);
$util->exec('
/ip dhcp-client lease
make-static [find address=$address]
comment [find address=$address] $name
/log info "User $name now has the static IP $address"
',
array(
'name' => $_GET['user'],
'address' => $_GET['ip']
)
);
Support
 Documentation and more examples
 GitHub wiki: https://github.com/pear2/Net_RouterOS/wiki
 MikroTik wiki: http://wiki.mikrotik.com/wiki/API_PHP_package
 Ask questions
 MikroTik forum: http://forum.mikrotik.com/
 Report bugs or request features for the client
 GitHub issue tracker: https://github.com/pear2/Net_RouterOS/issues
 Report bugs or request features for the protocol
 MikroTik support: support@mikrotik.com.
06 Nov 2014"The better PHP API" by Vasil Rangelov
17
Technical FAQ
 Can I run a RouterOS API application on the router itself?
 No
 Can I log in hotspot users with the API protocol?
 No. Not with the API protocol, not with SSH, not with Winbox even.
 Hotspot users can ONLY be logged in when THEIR devices make an
HTTP(S) request to the router with their credentials
 What if my target router is behind NAT?
 Solutions are same as those applicable for any TCP protocol
 VPN?
 What about encryption?
 The API protocol has an TLS encrypted variant on port 8729
 PEAR_Net_RouterOS supports it, but due to PHP problems, such
connections are very unstable currently.
06 Nov 2014"The better PHP API" by Vasil Rangelov
18
Social FAQ
 Why make another PHP client?
 I don’t like the other PHP clients
 Also many of the non-PHP clients, but it’s better to have something than nothing, so…
 The protocol is easy to implement for Computer Science bachelors like myself, so
ultimately “why not?”
 Why PEAR(2)?
 PEAR is not a framework, but a collection of packages following a common
coding standard
 It’s a kind of “stamp of quality”, albeit no longer a widely recognized one
 Why is the current version a beta?
 For PEAR2, “beta” does NOT mean “error prone”
 It means “possible breaking changes in the next release; Review change logs carefully
when upgrading”
 Think of it as how Gmail was in beta for a long time.
06 Nov 2014"The better PHP API" by Vasil Rangelov
19
Thank you
06 Nov 2014"The better PHP API" by Vasil Rangelov
20
Question time

Contenu connexe

Tendances

Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
do_aki
 

Tendances (17)

Make your application expressive
Make your application expressiveMake your application expressive
Make your application expressive
 
Browser Serving Your We Application Security - ZendCon 2017
Browser Serving Your We Application Security - ZendCon 2017Browser Serving Your We Application Security - ZendCon 2017
Browser Serving Your We Application Security - ZendCon 2017
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
Securing Your Web Server
Securing Your Web ServerSecuring Your Web Server
Securing Your Web Server
 
How PHP works
How PHP works How PHP works
How PHP works
 
How to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI AttacksHow to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI Attacks
 
Php manish
Php manishPhp manish
Php manish
 
このPHP拡張がすごい!2017
このPHP拡張がすごい!2017このPHP拡張がすごい!2017
このPHP拡張がすごい!2017
 
Php advance
Php advancePhp advance
Php advance
 
MySQL Presentation
MySQL PresentationMySQL Presentation
MySQL Presentation
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 
LFI
LFILFI
LFI
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
 
php
phpphp
php
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Remote File Inclusion (RFI) Vulnerabilities 101
Remote File Inclusion (RFI) Vulnerabilities 101Remote File Inclusion (RFI) Vulnerabilities 101
Remote File Inclusion (RFI) Vulnerabilities 101
 

En vedette

[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
Amazon Web Services Japan
 

En vedette (11)

Mikrotik API
Mikrotik APIMikrotik API
Mikrotik API
 
PHP API
PHP APIPHP API
PHP API
 
20110611 Facebook Case Study
20110611 Facebook Case Study20110611 Facebook Case Study
20110611 Facebook Case Study
 
Wtf is API and SDK
Wtf is API and SDKWtf is API and SDK
Wtf is API and SDK
 
The future-of-netflix-api
The future-of-netflix-apiThe future-of-netflix-api
The future-of-netflix-api
 
PIXNET iOS SDK @OSDC 2014
PIXNET iOS SDK @OSDC 2014PIXNET iOS SDK @OSDC 2014
PIXNET iOS SDK @OSDC 2014
 
The Marketing Playbook for API & SDK Adoption
The Marketing Playbook for API & SDK AdoptionThe Marketing Playbook for API & SDK Adoption
The Marketing Playbook for API & SDK Adoption
 
API Strategy Evolution at Netflix
API Strategy Evolution at NetflixAPI Strategy Evolution at Netflix
API Strategy Evolution at Netflix
 
Writing code samples for API/SDK documentation
Writing code samples for API/SDK documentationWriting code samples for API/SDK documentation
Writing code samples for API/SDK documentation
 
[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
[AWSマイスターシリーズ] AWS SDK for PHP / Ruby / boto(Python) / JavaScript in Node.js
 
20170324 html5j web_paltform_study
20170324 html5j web_paltform_study20170324 html5j web_paltform_study
20170324 html5j web_paltform_study
 

Similaire à The better PHP API (EN)

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHP
vishnupriyapm4
 

Similaire à The better PHP API (EN) (20)

Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Php
PhpPhp
Php
 
PHP
PHPPHP
PHP
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
PEAR For The Masses
PEAR For The MassesPEAR For The Masses
PEAR For The Masses
 
Lamp Zend Security
Lamp Zend SecurityLamp Zend Security
Lamp Zend Security
 
Web Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptxWeb Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptx
 
PHP: Hypertext Preprocessor Introduction
PHP: Hypertext Preprocessor IntroductionPHP: Hypertext Preprocessor Introduction
PHP: Hypertext Preprocessor Introduction
 
PHP
PHPPHP
PHP
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Pywps a tutorial for beginners and developers
Pywps a tutorial for beginners and developersPywps a tutorial for beginners and developers
Pywps a tutorial for beginners and developers
 
php basics
php basicsphp basics
php basics
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHP
 
Integrating PHP With System-i using Web Services
Integrating PHP With System-i using Web ServicesIntegrating PHP With System-i using Web Services
Integrating PHP With System-i using Web Services
 
Scripting in OpenOffice.org
Scripting in OpenOffice.orgScripting in OpenOffice.org
Scripting in OpenOffice.org
 
Openshift Enterprise
Openshift EnterpriseOpenshift Enterprise
Openshift Enterprise
 
Apache Ppt
Apache PptApache Ppt
Apache Ppt
 

Dernier

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

The better PHP API (EN)

  • 1. The better PHP API (По-доброто PHP API) By Vasil Rangelov a.k.a. boen_robot
  • 2. What is this “API” thing?  In programming:  “Application Programming Interface” - A set of operations, their inputs and outputs, unified by common purpose, and available to the programmer.  In MikroTik RouterOS:  Layer7 client/server protocol (ala HTTP, FTP, SSH, etc.)  Intended for machines, not for humans  Rigid, structured and lacking “human” conveniences  To avoid confusion, the protocol will be referred to as “RouterOS API”. 06 Nov 2014"The better PHP API" by Vasil Rangelov 2
  • 3. What can it be used for?  Creating custom management UI  Integration of RouterOS with external applications, e.g.  Billing systems  Self-service applications  Monitoring tools  In a word: Automation. 06 Nov 2014"The better PHP API" by Vasil Rangelov 3
  • 4. SSH vs. RouterOS API  Both could be used for automation  SSH is intended for human use  “Cosmetic” changes from one RouterOS version to another can cause problems with automation tools  Renames/removal of commands/arguments/properties can cause not just hard to detect failures, but potential damages too  RouterOS API is intended for machine use  Only changes to the protocol itself could possibly cause issues  Easy to detect failures, and potential recovery without damages. 06 Nov 2014"The better PHP API" by Vasil Rangelov 4
  • 5. Languages with general purpose RouterOS API clients  PHP (3)  Java (2)  .NET (C# (3), VB.NET (1))  Python (2)  Node.js (1)  Perl (2)  Ruby (1)  Delphi (2)  C/C++ (4)  Erlang (1)  ActionScript (1) 06 Nov 2014"The better PHP API" by Vasil Rangelov 5
  • 6. Comparison of PHP RouterOS API clients 06 Nov 2014 6 "The better PHP API" by Vasil Rangelov Client API PHP class (Denis Basta) RouterOS PHP class (ayufan) API PHP package (boen_robot) Requires PHP version 5.2+ 5.2+ 5.3+ Raw protocol I/O Yes No Yes General purpose conveniences One method (comm()) No Set of classes CRUD and misc. conveniences No Yes Yes (1 class) Asynchronous requests No Callbacks only Yes Scripts No Pseudo Yes Persistent connections No No Yes Command line emulation No No Pseudo
  • 7. Preparing the target router for RouterOS API  For RouterOS earlier than v6.0, enable the protocol with  /ip service enable api  The protocol is enabled by default since RouterOS v6.0  The RouterOS user needs to have the “api” policy  Default user groups all have it; Take care when using custom groups  If using the firewall’s “input” or “output” chains, ensure incoming connections to TCP port 8728 are allowed, as are outgoing connections from TCP port 8728. 06 Nov 2014"The better PHP API" by Vasil Rangelov 7
  • 8. Preparing the client device for RouterOS API  Install everything needed to create and run programs in your language of choice  For PHP, this means installing the PHP interpreter itself, and perhaps plug it into a web server Easiest with all-in-one solutions like XAMPP: http://apachefriends.org/ For command line applications, PHP itself from http://php.net/ is enough  Allow all involved executables (“php” and maybe “httpd”) to make outgoing connections to TCP port 8728  For Windows, to get to the firewall, press Win+R, and run “wf.msc”. 06 Nov 2014"The better PHP API" by Vasil Rangelov 8
  • 9. First use of the PHP RouterOS package (quick way)  Download the PHAR file from https://pear2.github.io/Net_RouterOS/  Create a file in Apache’s “htdocs” folder called f.e. “rostest.php”, with the following contents: 06 Nov 2014"The better PHP API" by Vasil Rangelov 9 <?php use PEAR2NetRouterOS; require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar'; try { $client = new RouterOSClient('192.168.0.1', 'admin', 'password'); echo 'OK'; } catch (Exception $e) { die($e); }  Adjust the path to the “.phar” file, the RouterOS IP and credentials as needed  Open a web browser and run http://localhost/rostest.php.
  • 10. Alternative installation methods  Extract the TGZ or ZIP files from https://pear2.github.io/Net_RouterOS/  Include “src/PEAR2/Autoload.php”  Using Composer:  composer require pear2/net_routeros  Include “vendor/autoload.php”  Using PEAR:  pear channel-discover pear2.php.net  pear install -a pear2/PEAR2_Net_RouterOS-alpha  Include “PEAR2/Autoload.php”  Using Pyrus:  pyrus install -o PEAR2_Net_RouterOS-alpha  Include “PEAR2/Autoload.php”. 06.11.2014"The better PHP API" от Васил Рангелов 10
  • 11. Troubleshooting (step 1: environment issues)  Open up the command line  On Windows, Win+R, and run “cmd”  Start the PHAR file with PHP  Windows:  "D:pathtophp.exe" "D:pathtoPEAR2_Net_RouterOS.phar“  UNIX:  "/the/path/to/php" "/the/path/to/PEAR2_Net_RouterOS.phar“  Check the output for any warnings or errors  Note: For brevity, “php PEAR2_Net_RouterOS.phar” will be used in the following slides in place of full paths. Adjust accordingly. 06 Nov 2014"The better PHP API" by Vasil Rangelov 11
  • 12. Troubleshooting (step 2: connection issues)  Start the PHAR file with the router’s IP as an argument  php PEAR2_Net_RouterOS.phar 192.168.0.1  If using a different TCP port for the RouterOS API (e.g. 443):  php PEAR2_Net_RouterOS.phar -p 443 192.168.0.1  Check the output for any errors and possible solutions  All is OK if you get nothing, and are allowed to type Enter “/quit” (without the quotes), and press Enter twice to exit. 06 Nov 2014"The better PHP API" by Vasil Rangelov 12
  • 13. Troubleshooting (step 3: login issues)  Start the PHAR file with the RouterOS username and password added at the end, e.g.  php PEAR2_Net_RouterOS.phar 192.168.0.1 "admin" "password"  Check the output for any errors and possible solutions  All is OK if you get nothing, and are allowed to type Enter “/quit” (without the quotes), and press Enter twice to exit. 06 Nov 2014"The better PHP API" by Vasil Rangelov 13
  • 14. Example: Torch for 4 seconds 06 Nov 2014"The better PHP API" by Vasil Rangelov 14 <?php use PEAR2NetRouterOS; require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar'; $client = new RouterOSClient('192.168.0.1', 'admin', 'password'); header('Content-Type: text/plain'); $torchRequest = new RouterOSRequest('/tool torch duration=4'); $torchRequest->setArgument('interface', $_GET['nic']); foreach ($client->sendSync($torchRequest) as $response) { foreach ($response as $name => $value) { echo "{$name}: {$value}n"; } echo "====n"; }
  • 15. Example: Print RouterOS logs 06 Nov 2014"The better PHP API" by Vasil Rangelov 15 <?php use PEAR2NetRouterOS; require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar'; $client = new RouterOSClient('192.168.0.1', 'admin', 'password'); header('Content-Type: text/plain'); $util = new RouterOSUtil($client); foreach ($util->setMenu('/log')->getAll() as $item) { echo $item('time') . ' ' . $item('topics') . ' ' . $item('message') . "n"; }
  • 16. Example: Executing script with parameters 06 Nov 2014"The better PHP API" by Vasil Rangelov 16 <?php use PEAR2NetRouterOS; require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar'; $client = new RouterOSClient('192.168.0.1', 'admin', 'password'); header('Content-Type: text/plain'); $util = new RouterOSUtil($client); $util->exec(' /ip dhcp-client lease make-static [find address=$address] comment [find address=$address] $name /log info "User $name now has the static IP $address" ', array( 'name' => $_GET['user'], 'address' => $_GET['ip'] ) );
  • 17. Support  Documentation and more examples  GitHub wiki: https://github.com/pear2/Net_RouterOS/wiki  MikroTik wiki: http://wiki.mikrotik.com/wiki/API_PHP_package  Ask questions  MikroTik forum: http://forum.mikrotik.com/  Report bugs or request features for the client  GitHub issue tracker: https://github.com/pear2/Net_RouterOS/issues  Report bugs or request features for the protocol  MikroTik support: support@mikrotik.com. 06 Nov 2014"The better PHP API" by Vasil Rangelov 17
  • 18. Technical FAQ  Can I run a RouterOS API application on the router itself?  No  Can I log in hotspot users with the API protocol?  No. Not with the API protocol, not with SSH, not with Winbox even.  Hotspot users can ONLY be logged in when THEIR devices make an HTTP(S) request to the router with their credentials  What if my target router is behind NAT?  Solutions are same as those applicable for any TCP protocol  VPN?  What about encryption?  The API protocol has an TLS encrypted variant on port 8729  PEAR_Net_RouterOS supports it, but due to PHP problems, such connections are very unstable currently. 06 Nov 2014"The better PHP API" by Vasil Rangelov 18
  • 19. Social FAQ  Why make another PHP client?  I don’t like the other PHP clients  Also many of the non-PHP clients, but it’s better to have something than nothing, so…  The protocol is easy to implement for Computer Science bachelors like myself, so ultimately “why not?”  Why PEAR(2)?  PEAR is not a framework, but a collection of packages following a common coding standard  It’s a kind of “stamp of quality”, albeit no longer a widely recognized one  Why is the current version a beta?  For PEAR2, “beta” does NOT mean “error prone”  It means “possible breaking changes in the next release; Review change logs carefully when upgrading”  Think of it as how Gmail was in beta for a long time. 06 Nov 2014"The better PHP API" by Vasil Rangelov 19
  • 20. Thank you 06 Nov 2014"The better PHP API" by Vasil Rangelov 20 Question time