Giter Club home page Giter Club logo

tik4net's Introduction

tik4net

Unique complex mikrotik API communication solution.

The tik4net project provides easy to use API to connect and manage mikrotik routers via mikrotik API protocol. It has 3 parts:

  • Basic ADO.NET like API - to perform R/W access to mikrotik in both sync and async code (tik4net.dll).
  • O/R mapper like highlevel API with imported mikrotik strong-typed entities. (tik4net.objects.dll)
  • Tools - semi-automatic generators of custom entity C# code (for usage with tik4net.objects.dll)

Features

  • Easy to use with O/R mapper like highlevel API
  • Low level access supported by low level API
  • Stable interface and backward compatibility
  • Broad range of .NET runtimes supported (including .NET core 2 and Xamarin)
  • New mikrotik v.6.43 login process supported
  • Includes MNDP discovery helper
  • Easy to understand and well documented code

Binaries

Stable

In development (v 3.6)

  • Download as sources.

Getting started and documentation

Mikrotik API wiki:

Project wiki:

Examples:

   using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api_v2)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
   {
      connection.Open(HOST, USER, PASS);
   ITikCommand cmd = connection.CreateCommand("/system/identity/print");
   var identity = cmd.ExecuteScalar(); 
   Console.WriteLine("Identity: {0}", identity);
   var logs = connection.LoadList<Log>();
   foreach (Log log in logs)
   {
       Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
   }
   var firewallFilter = new FirewallFilter()
   {
      Chain = FirewallFilter.ChainType.Forward,
      Action = FirewallFilter.ActionType.Accept,
   };
   connection.Save(firewallFilter);
   ITikCommand torchCmd = connection.CreateCommand("/tool/torch", 
      connection.CreateParameter("interface", "ether1"), 
      connection.CreateParameter("port", "any"),
      connection.CreateParameter("src-address", "0.0.0.0/0"),
      connection.CreateParameter("dst-address", "0.0.0.0/0"));

  torchCmd.ExecuteAsync(response =>
      {
         Console.WriteLine("Row: " + response.GetResponseField("tx"));
      });
  Console.WriteLine("Press ENTER");
  Console.ReadLine();
  torchCmd.Cancel();

Looking for help

  • Importing other classes
  • Looking for betatesters

Roadmap & future

  • create highlevel classes for all mikrotik entities (you can still generate your own classes)
  • create tiklink project - easy use-to wrapper over mikrotik router with fluent API
  • convert examples to separate unittests (in progress)
  • create and contribute to tiktop (see linux iftop) project

REMARKS: This project is rewritten version of deprecated tik4net at googlecode (last version was 0.9.7.)

Licenses

  • Apache 2.0.

tik4net's People

Contributors

chbw avatar danikf avatar daveschmid avatar deantwo avatar dj3mu avatar h44z avatar hackerprod avatar lu-shaobin avatar mortengjesing avatar sebastienwarin avatar soerendd avatar techladsjamie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tik4net's Issues

Ease of use of commands

There are 2 things that I feel are must have to make a greater ease of use:

  1. tag parameter could be added to all commands - sync and async as one. This is because I use multiple synchronous commands at the same time across multiple threads and their results always clash.
  2. Async commands could launch an event on ApiDoneSentence arrival - so I could clean up easily without looping over command.IsRunning.

Could you do that? :)

No tag is attached to sent commands

Hello,

A tag is not attached to sent commands, which makes them take each others' responses as their own when sent in parallel.

I'm using a version of late 2017 and haven't seen a change in the latest version.

Mocking commands

I would really like to mock ITikConnection.Save and many other functions but they are implemented as extension methods. Is that really necessary? What are the reasons for implementing most of the library as extension methods?

how filter like dynamic

I use var list = Connection.LoadList<IpAddress>(Connection.CreateParameter("dynamic", null)); but it has not work ,can you help me

Added value is always 0

Hi,
Whenever I try to enter a value they are 0.
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/interface/ethernet/switch/mac-based-vlan/add","src-mac-address=11:22:33:44:55:66" "new-customer-vid", "15")

Any help?

I'm trying to create command as /PPP/Secret set ... but got replied message "no such command"

Hi danikf

At first I like to say thank you for developed this good api for managing routerOS very easily.
I have an issue as following, hope you can help me how to do.

I've created some accounts for VPN user accounts,I write some code for a function to disable ppp user account, I have test in terminal console in my routerOS as

