Exemplo n.º 1
0
        static void Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                               .Build();

            while (true)
            {
                using ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api);

                var host     = configuration.GetSection("Mikrotik").GetSection("Host").Value;
                var user     = configuration.GetSection("Mikrotik").GetSection("User").Value;
                var password = configuration.GetSection("Mikrotik").GetSection("Password").Value;

                var influxDbEnabled   = bool.Parse(configuration.GetSection("InfluxDb").GetSection("Enabled").Value);
                var influxDbUrl       = configuration.GetSection("InfluxDb").GetSection("Url").Value;
                var influxDatabase    = configuration.GetSection("InfluxDb").GetSection("Database").Value;
                var influxMeasurement = configuration.GetSection("InfluxDb").GetSection("Measurement").Value;
                var isConsoleOutput   = bool.Parse(configuration.GetSection("App").GetSection("ConsoleOutput").Value);
                var sleepTimeout      = int.Parse(configuration.GetSection("App").GetSection("SleepTimeout").Value);

                connection.Open(host, user, password);
                connection.ExecuteNonQuery("/ip/accounting/snapshot/take");
                var interfaces = connection.LoadList <IpAddress>()
                                 .ToImmutableSortedDictionary(d => d.Address, a => a.Interface);
                var acctList = connection.LoadList <AccountingSnapshot>();

                var payload = new LineProtocolPayload();

                foreach (var item in acctList)
                {
                    var point = new LineProtocolPoint(
                        influxMeasurement,
                        new Dictionary <string, object>
                    {
                        { "bytes", item.Bytes },
                        { "packets", item.Packets },
                    },
                        TagDirection(item, interfaces),
                        DateTime.UtcNow);
                    payload.Add(point);
                }

                if (influxDbEnabled)
                {
                    var client = new LineProtocolClient(new Uri(influxDbUrl), influxDatabase);
                    client.WriteAsync(payload);
                }
                if (isConsoleOutput)
                {
                    var wr = new StringWriter();
                    payload.Format(wr);
                    Console.WriteLine(wr.GetStringBuilder().ToString());
                }

                Thread.Sleep(sleepTimeout);
            }
        }
Exemplo n.º 2
0
        public static bool suspendpppoeuser(string pppoeuser)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
            {
                connection.Open("10.19.10.1", "OrionAdmin", "Frank1e2015");


                var pppoeactive = connection.LoadList <PppActive>();
                foreach (PppActive pppa in pppoeactive)
                {
                    string ipaddress = "";
                    if (pppa.Name == pppoeuser)
                    {
                        ipaddress = pppa.Address;
                    }
                    if (ipaddress != "")
                    {
                        ITikCommand cmd = connection.CreateCommand("/ip/firewall/address-list/add",
                                                                   connection.CreateParameter("list", "unmssuspend"),
                                                                   connection.CreateParameter("address", ipaddress),
                                                                   connection.CreateParameter("comment", "suspend"));
                        cmd.ExecuteAsync(response =>
                        {
                            // Console.WriteLine("Row: " + response.GetResponseField("tx"));
                        });

                        cmd.Cancel();
                    }
                }

                connection.Close();
            }
            return(true);
        }
Exemplo n.º 3
0
        private static void CreateOrUpdateAddressListMulti(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName)).ToList();
            var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list

            if (existingAddressList.Count() <= 0)
            {
                //Create (just in memory)
                existingAddressList.Add(
                    new FirewallAddressList()
                {
                    Address = ipAddress,
                    List    = listName,
                });
                existingAddressList.Add(
                    new FirewallAddressList()
                {
                    Address = ipAddress2,
                    List    = listName,
                });
            }
            else
            {
                //Update (just in memory)
                foreach (var addressList in existingAddressList)
                {
                    addressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();
                }
            }

            //save differences into mikrotik  (existingAddressList=modified, listClonedBackup=unmodified)
            connection.SaveListDifferences(existingAddressList, listClonedBackup);
        }
