danikf / tik4net Goto Github PK
View Code? Open in Web Editor NEWManage mikrotik routers with .NET C# code via ADO.NET like API or enjoy O/R mapper like highlevel api.
License: Apache License 2.0
Manage mikrotik routers with .NET C# code via ADO.NET like API or enjoy O/R mapper like highlevel api.
License: Apache License 2.0
From support forum:
Hi daniel
thanks for upgrade. its awesome!!
but i got some problem in InterfaceMonitorTraffic object. If i use this object to RB 750Gr3, it says "Missing Word with name rx-drops-per-second". but working excellent in RB951Ui-2nD.
and this SS of interface monitor on terminal were 750Gr3 not contains rx-drops-per-second
https://ibb.co/nyY9K9
what should i do?
thanks
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();
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)
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.
How can i change the connection timeout?
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
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
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
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.
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.
Goodnight
To obtain the Rx and Tx values of the interface, in which way it is done, thank you in advance.
hreynaldoh
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
I use var list = Connection.LoadList<IpAddress>(Connection.CreateParameter("dynamic", null));
but it has not work ,can you help me
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!
Could you please build a release for .net 4.6?
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?
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");
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();
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
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.
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.
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!
I have hosted mikrotik 5.20 on virtual box on a laptop. And when i want to access via code from my desktop i says exception ( No connection could be made because the target machine actively refused it 192.168.1.139:8728 ). But web fig on same desktop does work with 192.168.1.139:80
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?
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
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
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?
Currently the only way to determine how to use the object classes is to read the source code and tests.
Add another example on how to use the objects (eg loadall)
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
Could you create a nuget package for this project please?
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
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
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.
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.
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)
{
...
}
}
From mikrotik forum:
[admin@<HOST>] > /ip ipsec remote-peers print detail
Flags: R - responder, N - natt-peer
0 RN id="blah" local-address=X.X.X.X port=4500
remote-address=Y.Y.Y.Y port=59061 state=established
side=responder dynamic-address=172.29.58.92 uptime=46s last-seen=46s
Reason:
https://forum.mikrotik.com/viewtopic.php?f=9&t=99954&start=101#p691864
See duplicit port
fields.
Hi,
Mikrotik has changed the authentication process for API login in 6.43rc19 (2018-May-25 08:48).
Changelog: https://mikrotik.com/download/changelogs/release-candidate-release-tree
Wiki: https://wiki.mikrotik.com/wiki/Manual:API#Initial_login
many thanks in advance
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?
There are 2 things that I feel are must have to make a greater ease of use:
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.ApiDoneSentence
arrival - so I could clean up easily without looping over command.IsRunning
.Could you do that? :)
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.
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
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.
https://github.com/danikf/tik4net/blob/master/tik4net.objects/Interface/InterfaceWireless.cs#L801
should be "all-rates-fixed"
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.
ExecuteListWithDuration
to return when it receive !done
ExecuteListUntilDone
, with optional timeoutis there any way to connect to hotspot programmatically over the internet or over dynamic Ip.
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;}
}
}
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);
How to use ITikCommand with /tool wol interaface=ether1 mac=AA...
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())
The following code:
...
connection.LoadAsync<WirelessAccessList>(
(item) => { },
(ex) => { }
);
...
Throws:
interface/wireless/access-list
MESSAGE: no such command
Am I using it wrong?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.