ppp secret set [find name=[email protected]] disable=yes

It works fine after command executed in terminal console.

my c# code with tik4net command as bellow:

ITikCommand cmd = connection.CreateCommandAndParameters("/ppp/secret/set find[name=" + username + "] disable=yes"); cmd.ExecuteNonQuery();

the username is a variable for ppp user name that I want to disable with.

but the message be shown after execute command : no such command.

Do you have any idea to tell how to perform the command by CreateCommand() method ?

I really appreciate your instructions.

Albert Hsu

Lack of wireless channels and sniffer entities

Hi, the library could make a great use of entities for interface/wireless/channels and interface/wireless/sniffer.

Here are the entities I added locally to my work, hope I don't miss anything:

Channels:

using System;

namespace tik4net.Objects.Interface.Wireless
{
    [TikEntity("interface/wireless/channels", IsSingleton = false)]
    public class Channels
    {
        [TikProperty(".id", IsReadOnly = true)]
        public string Id {get; private set;}

        [TikProperty("list")]
        public String List {get; set;}

        [TikProperty("name")]
        public String Name {get; set;}

        [TikProperty("frequency")]
        public String Frequency {get; set;}

        [TikProperty("width")]
        public String Width {get; set;}

        [TikProperty("band")]
        public String Band {get; set;}

        [TikProperty("extension-channel", DefaultValue = "disabled")]
        public String ExtensionChannel {get; set;}
    }
}

Sniffer:

using System;

namespace tik4net.Objects.Interface.Wireless
{
    [TikEntity("interface/wireless/sniffer", IsSingleton = true)]
    public class Channels
    {
        [TikProperty(".id", IsReadOnly = true)]
        public string Id {get; private set;}

        [TikProperty("streaming-enabled", DefaultValue = "yes")]
        public bool StreamingEnabled {get; set;}

        [TikProperty("streaming-server")]
        public string StreamingServer {get; set;}

        [TikProperty("multiple-channels", DefaultValue = "yes")]
        public bool MultipleChannels {get; set;}

        [TikProperty("channel-time", DefaultValue = "")]
        public string ChannelTime {get; set;}
    }
}

ExecuteListWithDuration doesn't stop on disconnection

The following code:

var cmd = connection.CreateCommand("interface/wireless/sniffer/sniff")
cmd.AddParameter("interface", "wlan1");
cmd.ExecuteListWithDuration(9999);

Doesn't stop when I shut down my MikroTik board. A breakpoint inside ExecuteListWithDuration shows that Connection._isOpened == true.

I haven't tested other functions such as ExecuteAsync etc.

/system/reboot

The command system reboot frozen the thread waiting for response that not exists, is possible to make a Command without a response waiter?

ex: ExecuteNonWait

generate multiple hotspot user and show current TX and RX Rate

i wanna ask something , i have create an android application using this tools
here's the playstore link https://play.google.com/store/apps/details?id=com.meizoel.imikrotik

first question is how i can generate 20 user hotspot with random username and password
if have try two scenario using connection.save();
scenario one without sleep threed , i only create 5 user.
scenario two with sleep thread it up to 10 user , doesn't meet my requirment for create 20 user.
log message from both scenario are connection timeout, how to make it fill the requirment..

and second question how to show current TX Rate and RX Rate on list interface, hotspot active user and host

please help me

connection.LoadAsync<TEntity> throws

The following code:

...
connection.LoadAsync<WirelessAccessList>(
    (item) => { },
    (ex) => { }
);
...

Throws:

interface/wireless/access-list
MESSAGE: no such command

Am I using it wrong?

Support Xamarin For Android?

Hai i want ask , is it compatible for xamarin android ?

if not compatible , can you show or give me a tips for make it compatible for xamarin android

Dbii Networks interface

When I try to configure the red interface of Dbii Networks, an "unknown parameter" exception is thrown.
As much as I researched, this is because of the default-name parameter.

How can I remove it?

Rx o Tx of Interface

Goodnight

To obtain the Rx and Tx values ​​of the interface, in which way it is done, thank you in advance.

hreynaldoh

Encoding problem

I call the SSID field in the CapsManRegistrationTable through the API. Since the SSID contains Chinese characters, the displayed SSID result has an unrecognized question mark.

connection.Encoding = Encoding.GetEncoding("windows-1250");

Use connection.Encoding = Encoding.GetEncoding("windows-1250"); An error message appears: System.ArgumentException: 'windows-1250' is not a supported encoding name. For information on defining a custom encoding