Exemplo n.º 4
0
        private static void CreateOrUpdateAddressListMulti(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList<FirewallAddressList>(
                connection.CreateParameter("list", listName)).ToList();
            var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list

            if (existingAddressList.Count() <= 0)
            {
                //Create (just in memory)
                existingAddressList.Add(
                    new FirewallAddressList()
                    {
                        Address = ipAddress,
                        List = listName,
                    });
                existingAddressList.Add(
                    new FirewallAddressList()
                    {
                        Address = ipAddress2,
                        List = listName,
                    });
            }
            else
            {
                //Update (just in memory)
                foreach (var addressList in existingAddressList)
                {
                    addressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();
                }
            }

            //save differences into mikrotik  (existingAddressList=modified, listClonedBackup=unmodified)
            connection.SaveListDifferences(existingAddressList, listClonedBackup);
        }
        /// <summary>
        /// Traceroutes given <see paramref="address"/>.
        /// </summary>
        public static IEnumerable <ToolTraceroute> HamnetTraceroute(this ITikConnection connection, string address)
        {
            var result = connection.LoadList <ToolTraceroute>(
                connection.CreateParameter("address", address, TikCommandParameterFormat.NameValue),
                connection.CreateParameter("count", "1", TikCommandParameterFormat.NameValue));

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Pings given <see paramref="address"/>. Returns <paramref name="cnt"/> of ping results to the <paramref name="address"/>.
        /// </summary>
        public static IEnumerable <ToolPing> Ping(this ITikConnection connection, string address, int cnt)
        {
            var result = connection.LoadList <ToolPing>(
                connection.CreateParameter("address", address, TikCommandParameterFormat.NameValue),
                connection.CreateParameter("count", cnt.ToString(), TikCommandParameterFormat.NameValue));

            return(result);
        }
Exemplo n.º 7
0
        private static void Log(ITikConnection connection)
        {
            var logs = connection.LoadList <Log>();

            foreach (Log log in logs)
            {
                Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
            }
        }
Exemplo n.º 8
0
        private static void PrintIpAddresses(ITikConnection connection)
        {
            var ipAddresses = connection.LoadList <IpAddress>();

            foreach (var addr in ipAddresses)
            {
                Console.WriteLine(addr.EntityToString());
            }
        }
Exemplo n.º 9
0
        private static void PrintAddressList(ITikConnection connection)
        {
            var addressLists = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName));

            foreach (FirewallAddressList addressList in addressLists)
            {
                Console.WriteLine("{0}{1}: {2} {3} ({4})", addressList.Disabled ? "X" : " ", addressList.Dynamic ? "D" : " ", addressList.Address, addressList.List, addressList.Comment);
            }
        }
Exemplo n.º 10
0
        private static void DeleteAddressListMulti(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName)).ToList();
            var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list

            existingAddressList.Clear();

            //save differences into mikrotik  (existingAddressList=modified, listClonedBackup=unmodified)
            connection.SaveListDifferences(existingAddressList, listClonedBackup);
        }
Exemplo n.º 11
0
        private static void DeleteAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();

            if (existingAddressList != null)
            {
                connection.Delete(existingAddressList);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            DateTime lastQuery = DateTime.MinValue;
            Thread   thQuery   = new Thread(new ThreadStart(() =>
            {
                while (PackageHost.IsRunning)
                {
                    if (DateTime.Now.Subtract(lastQuery).TotalMilliseconds >= PackageHost.GetSettingValue <int>("QueryInterval"))
                    {
                        if (this.connection == null || !this.connection.IsOpened)
                        {
                            this.connection = this.GetConnection();
                        }
                        if (this.connection != null && this.connection.IsOpened)
                        {
                            try
                            {
                                // Test connection with simple command
                                connection.CreateCommand("/system/identity/print").ExecuteScalar();
                                // Query & push
                                this.QueryAndPush("SystemResource", () => connection.LoadSingle <SystemResource>());
                                this.QueryAndPush("DhcpServerLeases", () => connection.LoadList <DhcpServerLease>());
                                this.QueryAndPush("WirelessClients", () => connection.LoadList <CapsManRegistrationTable>());
                                this.QueryAndPush("Queues", () => connection.LoadList <QueueSimple>());
                                this.QueryAndPush("IpAddresses", () => connection.LoadList <IpAddress>());
                                this.QueryAndPush("Interfaces", () => connection.LoadList <Interface>());
                            }
                            catch (IOException)
                            {
                                this.connection = null;
                            }
                        }
                        lastQuery = DateTime.Now;
                    }
                    Thread.Sleep(100);
                }
            }));

            thQuery.Start();
            PackageHost.WriteInfo("Package started !");
        }
Exemplo n.º 13
0
 void ButtonClickedConnect(System.Object sender, System.EventArgs e)
 {
     try
     {
         using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
         {
             connection.Open(ipAdress(), Login.Text, Password.Text);
             ITikCommand cmd = connection.CreateCommand("/system/identity/print");
             Console.WriteLine(cmd.ExecuteScalar());
             if (connection.IsOpened)
             {
                 ConnectionStatus.Text   = "OK";
                 buttonOn.IsVisible      = true;
                 buttonOff.IsVisible     = true;
                 ToOptionsPage.IsVisible = true;
                 buttonClear.Text        = "CANCEL";
                 IP_adress_1.IsEnabled   = false;
                 IP_adress_2.IsEnabled   = false;
                 IP_adress_3.IsEnabled   = false;
                 IP_adress_4.IsEnabled   = false;
                 Login.IsEnabled         = false;
                 Password.IsEnabled      = false;
                 buttonConnect.IsEnabled = false;
                 var poe_status = connection.LoadList <InterfaceEthernet>();
                 int portNum    = 0;
                 foreach (InterfaceEthernet interfaceEthernet in poe_status)
                 {
                     ports.Add(portNum, interfaceEthernet.Name);
                     portNum++;
                 }
                 //Console.WriteLine("Имя порта ", ports[0]); // имя порта
                 Console.WriteLine(ports.Keys.Count); // количество портов
             }
         }
     }
     catch (Exception ex)
     {
         //Console.WriteLine("Exception: " + ex.Message);
         ConnectionStatus.Text = ex.Message;
     }
 }
