# mikrotik-java
A Java client library implementation for the Mikrotik RouterOS API.
This project provides a Java client to manipulate Mikrotik routers using the remote API. Simple things must be easy to do, and complex things must be possible.
## Versions
![Java CI with Maven](https://github.com/GideonLeGrange/mikrotik-java/workflows/Java%20CI%20with%20Maven/badge.svg)
**The current stable version is 3.0.7**
Version 3.0.7 fixes nested expressions when constructing complex queries using `and` and `or` expressions. See [#72](https://github.com/GideonLeGrange/mikrotik-java/issues/72) for more information
### Changes in version 3.0:
Version 3.0 addresses the problems the API had around TLS encryption. The way secure connections are implemented is changed so that the user has complete control over the creation of TLS sockets. To this end:
* A new method, `connect(SocketFactory fact, String host, int port, int timeout)`, was added to allow for better user control over sockets and especially encryption.
* The `connectTLS()` API methods were removed.
* Most of the overloaded `connect()` methods were removed.
* Added a pre-built `jar` file to the downloads.
Further changes include:
* The previously deprecated `disconnect()` method is removed.
#### Versions 1.x and 2.x
Versions 1 and 2 are considered *obsolete* and will no longer be supported or patched.
## Getting the API
Maven users can use the artifact from Maven Central with this dependency:
```xml
<dependency>
<groupId>me.legrange</groupId>
<artifactId>mikrotik</artifactId>
<version>3.0.7</version>
</dependency>
```
You can also download the pre-built jar file, or a zip or tar.gz file with the source for the latest release [here](https://github.com/GideonLeGrange/mikrotik-java/releases/latest)
## Asking for help or contributing
I welcome contributions, be it bug fixes or other improvements.
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for information on how to contribute to this project.
# Using the API
How to use the API is best illustrated by examples.
These examples should illustrate how to use this library. Please note that I assume that the user is proficient in Java and understands the Mikrotik command line syntax. The command line syntax gives you an indication of what commands you can pass, but the RouterOS API used by this library does not support everyting.
Some things to consider when debugging your API calls are:
* The RouterOS API does not support auto-completion. You need to write out command and parameter names. For example, you can't say `/ip/hotspot/user/add name=john add=10.0.0.1`, you need to write out `address`.
* You need to quote values with spaces in. You can't say `name=Joe Blogs`, you need to use `name="Joe Blogs"`
* Exceptions with a root cause of `ApiCommandException` are errors received from the remote RouterOS device and contain the error message received.
## Opening a connection
Here is a simple example: Connect to a router and reboot it.
```java
ApiConnection con = ApiConnection.connect("10.0.1.1"); // connect to router
con.login("admin","password"); // log in to router
con.execute("/system/reboot"); // execute a command
con.close(); // disconnect from router
```
The above example shows a easy way of creating an unencrypted connection using the default API port and timeout, which is useful for development and testing.
### TLS encryption
For production environments, encrypting API traffic is recommended. To do this you need to open a TLS connection to the router by passing an instance of the `SocketFactory` you wish to use to construct the TLS socket to the API:
```java
ApiConnection con = ApiConnection.connect(SSLSocketFactory.getDefault(), "10.0.1.1", ApiConnection.DEFAULT_TLS_PORT, ApiConnection.DEFAULT_CONNECTION_TIMEOUT);
```
Above an instance of the default SSL socket factory is passed to the API. This will work as long as the router's certificate has been added to the local key store. Besides allowing the user to specify the socket factory, the above method also gives full control over the TCP Port and connection timeout.
RouterOS also supports anonymous TLS. An example showing how to create a socket factory for anonymous TLS is `AnonymousSocketFactory` in the examples directory.
### Connection timeouts
By default, the API will generate an exception if it cannot connect to the specified router. This can take place immediately (typically if the OS returns a 'Connection refused' error), but can also take up to 60 seconds if the router host is firewalled or if there are other network problems. This 60 seconds is the 'default connection timeout' an can be overridded by passing the preferred timeout to the APi as last parameter in a ```connect()``` call. For example:
```java
ApiConnection con = ApiConnection.connect(SSLSocketFactory.getDefault(), "10.0.1.1", ApiConnection.DEFAULT_TLS_PORT, 2000); // connect to router on the default API port and fail in 2 seconds
```
### Constants
Some constants are provided in `ApiConnection` to make it easier for users to construct connections with default ports and timeouts:
Constant | Use for | Value
---------|---------|------
DEFAULT_PORT | Default TCP `port` value for unencrypyted connections | 8728
DEFAULT_TLS_PORT | Default TCP `port` value for encrypyted connections | 8729
DEFAULT_CONNECTION_TIMEOUT | Default connection `timeout` value (ms) | 60000
### Try with resources
The API can also be used in a "try with resources" statement which will ensure that the connection is closed:
```java
try (ApiConnection con = ApiConnection.connect(SocketFactory.getDefault(), Config.HOST, ApiConnection.DEFAULT_PORT, 2000)) {
con.login(Config.USERNAME, Config.PASSWORD);
con.execute("/user/add name=eric");
}
```
In following examples the connection, login and disconnection code will not be repeated. In all cases it is assumed that an `ApiConnection` has been established, `login()` has been called, and that the connection is called `con`.
## Reading data
A simple example that returns a result - Print all interfaces:
```java
List<Map<String, String>> rs = con.execute("/interface/print");
for (Map<String,String> r : rs) {
System.out.println(r);
}
```
Results are returned as a list of maps of String key/value pairs. The reason for this is that a command can return multiple results, which have multpile variables. For example, to print the names of all the interfaces returned in the command above, do:
```java
for (Map<String, String> map : rs) {
System.out.println(map.get("name"));
}
```
### Filtering results
The same query, but with the results filtered: Print all interfaces of type 'vlan'.
```java
List<Map<String, String>> rs = con.execute("/interface/print where type=vlan");
```
### Selecting returned fields
The same query, but we only want certain result fields names: Print all interfaces of type 'vlan' and return just their name:
```java
List<Map<String, String>> rs = con.execute("/interface/print where type=vlan return name");
```
## Writing data
Creating, modifying and deleting configuration objects is of course possible.
### Creating an object
This example shows how to create a new GRE interface:
```java
con.execute("/interface/gre/add remote-address=192.168.1.1 name=gre1 keepalive=10");
```
### Modify an existing object
Change the IP address in the object created by the above example:
```java
con.execute("/interface/gre/set .id=gre1 remote-address=10.0.1.1");
```
### Remove an existing object
And now remove the object:
```java
con.execute("/interface/gre/remove .id=gre1");
```
### Un-setting a variable on an object
Un-setting a variable is a bit different, and you need to use a parameter called `value-name`. This isn't well documented. Let's say you have a firewall rule that was set up like this:
```java
con.execute("/ip/firewall/filter/add action=accept chain=forward time=00:00:01-01,mon")
```
Assuming th
没有合适的资源?快使用搜索试试~ 我知道了~
Mikrotik RouterOS API的Java客户端库实现
共42个文件
java:34个
md:3个
yml:2个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 136 浏览量
2022-06-30
16:33:47
上传
评论
收藏 43KB ZIP 举报
温馨提示
mikrotik-java Mikrotik RouterOS API的Java客户端库实现。 该项目提供了一个Java客户端,可以使用远程API来操纵Mikrotik路由器。 简单的事情必须容易做,而复杂的事情必须是可能的。 版本号 当前的稳定是3.0.7 3.0.7修复了使用and和or表达式构造复杂查询时的嵌套表达式。 有关更多信息,请参见 3.0中的更改: 3.0解决了API围绕TLS加密的问题。 更改了实现安全连接的方式,以便用户可以完全控制TLS套接字的创建。 为此: 添加了一个新方法connect(SocketFactory fact, String host, int port, int timeout) ,以允许用户更好地控制套接字,尤其是加密。 connectTLS() API方法已删除。 大多数重载的connect()方法都已删除。 在下载
资源推荐
资源详情
资源评论
收起资源包目录
1631585.zip (42个子文件)
333
mikrotik-java-master
.travis.yml 15B
pom.xml 5KB
.github
workflows
maven.yml 542B
LICENCE.md 9KB
CONTRIBUTING.md 3KB
src
main
java
me
legrange
mikrotik
grammar.txt 387B
ApiConnection.java 5KB
ResultListener.java 597B
MikrotikApiException.java 538B
ApiConnectionException.java 588B
impl
Parameter.java 685B
Error.java 694B
ParseException.java 421B
Command.java 2KB
Util.java 6KB
Parser.java 6KB
ApiCommandException.java 911B
Result.java 2KB
Done.java 343B
ApiDataException.java 401B
Scanner.java 5KB
ScanException.java 353B
Response.java 498B
ApiConnectionImpl.java 17KB
examples
ScriptCommand.java 1KB
AddAndModify.java 1KB
TryWithResources.java 716B
ConnectTLSAnonymous.java 2KB
AsyncWithErrorHandling.java 2KB
DownloadConfig.java 840B
SimpleCommandWithResults.java 717B
Config.java 272B
Example.java 499B
AsyncCommand.java 1KB
NestedExpressions.java 1KB
ConnectTLSCertificate.java 2KB
CharacterSets.java 2KB
SimpleCommand.java 541B
AnonymousSocketFactory.java 3KB
CommandWithWhere.java 707B
.gitignore 211B
README.md 10KB
共 42 条
- 1
资源评论
处处清欢
- 粉丝: 150
- 资源: 2471
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- Qt开发知识、经验总结 包括Qss,数据库,Excel,Model/View等
- IV数据.xlsx
- foldcraftlauncher_262944.apk
- 珍藏多年的基于matlab实现潮流计算程序源代码集合,包含多个潮流计算程序.rar
- 使用FPGA实现串-并型乘法器
- 基于matlab实现针对基于双曲线定位的DV-Hop算法中误差误差出一种基于加权双曲线定位的DV-Hop改进算法.rar
- 基于matlab实现由遗传算法开发的整数规划,车辆调度问题.rar
- 电视家7.0(对电视配置要求高).apk
- 免费计算机毕业设计-基于JavaEE的医院病历管理系统设计与实现(包含论文+源码)
- 手机端 我的世界融合植物大战僵尸版.apk
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功