Thank you so much!

FirewallFilter not able to use protocol=tcp

Hello,
if I want to add a new FirewallFilter with Protocol = tcp it throws the following exception:
---> tik4net.TikCommandException: failure: ports can be specified if proto is tcp,udp,udp-lite,dccp,sctp

my FirewallFilter Object: (serialized to Json)

  {
    "Action": 3,
    "Chain": "forward",
    "Comment": "test-tcp",
    "DstAddress": "8.8.8.8",
    "DstPort": "53",
    "Protocol": "tcp",
    "SrcAddress": "1.1.1.1",
    "SrcPort": "22",
  }

If Iam changing the Protocol from "tcp" to "udp" it will work.

I think the UnsetOnDefault is the Problem. I tried to set it to false but it doesn´t help.

[TikProperty("protocol", DefaultValue = "tcp", UnsetOnDefault = true)]

[Request] ExecuteListWithDuration return on !done and ExecuteListUntilDone

Attempting to make a simple synchronous traceroute, but none of the execute commands work, except for ExecuteListWithDuration.

I believe that calling the command /tool/traceroute address=8.8.8.8 count=1 would cause RouterOS to return a !done by itself without the need for a /cancel.

Do you think it would be possible to make ExecuteListWithDuration return when it it receive a !done?
And maybe a ExecuteListUntilDone would be interesting to have.

  • Change ExecuteListWithDuration to return when it receive !done
  • Add ExecuteListUntilDone, with optional timeout

NuGet package?

Could you create a nuget package for this project please?

[Request] Sub Exceptions of TikCommandException

I would love to see some special error cases moved into sub exceptions of TikCommandException.

For example login attempts could get its own sub exception.
So code like this would be easier to detect error types without reading the exception text.

try
{
    using (ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, host, user.UserName, user.Password))
    {
        ...
    }
}
catch (System.Net.Sockets.SocketException)
{
    // The socket could not conenct.
    throw;
}
catch (tik4net.TikCommandException)
{
    // Login failed.
    // Command failed.
    // Some other Tik4Net error.
    throw;
}

For example if you added a TikLoginException, we could do:

try
{
    using (ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, host, user.UserName, user.Password))
    {
        ...
    }
}
catch (System.Net.Sockets.SocketException)
{
    // The socket could not conenct.
    throw;
}
catch (tik4net.TikLoginException)
{
    // Login failed.
    throw;
}
catch (tik4net.TikCommandException)
{
    // Command failed.
    // Some other Tik4Net error.
    throw;
}

If you make in inherit from TikCommandException, it would supposedly not be a breaking change.

But if you don't mind a breaking change, for example for the next major update, you could go further and make a new root exception just called TikException, and make all other Tik3Net exceptions inherit from that.
And you could even wrap the System.Net.Sockets.SocketException from the socket in the TikConnectionException. But I don't know what best practice is for wrapping system exceptions.

Encoding Error

when i want to add a ip pool, use Chinese word like name=“北京” ,but it's result is "??" on the mikrotik ROS
var com = connection.CreateCommand("/ip/pool/add"); com.AddParameter("name", "北京"); com.AddParameter("ranges", "10.1.135.3");

Missing File

Just checked out the repo and tried to compile.
But i received an error.

In Project tik4net.objects the file /Ip/Dns/DnsCache.cs is missing.

Could you please provide the missing file?

Best Regards,
Sebastian

How to reset-counters

Hi there

I'm putting a tool in place that will help reset the download used in the user-manager. I'm using the query below from mikrotik's terminal and it works:
/tool user-manager user print where download-used >=1000000000;[/tool user-manager user reset-counters numbers=0]

I'm using the tik4net to accomplish this, unfortunately my codes aren't working. please see below and advise a work around:

