It works fine after command executed in terminal console.ppp secret set [find name=username] disable=yes
ITikCommand cmd = connection.CreateCommandAndParameters("/ppp/secret/set find[name=" + username + "] disable=yes");
cmd.ExecuteNonQuery();
// Retrieve the secret.
ITikReSentence secret = conn.CreateCommandAndParameters("/ppp/secret/print", "name", username).ExecuteSingleRow();
// Disable the secret.
conn.CreateCommandAndParameters("/ppp/secret/set", ".id", secret.Words[".id"], "disabled", "true").ExecuteNonQuery();
// Retrieve pptp secrets.
IEnumerable<ITikReSentence> secrets = conn.CreateCommandAndParameters("/ppp/secret/print", "service", "pptp").ExecuteList();
foreach (var secret in secrets)
{
// Disable the secret.
conn.CreateCommandAndParameters("/ppp/secret/set", ".id", secret.Words[".id"], "disabled", "true").ExecuteNonQuery();
}
ITikCommand smsCmd = connection.CreateCommand("/tool/sms/send",
connection.CreateParameter("port", "usb3"),
connection.CreateParameter("channel", "3"),
connection.CreateParameter("phone-number", "00420777123456"), // or "dst" instead of "phone-number" - depends on tik version ???
connection.CreateParameter("message", "Test message.")
);
smsCmd.ExecuteNonQuery();
Imports tik4net
Imports tik4net.Objects
Imports tik4net.Objects.Ip.Firewall
Namespace Test
Public Class MyTest
Public Sub TestMikrotik()
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open(HOST, USER, PASS)
Dim cmd As ITikCommand = connection.CreateCommand("/system/identity/print")
Dim identity = cmd.ExecuteScalar()
Console.WriteLine("Identity: {0}", identity)
Dim logs = connection.LoadList(Of Log)()
For Each log As Log In logs
Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message)
Next
Dim fwf = New FirewallFilter() With { _
.Chain = FirewallFilter.ChainType.Forward, _
.Action = FirewallFilter.ActionType.Accept _
}
connection.Save(fwf)
End Using
End Sub
End Class
End Namespace
Imports tik4net
Imports tik4net.Objects
Namespace Test
Public Class MyTest
Public Sub TestMikrotik()
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open(HOST, USER, PASS)
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/print")
Dim results = cmd.ExecuteList()
For Each users In results
Console.WriteLine(users)
Next users
End Using
End Sub
End Class
End Namespace
/// <summary>
/// /ip/hotspot/profile/print:
/// </summary>
[TikEntity("/ip/hotspot/profile/print")]
public class ServerProfile
{
/// <summary>
/// .tag:
/// </summary>
[TikProperty(".tag")]
public long Tag { get; set; }
/// <summary>
/// .id:
/// </summary>
[TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
public string Id { get; private set; }
/// <summary>
/// name:
/// </summary>
[TikProperty("name", IsMandatory = true)]
public string Name { get; set; }
/// <summary>
/// hotspot-address:
/// </summary>
[TikProperty("hotspot-address")]
public string HotspotAddress { get; set; }
/// <summary>
/// html-directory:
/// </summary>
[TikProperty("html-directory")]
public string HtmlDirectory { get; set; }
/// <summary>
/// http-proxy:
/// </summary>
[TikProperty("http-proxy")]
public string HttpProxy { get; set; }
/// <summary>
/// smtp-server:
/// </summary>
[TikProperty("smtp-server")]
public string SmtpServer { get; set; }
/// <summary>
/// login-by:
/// </summary>
[TikProperty("login-by")]
public string LoginBy { get; set; }
/// <summary>
/// split-user-domain:
/// </summary>
[TikProperty("split-user-domain")]
public bool SplitUserDomain { get; set; }
/// <summary>
/// use-radius:
/// </summary>
[TikProperty("use-radius")]
public bool UseRadius { get; set; }
/// <summary>
/// default:
/// </summary>
[TikProperty("default")]
public bool Default { get; set; }
}
ITikCommand cmd = connection.CreateCommand("/ip/hotspot/profile/edit");
cmd.AddParameter(TikSpecialProperties.Id, "0");
cmd.AddParameter("name", "helloworld");
cmd.ExecuteNonQuery();
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/add", "customer", "admin", "username", "test007", "password", "12345678")
cmd.ExecuteNonQuery()
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/create-and-activate-profile", "", "test007", "profile", "Always", "customer", "admin")
cmd.ExecuteNonQuery()
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","14")
void Main()
{
using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "mypassword"))
{
var list = conn.LoadAll<PppActive>();
}
}
[TikEntity("/ppp/active", IncludeDetails = true)]
public class PppActive
{
[TikProperty(".id")]
public string Id { get; private set; }
[TikProperty("name")]
public string Name { get; private set; }
[TikProperty("service")]
public string Service { get; private set; }
[TikProperty("caller-id")]
public string CallerId { get; private set; }
[TikProperty("address")]
public string Address { get; private set; }
[TikProperty("uptime")]
public string Uptime { get; private set; }
[TikProperty("encoding")]
public string Encoding { get; private set; }
[TikProperty("session-id")]
public string SessionId { get; private set; }
[TikProperty("limit-bytes-in")]
public int LimitBytesIn { get; private set; }
[TikProperty("limit-bytes-out")]
public int LimitBytesOut { get; private set; }
[TikProperty("radius")]
public bool Radius { get; private set; }
}
private void button1_Click(object sender, EventArgs e)
{
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
connection.Open("192.168.77.xxx", "admin", "pass");
ITikCommand certcmd = connection.CreateCommand("/certificate/add",
connection.CreateParameter("name", "test"),
connection.CreateParameter("common-name", "test.com"),
connection.CreateParameter("key-size", "2048"),
connection.CreateParameter("key-usage", "crl-sign,key-cert-sign"),
connection.CreateParameter("days-valid", "365"));
certcmd.ExecuteAsync(response =>
{
Console.WriteLine(response.GetResponseField(""));
});
Console.WriteLine("Certificate created - press ENTER");
Console.ReadLine();
}
}
Hi I had same problem than and I solve deleteing the tik4net 3.10 unit on Visual Studio (Nuget) and installing 3.0.1 and works fine, for some errors maybe 3.10 the last at this moment have this error of timeout still no solve at least for me on Mikrotik 5.20, using Api port NOT ApiSSL port. I hope to help youFirst of all: Great work!
I just started to play around with tik4net and C#, but I got a little trouble.
If I use your examples and create a WindowsConsoleApplication everything works as it should. Problems are starting when I try to do the same within a WindowsFormApplication. I use exactly the same code and paste it within action for a button on a form:
If I run my application now, I got an "Exception not handled error" saying no connection possible.Code: Select allprivate void button1_Click(object sender, EventArgs e) { using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api)) { connection.Open("192.168.77.xxx", "admin", "pass"); ITikCommand certcmd = connection.CreateCommand("/certificate/add", connection.CreateParameter("name", "test"), connection.CreateParameter("common-name", "test.com"), connection.CreateParameter("key-size", "2048"), connection.CreateParameter("key-usage", "crl-sign,key-cert-sign"), connection.CreateParameter("days-valid", "365")); certcmd.ExecuteAsync(response => { Console.WriteLine(response.GetResponseField("")); }); Console.WriteLine("Certificate created - press ENTER"); Console.ReadLine(); } }
Guess I need some help here.
hiHi Danikf
how to perform command below?
/ip hotspot user profile delete [find name=BLABLABLA]
its work perfectly in terminal, but when i am use it in vb.net, it says " no such command"
I really appreciate your instructions
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open(Form2.HostTB.Text, Form2.LoginTB.Text, Form2.PassTB.Text)
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/ip/hotspot/user/profile/remove")
cmd.AddParameter(TikSpecialProperties.Id, CBdelprof.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Profile Deleted")
/ip hotspot user print count-only where comment=expired.user
connection.LoadAll<UserProfile>().Where(u=>u.Comment="expired.user").Count();
connection.Open(HOST, PORT, USER, PASS);
Answer:To obtain the Rx and Tx values of the interface, in which way it is done, thank you in advance.
var ethIface = Connection.LoadSingle<Interface>(Connection.CreateParameter("name", "ether1"));
var rx = ethIface.RxByte;
Rx o Tx in real time of each interfcace not RxByte of interface?Question (posted as Github issue):Answer:To obtain the Rx and Tx values of the interface, in which way it is done, thank you in advance.
DCode: Select allvar ethIface = Connection.LoadSingle<Interface>(Connection.CreateParameter("name", "ether1")); var rx = ethIface.RxByte;
/// <summary>
/// Gets snapshot of actual traffic RX/TX values for given <paramref name="interfaceName"/>.
/// </summary>
public static InterfaceMonitorTraffic GetInterfaceMonitorTrafficSnapshot(ITikConnection connection, string interfaceName)
{
var cmd = connection.CreateCommand("/interface/monitor-traffic",
connection.CreateParameter("interface", interfaceName, TikCommandParameterFormat.NameValue),
connection.CreateParameter("once", "", TikCommandParameterFormat.NameValue));
var result = cmd.LoadList<InterfaceMonitorTraffic>().Single();
return result;
}
/// <summary>
/// /interface/monitor-traffic
/// NOTE: use <see cref="InterfaceMonitorTraffic.GetSnapshot"/> or with some kind of bulk/async load
/// </summary>
[TikEntity("/interface", IncludeDetails = true, IsReadOnly = true)]
public class InterfaceMonitorTraffic
{
/// <summary>
/// name
/// </summary>
[TikProperty("name", IsMandatory = true, IsReadOnly = true)]
public string Name { get; private set; }
/// <summary>
/// rx-packets-per-second
/// </summary>
[TikProperty("rx-packets-per-second", IsMandatory = true, IsReadOnly = true)]
public string RxPacketsPerSecond { get; private set; }
/// <summary>
/// rx-bits-per-second
/// </summary>
[TikProperty("rx-bits-per-second", IsMandatory = true, IsReadOnly = true)]
public string RxBitsPerSecond { get; private set; }
/// <summary>
/// rx-drops-per-second
/// </summary>
[TikProperty("rx-drops-per-second", IsMandatory = true, IsReadOnly = true)]
public string RxSropsPerSecond { get; private set; }
/// <summary>
/// rx-errors-per-second
/// </summary>
[TikProperty("rx-errors-per-second", IsMandatory = true, IsReadOnly = true)]
public string RxErrorsPerSecond { get; private set; }
/// <summary>
/// tx-packets-per-second
/// </summary>
[TikProperty("tx-packets-per-second", IsMandatory = true, IsReadOnly = true)]
public string TxPacketsPerSecond { get; private set; }
/// <summary>
/// tx-bits-per-second
/// </summary>
[TikProperty("tx-bits-per-second", IsMandatory = true, IsReadOnly = true)]
public string TxBitsPerSecond { get; private set; }
/// <summary>
/// tx-drops-per-second
/// </summary>
[TikProperty("tx-drops-per-second", IsMandatory = true, IsReadOnly = true)]
public string TxSropsPerSecond { get; private set; }
/// <summary>
/// tx-errors-per-second
/// </summary>
[TikProperty("tx-errors-per-second", IsMandatory = true, IsReadOnly = true)]
public string TxErrorsPerSecond { get; private set; }
}
connection.LoadList(Of HotspotUser)()
thank you !!!!Hi,
it will be part of the next release.
https://github.com/danikf/tik4net/commi ... 15b5f67ddf
Enjoy,
D
PS: see this tutorial for custom objects:
https://github.com/danikf/tik4net/wiki/ ... m-entities
https://github.com/danikf/tik4net/wiki/ ... -API-tools
var user = new HotspotUser()
{
Name = "TEST",
LimitUptime = "1:00:00",
Password = "secretpass"
};
_connection.Save(user);
great update!! thank you daniel.Version 3.4. released.
https://github.com/danikf/tik4net/releases/tag/v3.4
Whats new:
tool/traceroute entity + helpers
tool/ping helpers
Command.ExecuteWithDuration fix
InterfaceMonitorTraffic fix
D
ITikCommand printcmd = connection.CreateCommand("/ip/ipsec/remote-peer/print");
IEnumerable<ITikReSentence> userlist = printcmd.ExecuteList();
Hi,now i have a small request.
can you add ip bindings object?
Hi,When you reset no default the Mikrotik router(951Ui), it IP will become "0.0.0.0".
So there is no other way for me to configure the router via MAC address.
First line of the exception talks about 4500 vs 59061Unhandled Exception: tik4net.TikSentenceException: Duplicit key 'port' with deffirent values '4500' vs. '59061'
at tik4net.Api.ApiSentence..ctor(IEnumerable`1 words)
at tik4net.Api.ApiConnection.ReadSentence()
at tik4net.Api.ApiConnection.GetOne(String tag)
at tik4net.Api.ApiConnection.<GetAll>d__60.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at tik4net.Api.ApiConnection.CallCommandSync(String[] commandRows)
at tik4net.Api.ApiCommand.ExecuteSingleRow()
Now, What I'm wondering is.. why on earth would this cause exception such as above?[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
Now, I don't think I can do anything about Android phone using different remote port so how should I handle this case from the code?[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=4500 state=established side=responder
uptime=7m20s last-seen=1m19s
ITikReSentence id = connection.CreateCommandAndParameters("/ip/ipsec/remote-peers/print", "id", username).ExecuteSingleRow();
Hi,BTW, Is there document on how to go about using the dev version?
Would this be possible with nuget?
/ip firewall filter
add chain=input dst-port=8728 in-interface-list=LAN protocol=tcp src-address=192.168.88.0/24
ip bindings fromHi,now i have a small request.
can you add ip bindings object?
what are you meaning by "ip binding object". Is it different from IpAddress object?
D
Hello! Thank you very much, all is working fine! Have a nice day!Is your mikrotik router properly configured? Which version of routeros do you use?
https://github.com/danikf/tik4net/wiki/SSL-connection
D
Here you are (and also commited in dev branch).ip bindings from
ip/hotspot/ip-binding
namespace tik4net.Objects.Ip.Hotspot
{
/// <summary>
/// ip/hotspot/ip-binding
///
/// IP-Binding HotSpot menu allows to setup static One-to-One NAT translations, allows to bypass specific HotSpot clients without any authentication, and also allows to block specific hosts and subnets from HotSpot network
/// </summary>
[TikEntity("ip/hotspot/ip-binding")]
public class HotspotIpBinding
{
/// <summary>
/// .id: primary key of row
/// </summary>
[TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
public string Id { get; private set; }
/// <summary>
/// address: The original IP address of the client
/// </summary>
[TikProperty("address", DefaultValue = "")]
public string/*IP Range*/ Address { get; set; }
/// <summary>
/// mac-address: MAC address of the client
/// </summary>
[TikProperty("mac-address", DefaultValue = "")]
public string/*MAC*/ MacAddress { get; set; }
/// <summary>
/// server
/// Name of the HotSpot server.
/// all - will be applied to all hotspot servers
/// </summary>
[TikProperty("server", DefaultValue = "all")]
public string/*string | all*/ Server { get; set; }
/// <summary>
/// to-address: New IP address of the client, translation occurs on the router (client does not know anything about the translation)
/// </summary>
[TikProperty("to-address", DefaultValue = "")]
public string/*IP*/ ToAddress { get; set; }
/// <summary>
/// type
/// Type of the IP-binding action
/// regular - performs One-to-One NAT according to the rule, translates address to to-address
/// bypassed - performs the translation, but excludes client from login to the HotSpot
/// blocked - translation is not performed and packets from host are dropped
/// </summary>
[TikProperty("type", DefaultValue = "")]
public string/*blocked | bypassed | regular*/ Type { get; set; }
}
}
interactive command examples that will not work in API are:
/system telnet
/system ssh
/tool mac-telnet
Hi,Sorry, this is an unsupported feature:
I saw also some sample bash script (from some mikrotik guy) which uses ssh to neighbour machine to perform changes on another machine via RoMon/mactelnet internal feature (but I cant find it anymore).Janisk (from mikrotik) citation: everything that looks suspiciously interactive, like ssh login or telnet login will not work if ran from scheduler or script.
var profile = vResult.GetResponseFieldOrDefault("actual-profile", "(none)");
if (vResult.Words.ContainsKey("actual-profile"))
{
// Do something
}
/interface ethernet monitor ether3 once
name: eth3-AP-AC-45
status: link-ok
auto-negotiation: done
rate: 1Gbps
full-duplex: yes
tx-flow-control: no
rx-flow-control: no
advertising: 10M-half,10M-full,100M-half,100M-full,1000M-half,1000M-full
link-partner-advertising: 10M-half,10M-full,100M-half,100M-full,1000M-half,1000M-full
Here you are (also commited to DEV branch).Hi all,
I would need to get the real "speed rate" of an ethernet interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tik4net.Objects.Interface.Ethernet
{
/// <summary>
/// /interface ethernet monitor: command prints out current link, rate and duplex status of an interface.
/// </summary>
[TikEntity("/interface/ethernet/monitor", LoadCommand = "", LoadDefaultParameneterFormat = TikCommandParameterFormat.NameValue, IncludeDetails = false, IsReadOnly = true)]
public class EthernetMonitor
{
/// <summary>
/// name
/// </summary>
[TikProperty("name", IsMandatory = true, IsReadOnly = true)]
public string Name { get; private set; }
/// <summary>
/// auto-negotiation
/// Current auto negotiation status:
/// done - negotiation completed
/// incomplete - negotiation failed or not yet completed
/// </summary>
[TikProperty("auto-negotiation")]
public string/*done | incomplete*/ AutoNegotiation { get; set; }
/// <summary>
/// default-cable-settings
/// Default cable length setting (only applicable to NS DP83815/6 cards)
/// short - support short cables
/// standard - support standard cables
/// </summary>
[TikProperty("default-cable-settings")]
public string/*short | standard*/ DefaultCableSettings { get; set; }
/// <summary>
/// full-duplex: Whether transmission of data occurs in two directions simultaneously
/// </summary>
[TikProperty("full-duplex")]
public bool FullDuplex { get; set; }
/// <summary>
/// rate: Actual data rate of the connection.
/// </summary>
[TikProperty("rate")]
public string/*10Mbps | 100Mbps | 1Gbps*/ Rate { get; set; }
/// <summary>
/// status
/// Current link status of an interface
/// link-ok - the card is connected to the network
/// no-link - the card is not connected to the network
/// unknown - the connection is not recognized (if the card does not report connection status)
/// </summary>
[TikProperty("status")]
public string/*link-ok | no-link | unknown*/ Status { get; set; }
/// <summary>
/// tx-flow-control: Whether TX flow control is used
/// </summary>
[TikProperty("tx-flow-control")]
public string TxFlowControl { get; set; }
/// <summary>
/// rx-flow-control: Whether RX flow control is used
/// </summary>
[TikProperty("rx-flow-control")]
public string RxFlowControl { get; set; }
/// <summary>
/// sfp-module-present: Whether SFP module is in cage
/// </summary>
[TikProperty("sfp-module-present")]
public bool SfpModulePresent { get; set; }
/// <summary>
/// sfp-rx-lose:
/// </summary>
[TikProperty("sfp-rx-lose")]
public bool SfpRxLose { get; set; }
/// <summary>
/// sfp-tx-fault:
/// </summary>
[TikProperty("sfp-tx-fault")]
public bool SfpTxFault { get; set; }
/// <summary>
/// sfp-connector-type:
/// </summary>
[TikProperty("sfp-connector-type")]
public string SfpConnectorType { get; set; }
/// <summary>
/// sfp-link-length-copper: Detected link length when copper SFP module is used
/// </summary>
[TikProperty("sfp-link-length-copper")]
public string SfpLinkLengthCopper { get; set; }
/// <summary>
/// sfp-vendor-name: Vendor of the SFP module
/// </summary>
[TikProperty("sfp-vendor-name")]
public string SfpVendorName { get; set; }
/// <summary>
/// sfp-vendor-part-number: SFP module part number
/// </summary>
[TikProperty("sfp-vendor-part-number")]
public string SfpVendorPartNumber { get; set; }
/// <summary>
/// sfp-vendor-revision: SFP module revision number
/// </summary>
[TikProperty("sfp-vendor-revision")]
public string SfpVendorRevision { get; set; }
/// <summary>
/// sfp-vendor-serial: SFP module serial number
/// </summary>
[TikProperty("sfp-vendor-serial")]
public string SfpVendorSerial { get; set; }
/// <summary>
/// sfp-manufacturing-date: SFP module manufacturing date
/// </summary>
[TikProperty("sfp-manufacturing-date")]
public string SfpManufacturingDate { get; set; }
/// <summary>
/// eeprom: EEPROM of an SFP module
/// </summary>
[TikProperty("eeprom")]
public string Eeprom { get; set; }
/// <summary>
/// Gets snapshot of actual values for given <paramref name="interfaceName"/>.
/// </summary>
public static EthernetMonitor GetSnapshot(ITikConnection connection, string interfaceName)
{
return EthernetMonitorConnectionExtensions.GetEthernetMonitorSnapshot(connection, interfaceName);
}
}
/// <summary>
/// Connection extension class for <see cref="InterfaceMonitorTraffic"/>
/// </summary>
public static class EthernetMonitorConnectionExtensions
{
/// <summary>
/// Gets snapshot of actual values for given <paramref name="interfaceName"/>.
/// </summary>
public static EthernetMonitor GetEthernetMonitorSnapshot(this ITikConnection connection, string interfaceName)
{
var result = connection.LoadSingle<EthernetMonitor>(
connection.CreateParameter("numbers", interfaceName, TikCommandParameterFormat.NameValue),
connection.CreateParameter("once", "", TikCommandParameterFormat.NameValue));
return result;
}
}
}
Thank you very much Danikf!Here you are (also commited to DEV branch).Hi all,
I would need to get the real "speed rate" of an ethernet interface.
D
/interface print detail
name="eth10-myName" default-name="ether10" type="ether" mtu=1500
actual-mtu=1500 l2mtu=1598 max-l2mtu=9498 mac-address=D4:CA:6D:CC:BB:AA
last-link-down-time=nov/30/2018 17:25:50
last-link-up-time=nov/30/2018 17:25:51 link-downs=1
[TikProperty("last-link-down-time")]
public string LastLinkDownTime { get; set; }
[TikProperty("last-link-up-time")]
public string LastLinkUpTime { get; set; }
Hi,Does anyone knows why the ConnectionBytes property of a FirewallFilter object always returns 0?
/// <summary>
/// Statistics - bytes
/// </summary>
[TikProperty("bytes", IsReadOnly = true)]
public long Bytes { get; private set; }
/// <summary>
/// Statistics - packets
/// </summary>
[TikProperty("packets", IsReadOnly = true)]
public long Packets { get; private set; }
Thanks - added to code base. Will be part ot the next release.Yes, just take a copy of https://github.com/danikf/tik4net/blob/ ... terface.cs and include the properties:
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open("10.0.1.207", "admin", "12345")
Dim smsCmd As ITikCommand = connection.CreateCommand("/tool/sms/send",
connection.CreateParameter("port", "lte"),
connection.CreateParameter("phone-number", "5694341XXXX"),
connection.CreateParameter("message", "Test message." & dateTime.now().toString()))
smsCmd.ExecuteNonQuery()
End using
Hi,
probably yes - in general. You can perform every operation which you can script in mikrotik API I don't have GSM modem connected to mikrotik so I can't test it.
The code could be (not tested):SMS documentation (warning - it is documentation for console, not for API - syntax will be a little bit different):Code: Select allITikCommand smsCmd = connection.CreateCommand("/tool/sms/send", connection.CreateParameter("port", "usb3"), connection.CreateParameter("channel", "3"), connection.CreateParameter("phone-number", "00420777123456"), // or "dst" instead of "phone-number" - depends on tik version ??? connection.CreateParameter("message", "Test message.") ); smsCmd.ExecuteNonQuery();
http://wiki.mikrotik.com/wiki/Manual:Tools/Sms
Other usefull links:
https://aacable.wordpress.com/2012/11/2 ... gsm-modem/
http://forum.mikrotik.com/viewtopic.php ... it=sms+api
Remarks: you have to install advanced-tools package and have gsm modem connected to mikrotik.
Let me know if it works,
D
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open("10.0.1.207", "admin", "12345")
Dim smsCmd As ITikCommand =
connection.CreateCommandAndParameters(
"/tool/sms/send",
TikCommandParameterFormat.NameValue,
"port", "lte",
"phone-number", "5694341XXXX",
"message", "Test message." & DateTime.Now.ToString())
smsCmd.ExecuteSingleRow()
End Using
The API returns a result which is not expected by ExecuteNonQuery.
Try this instead, ExecuteSingleRows assumes parameters are query words by default so you'll have to supply parameterformat NameValue:
Code: Select allUsing connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api) connection.Open("10.0.1.207", "admin", "12345") Dim smsCmd As ITikCommand = connection.CreateCommandAndParameters( "/tool/sms/send", TikCommandParameterFormat.NameValue, "port", "lte", "phone-number", "5694341XXXX", "message", "Test message." & DateTime.Now.ToString()) smsCmd.ExecuteSingleRow() End Using
/tool sms inbox remove [find]
ITikCommand cmd = connection.CreateCommand("/tool/sms/inbox/remove");
connection.CreateParameter("numbers", "[find]");
cmd.ExecuteNonQuery();
ITikCommand cmd = connection.CreateCommand("/tool/sms/inbox/remove [find]");
cmd.ExecuteNonQuery();
using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", ""))
{
var list =
conn.CreateCommandAndParameters(
"/tool/sms/inbox/print",
TikCommandParameterFormat.NameValue,
".proplist", ".id"
).ExecuteList();
foreach (var item in list)
{
conn.CreateCommandAndParameters(
"/tool/sms/inbox/remove",
".id", item.Words[".id"]
).ExecuteNonQuery();
}
}
void Main()
{
using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", ""))
{
conn.DeleteAll<ToolSmsInbox>();
}
}
[TikEntity("/tool/sms/inbox")]
public class ToolSmsInbox
{
[TikProperty(".id")]
public string Id { get; private set; }
[TikProperty("phone")]
public string Phone { get; private set; }
[TikProperty("type")]
public string Type { get; private set; }
[TikProperty("timestamp")]
public string Timestamp { get; private set; }
[TikProperty("message")]
public string Message { get; private set; }
}
What's new in 6.45.2 (2019-Jul-17 10:04):
Important note!!!
Due to removal of compatibility with old version passwords in this version, downgrading to any version prior to v6.43 (v6.42.12 and older) will clear all user passwords and allow password-less authentication. Please secure your router after downgrading.
Old API authentication method will also no longer work, see documentation for new login procedure:
https://wiki.mikrotik.com/wiki/Manual:API#Initial_login
using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", "admin", ""))
{
var cmd = conn.CreateCommand("/system/identity/print");
var result = cmd.ExecuteSingleRow();
Console.WriteLine(result.Words["name"]);
}
Code: Select all
string[] command = new string[] { @"{\r\ \n/system identity set name=" + _siteName + @"\r\ "
+ @"\n/ip pool set [find name=default-dhcp] ranges=" + _ipAddress + @".101-" + _ipAddress + @".254\r\ "
+ @"\n/ip dhcp-server network set [find comment=\""default configuration\""] address=" + _ipAddress + @".0/24 gateway=" + _ipAddress + @".1 ntp-server=10.9.0.1," + _ipAddress + @".1\r\ "
+ @"\n/interface sstp-client set [find name=sstp-manage] password=" + _managePassword + @" user=" + _manageLogin + @"\r\ "
+ @"\n/interface sstp-client set [find name=vpn-out] password=" + _vpnPassword + @" user=" + _vpnLogin + @"\r\ "
+ @"\n/ip address set [find comment=\""LAN Address\""] address=" + _ipAddress + @".1/24 network=" + _ipAddress + @".0\r\ "
+ @"\n}"
};
only work until ROS 6.45.2Use TikConnectionType.Api_v2:
Code: Select allusing (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", "admin", "")) { var cmd = conn.CreateCommand("/system/identity/print"); var result = cmd.ExecuteSingleRow(); Console.WriteLine(result.Words["name"]); }
Tested (and works OK) with my v6.45.6 RB493 (at least SSL version).only work until ROS 6.45.2
doesn't work for ROS above 6.45.2
/interface pppoe-server remove [find user=ex]
using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", 8728, "admin", ""))
{
var command = conn.CreateCommand("/interface/pppoe-server/print");
command.AddParameter(".proplist", ".id", TikCommandParameterFormat.NameValue);
command.AddParameterAndValues("user", "ex");
var list = command.ExecuteList();
foreach (var item in list)
{
conn.CreateCommandAndParameters(
"/interface/pppoe-server/remove",
".id", item.Words[".id"]
).ExecuteNonQuery();
}
}
void Main()
{
using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", 8728, "admin", ""))
{
var list = conn.LoadList<PppoeServer>(conn.CreateParameter("user", "ex"));
foreach (var item in list)
{
conn.Delete(item);
}
}
}
[TikEntity("/interface/pppoe-server")]
public class PppoeServer
{
[TikProperty(".id")]
public string Id { get; set; }
[TikProperty("user")]
public string User { get;set;}
}
Hi,Code: Select all/interface pppoe-server remove [find user=ex]
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api_v2)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
{
connection.Open(HOST, USER, PASS);
protected void Login_Click(object sender, EventArgs e)
{
try
{
// Using Tik4Net connecion to Login
ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, TextBox1.Text, TextBox2.Text, TextBox3.Text);
// Now creating command string
ITikCommand cmd = connection.CreateCommand("/system/identity/print");
// Execute the command and add it in a string
string identity = cmd.ExecuteScalar();
// Print it on Website
//Response.Write("Identity: " + identity);
Mess.ForeColor = System.Drawing.Color.Green;
Mess.Text = "Identity :" + identity;
} catch(Exception ex )
{
//Response.Write("Exception : " + ex.Message);
Mess.ForeColor = System.Drawing.Color.Red;
Mess.Text = ex.Message;
}
}
}
protected void Login_Click(object sender, EventArgs e)
{
try
{
// Using Tik4Net connecion to Login
ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, TextBox1.Text, TextBox2.Text, TextBox3.Text);
// Now creating command string
ITikCommand cmd = connection.CreateCommand("/system/identity/print");
// Execute the command and add it in a string
string identity = cmd.ExecuteScalar();
// Print it on Website
//Response.Write("Identity: " + identity);
Mess.ForeColor = System.Drawing.Color.Green;
Mess.Text = "Identity :" + identity;
} catch(Exception ex )
{
//Response.Write("Exception : " + ex.Message);
Mess.ForeColor = System.Drawing.Color.Red;
Mess.Text = ex.Message;
}
}
}
Dim connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, IP, u, p)
Dim loadCmd = connection.CreateCommandAndParameters("/interface/lte/info", "number", "0", "once", "")
Dim response = loadCmd.ExecuteList()
Hi.Hi everybody,
after more than one year - there is new version of tik4net.
Details:
https://github.com/danikf/tik4net/wiki/History
In hope it will be usefull,
D
Sorry to say that, but this type of question is out of the scope of the API support ... This API provides C# way to communication with mikrotik.Hi.
I have a question.
I want to create a custom login page and the users can login with facebook api. the user log must save in db and admin can manage the users.
Can i do this with your library or a bit customization?
Thanks a lot.
Hi,Hi,
I've started playing with this library and have found that I am unable to retrieve the LTE info from the router.
I am using the following code to try and get information.
We have a working version for php to get the LTE info, but this will have to be ported to a vb.net application.Code: Select allDim connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, IP, u, p) Dim loadCmd = connection.CreateCommandAndParameters("/interface/lte/info", "number", "0", "once", "") Dim response = loadCmd.ExecuteList()
Not sure if I am doing something wrong, or perhaps something else I am missing?
ITikCommand monitor = connection.CreateCommandAndParameters("/interface/ethernet/monitor", "interface", "ether3");
monitor.ExecuteAsync(re => responses.Add(re));
System.Threading.Thread.Sleep(5000);
monitor.CancelAndJoin();
monitor = connection.CreateCommandAndParameters("/interface/monitor-traffic", "interface", "ether3");
monitor.ExecuteAsync(re => responses.Add(re));
This does not give me nay responses.
monitor.ExecuteAsync(
re => responses.Add(re),
e => Console.WriteLine(e.ToString()));
ITikCommand monitor = conn.CreateCommandAndParameters("/interface/ethernet/monitor", ".id", "ether3");
EthernetMonitor em = EthernetMonitor.GetSnapshot(connection, "ether3");
string linkspeed = em.Rate;
using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "password"))
{
conn.CreateCommandAndParameters("/ip/ipsec/peer/disable", ".id", "peer-A").ExecuteNonQuery();
conn.CreateCommandAndParameters("/ip/ipsec/peer/enable", ".id", "peer-A").ExecuteNonQuery();
}
var firewallconnection = connection.LoadList<FirewallConnection>();
foreach (var item in firewallconnection )
{
if (item.SrcAddress.Contains("192.168.1.101"))
{
connection.Delete<FirewallConnection>(item);
}
}
can i get an example?You can create multiple clients in a single program.
var conn1 = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "password");
var conn2 = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.2", 8728, "admin", "password");
var list1 = conn1.LoadList<tik4net.Objects.Ip.IpAddress>();
var list2 = conn2.LoadList<tik4net.Objects.Ip.IpAddress>();
// List contains IP addresses of both devices.
var list = list1.Concat(list2);
/system/package/update/check-for-updates
/system/package/update/download
/system/reboot
try
{
string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"];
string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"];
string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"];
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword))
{
connection.Open();
string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'";
SqlCommand command2 = new SqlCommand(query, connection);
SqlDataReader reader = command2.ExecuteReader();
while (reader.Read())
{
string TcNo = reader.GetString(0);
int CheckIn = reader.GetInt32(1);
int CheckOut = reader.GetInt32(2);
ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
printCmd.AddParameter("?.name", TcNo);
List<ITikReSentence> response = printCmd.ExecuteList().ToList();
bool userExists = (response != null && response.Count > 0);
if (userExists && CheckIn == 1 && CheckOut == 1)
{
// Find the user ID
ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
printCmd.AddParameter("?.name", TcNo);
ITikSentence response = printCmd.ExecuteList();
string userId = response.FirstOrDefault()?[".id"];
if (!string.IsNullOrEmpty(userId))
{
// Remove the user from the hotspot
ITikCommand removeCmd = connection1.CreateCommand("/ip/hotspot/user/remove");
removeCmd.AddParameter(".id", userId);
removeCmd.ExecuteNonQuery();
}
}
else if (!userExists && CheckIn == 1 && CheckOut == 0)
{
// Create an API command to add a new hotspot user with the name from the SQL query
ITikCommand addCmd = connection1.CreateCommand("/ip/hotspot/user/add");
addCmd.AddParameter("name", TcNo);
addCmd.ExecuteNonQuery();
}
}
}
}
catch (Exception ex)
{
// Handle any errors that occur
MessageBox.Show(ex.Message);
}
{
try
{
string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"];
string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"];
string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"];
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword))
{
connection.Open();
string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'";
SqlCommand command2 = new SqlCommand(query, connection);
SqlDataReader reader = command2.ExecuteReader();
while (reader.Read())
{
string TcNo = reader.GetString(0);
int CheckIn = reader.GetInt32(1);
int CheckOut = reader.GetInt32(2);
bool userExists = false;
// Check if the user already exists
foreach (HotspotUser user in connection1.LoadAll<HotspotUser>())
{
if (user.Name == TcNo)
{
userExists = true;
break;
}
}
if (!userExists && CheckIn == 1 && CheckOut == 0)
{
// Add the new user if it doesn't exist
var user = new HotspotUser()
{
Name = TcNo,
};
connection1.Save(user);
}
else if (CheckIn == 1 && CheckOut == 1)
{
// Remove the user if it exists
foreach (HotspotUser user in connection1.LoadAll<HotspotUser>())
{
if (user.Name == TcNo)
{
connection1.Delete(user);
break;
}
}
}
}
}
}
catch (Exception ex)
{
// Handle any errors that occur
MessageBox.Show(ex.Message);
}
}
hi, i'm trying to do remove hotspot user by id name but it's not working. I checked all the pages and couldn't make it. Here is my code
Code: Select alltry { string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"]; string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"]; string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"]; string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword)) { connection.Open(); string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'"; SqlCommand command2 = new SqlCommand(query, connection); SqlDataReader reader = command2.ExecuteReader(); while (reader.Read()) { string TcNo = reader.GetString(0); int CheckIn = reader.GetInt32(1); int CheckOut = reader.GetInt32(2); ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print"); printCmd.AddParameter("?.name", TcNo); List<ITikReSentence> response = printCmd.ExecuteList().ToList(); bool userExists = (response != null && response.Count > 0); if (userExists && CheckIn == 1 && CheckOut == 1) { // Find the user ID ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print"); printCmd.AddParameter("?.name", TcNo); ITikSentence response = printCmd.ExecuteList(); string userId = response.FirstOrDefault()?[".id"]; if (!string.IsNullOrEmpty(userId)) { // Remove the user from the hotspot ITikCommand removeCmd = connection1.CreateCommand("/ip/hotspot/user/remove"); removeCmd.AddParameter(".id", userId); removeCmd.ExecuteNonQuery(); } } else if (!userExists && CheckIn == 1 && CheckOut == 0) { // Create an API command to add a new hotspot user with the name from the SQL query ITikCommand addCmd = connection1.CreateCommand("/ip/hotspot/user/add"); addCmd.AddParameter("name", TcNo); addCmd.ExecuteNonQuery(); } } } } catch (Exception ex) { // Handle any errors that occur MessageBox.Show(ex.Message); }