Exemplo n.º 14
0
        private static void CreateOrUpdateAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList<FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();
            if (existingAddressList == null)
            {
                //Create
                var newAddressList = new FirewallAddressList()
                {
                    Address = ipAddress,
                    List = listName,
                };
                connection.Save(newAddressList);
            }
            else
            {
                //Update
                existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();

                connection.Save(existingAddressList);
            }
        }
Exemplo n.º 15
0
        public static bool Mikrotik()

        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
            {
                connection.Open("10.19.20.1", "OrionAdmin", "Frank1e2015");
                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();
                return(true);
            }
        }
Exemplo n.º 16
0
        private static void CreateOrUpdateAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();

            if (existingAddressList == null)
            {
                //Create
                var newAddressList = new FirewallAddressList()
                {
                    Address = ipAddress,
                    List    = listName,
                };
                connection.Save(newAddressList);
            }
            else
            {
                //Update
                existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();

                connection.Save(existingAddressList);
            }
        }
Exemplo n.º 17
0
 private static void PrintIpAddresses(ITikConnection connection)
 {
     var ipAddresses = connection.LoadList<IpAddress>();
     foreach(var addr in ipAddresses)
     {
         Console.WriteLine(addr.EntityToString());
     }
 }
Exemplo n.º 18
0
 private static void PrintAddressList(ITikConnection connection)
 {
     var addressLists = connection.LoadList<FirewallAddressList>(
         connection.CreateParameter("list", listName));
     foreach (FirewallAddressList addressList in addressLists)
     {
         Console.WriteLine("{0}{1}: {2} {3} ({4})", addressList.Disabled ? "X" : " ", addressList.Dynamic ? "D" : " ", addressList.Address, addressList.List, addressList.Comment);
     }
 }
Exemplo n.º 19
0
 private static void Log(ITikConnection connection)
 {
     var logs = connection.LoadList<Log>();
     foreach (Log log in logs)
     {
         Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
     }
 }
Exemplo n.º 20
0
        private static void DeleteAddressListMulti(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList<FirewallAddressList>(
                connection.CreateParameter("list", listName)).ToList();
            var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list

            existingAddressList.Clear();

            //save differences into mikrotik  (existingAddressList=modified, listClonedBackup=unmodified)
            connection.SaveListDifferences(existingAddressList, listClonedBackup);
        }
Exemplo n.º 21
0
        private static void DeleteAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList<FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();

            if (existingAddressList != null)
                connection.Delete(existingAddressList);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Called when the package is started.
 /// </summary>
 public override void OnStart()
 {
     Task.Factory.StartNew(async() =>
     {
         while (PackageHost.IsRunning)
         {
             try
             {
                 if (this.connection == null || !this.connection.IsOpened)
                 {
                     this.connection = this.GetConnection();
                 }
                 if (this.connection != null && this.connection.IsOpened)
                 {
                     try
                     {
                         // Test connection with simple command
                         connection.CreateCommand("/system/identity/print").ExecuteScalar();
                         // Query & push
                         // - Base objects -
                         this.QueryAndPush("SystemResource", () => connection.LoadSingle <SystemResource>());
                         this.QueryAndPush("Interfaces", () => connection.LoadList <Interface>());
                         this.QueryAndPush("IpAddresses", () => connection.LoadList <IpAddress>());
                         this.QueryAndPush("Pools", () => connection.LoadList <IpPool>());
                         this.QueryAndPush("Queues", () => connection.LoadList <QueueSimple>());
                         // - DHCP client & server leases -
                         this.QueryAndPush("DhcpClient", () => connection.LoadList <IpDhcpClient>());
                         this.QueryAndPush("DhcpServerLeases", () => connection.LoadList <DhcpServerLease>());
                         // - IPv6 objects -
                         this.QueryAndPush("Ipv6Neighbors", () => connection.LoadList <Ipv6Neighbor>());
                         this.QueryAndPush("Ipv6Pools", () => connection.LoadList <Ipv6Pool>());
                         this.QueryAndPush("Ipv6Addresses", () => connection.LoadList <Ipv6Address>());
                         this.QueryAndPush("Ipv6DhcpClient", () => connection.LoadList <Ipv6DhcpClient>());
                         // - CAPSMAN registration table  -
                         this.QueryAndPush("WirelessClients", () => connection.LoadList <CapsManRegistrationTable>());
                     }
                     catch (IOException)
                     {
                         this.connection = null;
                     }
                 }
                 await Task.Delay(Math.Min(1000, PackageHost.GetSettingValue <int>("QueryInterval")));
             }
             catch (Exception ex)
             {
                 PackageHost.WriteError($"Fatal error in the main loop : {ex}");
                 await Task.Delay(5000);
             }
         }
     }, TaskCreationOptions.LongRunning);
     PackageHost.WriteInfo("Package started !");
 }
Exemplo n.º 23
0
 /// <summary>
 /// Load users with filter
 /// </summary>
 /// <param name="filters">The filter to be used</param>
 /// <returns>The list of users</returns>
 public Task <IEnumerable <UserManagerUser> > LoadUsersWithFilterAsync(params ITikCommandParameter[] filters) => Task.Run(() => _connection.LoadList <UserManagerUser>(filters));