connection.Open(ip, user, pwd);

            string[] str = new string[4];
            str[0] = ">download-used";
            str[1] = "1000000000;";
            str[2] = "/tool/user-manager/user/reset-counters/numbers";
            str[3] = txtreset.Text;
        
            
            ITikCommand cmd = connection.CreateCommandAndParameters("/tool/user- 
                                    manager/user/print", str); 

"System.ObjectDisposedException" in System.dll with Connection.LoadAsync<T>

Hey Daniel,

here I am again.
I found some time to play arround with tik4net.

I don't think I understand the code completly but it was enough to get the another Tool command running -
at least under special conditions.

Before I continoue - Thanks for your work. It gave me some great inspiration for another project.

Like told before I implemented MikroTik ping command, but I occured some trouble with an "System.ObjectDisposedException". It seams that the async call is not working, or I am missing something.

I created a little project, named tik4net.ping, which reproduces the behaviour on my fork of tik4net https://github.com/seho85/tik4net.git

When in the tik4net.ping project, in the file MainWindow.xaml.cs, in the method button_Click..., the non blocking delay loop is commented out the exception is thrown.

Maybe I am missing somethinh here, because I am not very familiar with async calls, but from my understanding of an async call it should work in my WPF example too.

Any help is appreciated.

Kinds regards,
Sebastian

[Suggestion] ExecuteScalarOrDefault

Same as with #58, cmd.ExecuteScalar() throws an exception when no result is found. It might be acceptable that it throws an exception when there are multiple results, rather than randomly return the first value in the sentence.

But a cmd.ExecuteScalarOrDefault() would be nice to have.

ExecuteListWithDuration causes memory leaks

I use ExecuteListWithDuration with a huge duration. The local variable results keeps all resentences and causes memory leaks. Can you add a parameter that allows dropping the results?

How To Arp Remove All (possible?)

I am adding in the arp table

Dim cmd As ITikCommand = connection.CreateCommand("/ip/arp/add", connection.CreateParameter("address", ip), ' connection.CreateParameter("interface", "ether1"), connection.CreateParameter("mac-address", mac), ' connection.CreateParameter("comment", nome)) cmd.ExecuteScalar()

How to send command /ip arp remove [find] to delete all the arp table

connection.Open timeout

you commit timeout at latest code, the code is useful when socket connect ok, but if the host can not be connected, connection.Open will never return in my test(2 minutes)

Terminal

Hi
I'm starting using this project for my network (ISP company) and it is so great, but now i want to create a mikrotik terminal inside my web, is that possible? and what tool should i use for that? i'm thinking to create a new script file and run it and remove it.

Exception Single response sentence expected

Hi,
I want to run scripts from the api but i get exception "Single response sentence expected" and my code is

ITikCommand scriptCmd = connection.CreateCommand( "/system/script/run", connection. CreateParameter("number", "0")); scriptCmd.ExecuteNonQuery();

Cancel command is not fully implemented

I was able to find the reason cancel command cancels simultaneous sniff commands:

https://wiki.mikrotik.com/wiki/Manual:API#.2Fcancel.2C_simultaneous_commands

It looks like you don't add the tag of the specific command correctly, and don't add a tag for the cancel command itself.

Let a sniff command use tag=5, for example, and a tag for cancel itself be 17.

It looks like you send:
/cancel.=.tag=5. where . is a placeholder for (0x07, 0x07, ., 0x00)
instead of:
/cancel.=tag=5..tag=17. where . is a placeholder for (0x07, 0x06, 0x06, ., 0x00)

Note the dot before the first tag, it is even written in remarks in CancelInternal.

From the link:
optional argument: =tag=tag of command to cancel, without it cancels all running commands

So I tried adding a new property to TikSpecialProperties:
private const string CancelTag = "=tag";
and add it as a second parameter to CancelInternal, something like this:

int tag = Interlocked.Increment(ref _tagCounter);

ApiCommand cancelCommand = new ApiCommand(_connection, "/cancel",
    new ApiCommandParameter(TikSpecialProperties.CancelTag, _runningTag.ToString()),
    new ApiCommandParameter(TikSpecialProperties.tag, tag.ToString()));

But now I'm stuck with:
/cancel.=tag=5.=.tag=17.
The third = shouldn't be there. It works perfectly if it isn't there - I can simultaneously sniff with 2 different interfaces and send a hard coded cancellation to one of them and the other keeps sniffing!

[Suggestion] ExecuteSingleRowOrDefault

We currently have cmd.ExecuteSingleRow() which is very useful. At least if you are expecting there to be a result, or don't mind adding a try-catch just to be sure there isn't no results.

I suggest a simple cmd.ExecuteSingleRowOrDefault(). Simply return null if no results were found.

not enough permissions (9)

Getting not enough permission (9) error message while executing the bellow usermanager command.

Help needed !!

ITikCommand activepro = connection.CreateCommand("/tool/user-manager/user/create-and-activate-profile",
            connection.CreateParameter("customer", "admin"),
            connection.CreateParameter("numbers", "udhay"),
            connection.CreateParameter("profile", "Quota5GV10d"));
            activepro = connection.CreateCommand(activate);
            var retmsg = activepro.ExecuteScalar();
           Console.WriteLine("Result: " +  retmsg);

Regards
Udhaya Moorthi

I can't remove the session using .id

Actually we have tried to remove the session manually by using the below command. I can fetch the id using /ip/hotspot/active/print. I tried so many times it shows the error "no such item (4). Kindly help me to resolve this issue.

ITikCommand RemoveSession = connection.CreateCommand("/ip/address/remove",
connection.CreateParameter(".id", id));
RemoveSession.ExecuteNonQuery();

Support RoMON connections

I'd like to have support for connecting to a Mikrotik device via RoMON to allow running API calls over a normally unroutable network. This would allow developers to develop a single controlling application rather than running multiple instances within routable network segments.

Problem with connection - Connection could not be opened.

Hello, how are you ?

I would first like to thank you for your beautiful work, you are helping me a lot with the management of the MKs.

I use the version made until Nov 12, 2017 and everything works fine, but when I upgrade to other versions the system stopped connecting, I noticed that changes were made to the OpenConnection async API (https://github.com/danikf/tik4net/commit) / 81f68f5 # [diff-6fe9fe2e4206c910a881330d5648084f)

Do you have any idea what that might be? I use exactly as in the examples, I tried to run in debug mode however it returns a generic error.

Sorry for my language, but I'm using Google Translate

Script source code

Hello!
here is a small bug when you try to get script content.
If script contains \r\n - regex doesn't work thinking that script source is multiline.
Here is my fix:
public ApiSentence(IEnumerable words)
{
Regex keyValueRegex = new Regex("^=?(?[^=]+)=(?.*)$", RegexOptions.Singleline);
foreach(string word in words)
{
...
}
}

Not work on ASP MVC5

It show that 'The type or namespace name 'tik4net' could not be found (are you missing a using directive or an assembly reference?)
Please help me. I use nuget package

GitHub Release Tags

Any chance I could get you to make release tags on the versions that are released as NuGets? It would make it a lot easier to find the source code for the current and previous NuGet versions.

You simply select the commit in https://github.com/danikf/tik4net/releases, give it a version name, and optionally write a description and/or changelog.
You can also upload and attach the complied .dll files to the release, no external hosting required.

If you need an example you can see how we do it on AsterNET.
Here: https://github.com/AsterNET/AsterNET/releases

Can't use .proplist

I am having trouble using the .proplist command parameter.

Allowing it to automatically detect the TikCommandParameterFormat seem, to make it fail and not return anything at all.

Example code:

ITikCommand cmd = conn.CreateCommand("/ip/address/print"
                                    ,conn.CreateParameter(".proplist", "address")
                                    ,conn.CreateParameter("interface", "bridge", TikCommandParameterFormat.Filter)
                                    ,conn.CreateParameter("disabled", "no", TikCommandParameterFormat.Filter)
                                    );
ITikSentence address = cmd.ExecuteSingleRow();

Nothing is returned at all.


I have dug into the source code a little to see why it isn't read correctly, and I think I have to set parameterFormat to TikCommandParameterFormat.Tag. But it doesn't work as I expected.

Example code:

ITikCommand cmd = conn.CreateCommand("/ip/address/print"
                                    ,conn.CreateParameter(".proplist", "address", TikCommandParameterFormat.Tag)
                                    ,conn.CreateParameter("interface", "bridge", TikCommandParameterFormat.Filter)
                                    ,conn.CreateParameter("disabled", "no", TikCommandParameterFormat.Filter)
                                    );
ITikSentence address = cmd.ExecuteSingleRow();

I am expecting only to get the address word, but I am still getting all the other properties from the router.


My old pure API program has it working fine like this:

_mikrotik.Send("/ip/address/print");
_mikrotik.Send("=.proplist=address");
_mikrotik.Send("?interface=bridge");
_mikrotik.Send("?disabled=no", true);
foreach (string h in _mikrotik.Read())

API-SSL

I don't see any support for connecting to the API via SSL. There is only Api, Ssh, and Telnet in your project right now.
You can take this as a feature request I guess?

The manual (here: Manual:API-SSL) says that it is available in RouterOS 6.1 and onward. While there isn't much information on it here, from my understanding it is mostly the TCP connection that needs to be setup differently, everything else is the same. (source)

Edit: Oh, just noticed it is already on your to-do list. Sorry.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.