Пример #1
0
        void clickedOff(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());
                    var poe = connection.CreateCommand("/interface/ethernet/set");

                    foreach (string i in OptionsPage.numbers)
                    {
                        int numPort = Int32.Parse(i);
                        poe.AddParameter(TikSpecialProperties.Id, ports[numPort - 1]);
                        poe.AddParameter("poe-out", "off");
                        poe.AddParameter("disabled", "yes");
                        //Console.WriteLine("ports: " + ports[numPort]);
                        poe.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
            }
        }
Пример #2
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);
        }
Пример #3
0
 public ProgramExamples()
 {
     connection             = ConnectionFactory.CreateConnection(TikConnectionType.Api);
     connection.OnReadRow  += Connection_OnReadRow;  // logging commands to cosole
     connection.OnWriteRow += Connection_OnWriteRow; // logging commands to cosole
     connection.Open("vpn.wifiburada.com", "admin", "As081316");
 }
Пример #4
0
        internal static List <MikrotikUserList> GetUserListFromMikrotik(ITikConnection connection, Mikrotik mikrotik)
        {
            List <MikrotikUserList> lstMikrotikUserList = new List <MikrotikUserList>();
            ITikCommand             userCmd             = connection.CreateCommand("/ppp/secret/print");
            var lstUserFromMikrotik = userCmd.ExecuteList();

            foreach (var user in lstUserFromMikrotik)
            {
                var name     = user.Words["name"];
                var password = user.Words["password"];
                var package  = user.Words["profile"];
                var active   = user.Words["disabled"];
                var profile  = user.Words["profile"];
                lstMikrotikUserList.Add(new MikrotikUserList()
                {
                    UserName     = name,
                    Password     = password,
                    MikrotikID   = mikrotik.MikrotikID,
                    MikrotikName = mikrotik.MikName,
                    ProfileName  = profile,
                    active       = active
                });
            }
            return(lstMikrotikUserList);
        }
Пример #5
0
 internal TikListMerge(ITikConnection connection, IEnumerable <TEntity> expected, IEnumerable <TEntity> original)
 {
     _connection = connection;
     _metadata   = TikEntityMetadataCache.GetMetadata <TEntity>();
     _expected   = expected;
     _original   = original;
 }
Пример #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(HOST, USER, PASS);

                    var natRule     = connection.CreateCommandAndParameters("/ip/firewall/nat/print", "comment", nameRule).ExecuteList();
                    var id          = natRule.Single().GetId();
                    var disableRule = connection.CreateCommandAndParameters("/ip/firewall/nat/disable", TikSpecialProperties.Id, id);
                    disableRule.ExecuteNonQuery();

                    var list = connection.CreateCommandAndParameters("/ip/firewall/connection/print", "dst-address", dst).ExecuteList();
                    foreach (var item in list)
                    {
                        connection.CreateCommandAndParameters("/ip/firewall/connection/remove", ".id", item.Words[".id"]).ExecuteNonQuery();
                    }
                };
            }
            catch
            {
                Color colorOff_n = Color.Red;
                label1.ForeColor = colorOff_n;
                label1.Text      = ("Возникло исключение!\n Имя сервера или порт \nне доступты!");
            }
        }
Пример #7
0
        /// <summary>
        /// Loads entity list. Could be filtered with <paramref name="filterParameters"/>.
        /// </summary>
        /// <typeparam name="TEntity">Loaded entities type.</typeparam>
        /// <param name="connection">Tik connection used to load.</param>
        /// <param name="filterParameters">Optional list of filter parameters (interpreted as connected with AND)</param>
        /// <returns>List (or empty list) of loaded entities.</returns>
        /// <seealso cref="TikCommandExtensions.LoadList{TEntity}(ITikCommand)"/>
        public static IEnumerable <TEntity> LoadList <TEntity>(this ITikConnection connection, params ITikCommandParameter[] filterParameters)
            where TEntity : new()
        {
            var command = CreateLoadCommandWithFilter <TEntity>(connection, filterParameters);

            return(command.LoadList <TEntity>());
        }
Пример #8
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);
        }
Пример #9
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);
        }
Пример #10
0
        /// <summary>
        /// Creates and opens connection to the specified mikrotik host on specified port and perform the logon operation.
        /// </summary>
        /// <param name="connectionType">Type of technology used to connect to mikrotik router.</param>
        /// <param name="host">The host (name or ip).</param>
        /// <param name="port">TCPIP port.</param>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns>Opened instance of mikrotik Connection.</returns>
        /// <seealso cref="ITikConnection.Close"/>
        public static ITikConnection OpenConnection(TikConnectionType connectionType, string host, int port, string user, string password)
        {
            ITikConnection result = CreateConnection(connectionType);
            result.Open(host, port, user, password);

            return result;
        }
Пример #11
0
        /// <summary>
        /// Alias to <see cref="LoadList{TEntity}(ITikConnection, ITikCommandParameter[])"/> without filter, ensures that result contains exactly one row.
        /// </summary>
        /// <typeparam name="TEntity">Loaded entities type.</typeparam>
        /// <param name="connection">Tik connection used to load.</param>
        /// <param name="filterParameters">Optional list of filter parameters (interpreted as connected with AND)</param>
        /// <returns>Loaded single entity or null.</returns>
        /// <exception cref="InvalidOperationException">Connection or command text not set. Comand is already running. Connection is not opened. Invalid response from API.</exception>
        /// <exception cref="TikCommandTrapException">!trap returned from API call.</exception>
        /// <exception cref="TikCommandFatalException">!fatal returned from API call.</exception>
        /// <exception cref="TikCommandUnexpectedResponseException">Unexpected response from mikrotik (multiple returned rows, missing !done row etc.)</exception>
        /// <exception cref="TikNoSuchCommandException">Invalid mikrotik command (syntax error). Mikrotik API message: 'no such command'</exception>
        /// <exception cref="TikCommandAmbiguousResultException">More than one row returned.</exception>
        public static TEntity LoadSingleOrDefault <TEntity>(this ITikConnection connection, params ITikCommandParameter[] filterParameters)
            where TEntity : new()
        {
            var command = CreateLoadCommandWithFilter <TEntity>(connection, filterParameters);

            return(command.LoadSingleOrDefault <TEntity>());
        }
Пример #12
0
        private static void WriteToLog(ITikConnection connection, string message, string logLevelCommandSufix)
        {
            var cmd = connection.CreateCommand("/log/" + logLevelCommandSufix,
                                               connection.CreateParameter("message", message));

            cmd.ExecuteNonQuery();
        }
Пример #13
0
        /// <summary>
        /// Creates and opens connection to the specified mikrotik host on default port and perform the logon operation.
        /// Async version.
        /// </summary>
        /// <param name="connectionType">Type of technology used to connect to mikrotik router.</param>
        /// <param name="host">The host (name or ip).</param>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns>Opened instance of mikrotik Connection.</returns>
        /// <seealso cref="ITikConnection.Close"/>
        public static async System.Threading.Tasks.Task <ITikConnection> OpenConnectionAsync(TikConnectionType connectionType, string host, string user, string password)
        {
            ITikConnection result = CreateConnection(connectionType);
            await result.OpenAsync(host, user, password);

            return(result);
        }
Пример #14
0
        private static void QueueTreeMerge(ITikConnection connection)
        {
            var original = connection.LoadAll <QueueTree>().Where(q => q.Name == "Q1" || q.Name == "Q2" || q.Name.StartsWith("Q3"));

            string           unique   = Guid.NewGuid().ToString();
            List <QueueTree> expected = new List <QueueTree>()
            {
                new QueueTree()
                {
                    Name = "Q1", Parent = "global", PacketMark = "PM1"
                },
                new QueueTree()
                {
                    Name = "Q2", Parent = "global", PacketMark = "PM2", Comment = unique
                },                                                                                        //always update
                new QueueTree()
                {
                    Name = "Q3 " + unique, Parent = "global", PacketMark = "PM3"
                },                                                                                // always insert + delete from previous run
            };

            //Merge with Name as key - can not save via SaveListDifferences because all items in 'expected' are new (.id=null) => insert will be done, not CUD
            connection.CreateMerge(expected, original)
            .WithKey(queue => queue.Name)
            .Field(q => q.Parent)
            .Field(q => q.PacketMark)
            .Field(q => q.Comment)
            .Save();
        }
Пример #15
0
        private static ITikCommand CreateLoadCommandWithFilter <TEntity> (ITikConnection connection, ITikCommandParameter[] parameters)
        {
            var metadata = TikEntityMetadataCache.GetMetadata <TEntity>();

            ITikCommand command = connection.CreateCommand(metadata.EntityPath + metadata.LoadCommand, metadata.LoadDefaultParameneterFormat);

            // =detail=
            if (metadata.IncludeDetails)
            {
                command.AddParameter("detail", "", TikCommandParameterFormat.NameValue);
            }
            //.proplist
            if (metadata.IncludeProplist)
            {
                command.AddParameter(TikSpecialProperties.Proplist, string.Join(",", metadata.Properties.Select(prop => prop.FieldName).ToArray()), TikCommandParameterFormat.NameValue);
            }
            //filter
            //parameters
            if (parameters != null)
            {
                foreach (ITikCommandParameter param in parameters)
                {
                    command.Parameters.Add(param);
                }
            }

            return(command);
        }
Пример #16
0
        private static void ModifyIpAccounting(ITikConnection connection)
        {
            var accounting = connection.LoadSingle <IpAccounting>();

            accounting.Threshold = 257;
            connection.Save(accounting);
        }
Пример #17
0
        static void Main(string[] args)
        {
            //Future idea: create tool like iftop via API
            //Posible features:
            // DNS resolve
            // Geolocation - https://db-ip.com/db/
            // Visualise if address is from any AddressList
            // ??
            // looking for volunteers :-)

            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.Open(ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);
                string interfaceName = ConfigurationManager.AppSettings["interface"];

                Console.Clear();

                var loadingContext = connection.LoadAsync <ToolTorch>(
                    TorchItemRead, error => Console.WriteLine(error.ToString()),
                    connection.CreateParameter("interface", interfaceName),
                    //connection.CreateParameter("ip-protocol", "any"),
                    connection.CreateParameter("port", "any"),
                    connection.CreateParameter("src-address", "0.0.0.0/0"),
                    connection.CreateParameter("dst-address", "0.0.0.0/0"));

                Console.ReadLine();

                loadingContext.Cancel();
            }
        }
Пример #18
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);
            }
        }
Пример #19
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);
        }
Пример #20
0
        /// <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);
        }
Пример #21
0
        /// <summary>
        /// Gets snapshot of actual traffic RX/TX values for given <paramref name="interfaceName"/>.
        /// </summary>
        public static InterfaceMonitorTraffic GetInterfaceMonitorTrafficSnapshot(this ITikConnection connection, string interfaceName)
        {
            var result = connection.LoadSingle <InterfaceMonitorTraffic>(
                connection.CreateParameter("interface", interfaceName, TikCommandParameterFormat.NameValue),
                connection.CreateParameter("once", "", TikCommandParameterFormat.NameValue));

            return(result);
        }
Пример #22
0
        /// <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);
        }
Пример #23
0
 public Connection(string host, string user, string pass)
 {
     TikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api);
     TikConnection.SendTagWithSyncCommand = true;
     TikConnection.ReceiveTimeout         = (int)Program.Configuration.Global.CommandTimeout.TotalMilliseconds;
     TikConnection.SendTimeout            = (int)Program.Configuration.Global.CommandTimeout.TotalMilliseconds;
     TikConnection.Open(host, user, pass);
 }
Пример #24
0
        /// <summary>
        /// Calls command and reads all returned rows for given <paramref name="durationSec"/> period.
        /// After this period calls cancell to mikrotik router and returns all loaded rows.
        /// Throws exception if any 'trap' row occurs.
        /// </summary>
        /// <typeparam name="TEntity">Loaded entities type.</typeparam>
        /// <param name="connection">Tik connection used to load.</param>
        /// <param name="durationSec">Loading period.</param>
        /// <param name="parameters">Optional list of filters/parameters (interpreted as connected with AND)</param>
        /// <returns>List (or empty list) of loaded entities.</returns>
        public static IEnumerable <TEntity> LoadWithDuration <TEntity>(this ITikConnection connection, int durationSec, params ITikCommandParameter[] parameters)
            where TEntity : new()
        {
            var command = CreateLoadCommandWithFilter <TEntity>(connection, "", TikCommandParameterFormat.NameValue, parameters);

            var responseSentences = command.ExecuteListWithDuration(durationSec);

            return(responseSentences.Select(sentence => CreateObject <TEntity>(sentence)).ToList());
        }
Пример #25
0
 private void materialFlatButton1_Click(object sender, EventArgs e)
 {
     using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
     {
         connection.Open("192.168.0.1", "admin", "yami_yonatan");
         ITikCommand cmd = connection.CreateCommand("ip/neighbor/print");
         MessageBox.Show(cmd.ExecuteScalar());
     }
 }
Пример #26
0
        static void Main(string[] args)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.OnReadRow  += Connection_OnReadRow;
                connection.OnWriteRow += Connection_OnWriteRow;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();

                connection.Open(configuration["host"], configuration["user"], configuration["pass"]);

                List <string> commandRows = new List <string>();
                string        command;
                Console.WriteLine("Write command and press [ENTER] on empty line");
                Console.WriteLine("Empty command + [ENTER] stops console.");
                do
                {
                    command = Console.ReadLine();

                    if (!string.IsNullOrWhiteSpace(command))
                    {
                        commandRows.Add(command);
                    }
                    else
                    {
                        if (commandRows.Any())
                        {
                            List <string> rows = new List <string>();
                            foreach (string row in commandRows)
                            {
                                rows.AddRange(row.Split('|').Where(r => !string.IsNullOrEmpty(r)));
                            }
                            var result = connection.CallCommandSync(rows.ToArray());
                            foreach (var resultItem in result)
                            {
                                foreach (var word in resultItem.Words)
                                {
                                    Console.WriteLine($"{word.Key}={word.Value}");
                                }
                            }

                            commandRows.Clear();
                        }
                        else
                        {
                            break; //empty row and empty command -> end
                        }
                    }
                }while (true);
            }

            Console.WriteLine("Press [ENTER] to close.");
            Console.ReadLine();
        }
Пример #27
0
        /// <summary>
        /// Calls command and reads all returned rows for given <paramref name="durationSec"/> period.
        /// After this period calls cancell to mikrotik router and returns all loaded rows.
        /// Throws exception if any 'trap' row occurs.
        /// </summary>
        /// <typeparam name="TEntity">Loaded entities type.</typeparam>
        /// <param name="connection">Tik connection used to load.</param>
        /// <param name="durationSec">Loading period.</param>
        /// <param name="parameters">Optional list of filters/parameters (interpreted as connected with AND)</param>
        /// <returns>List (or empty list) of loaded entities.</returns>
        /// <seealso cref="TikCommandExtensions.LoadWithDuration{TEntity}(ITikCommand, int)"/>
        public static IEnumerable <TEntity> LoadWithDuration <TEntity>(this ITikConnection connection, int durationSec, params ITikCommandParameter[] parameters)
            where TEntity : new()
        {
            Guard.ArgumentNotNull(connection, "connection");

            var command = CreateLoadCommandWithFilter <TEntity>(connection, parameters);

            return(command.LoadWithDuration <TEntity>(durationSec));
        }
Пример #28
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);
            }
        }
Пример #29
0
        private static void DnsCachePrint(ITikConnection connection)
        {
            var cache = connection.LoadAll <IpDns.DnsCache>();

            foreach (var c in cache)
            {
                Console.WriteLine(c.EntityToString());
            }
        }
 /// <summary>
 /// Construct from all parameters.
 /// </summary>
 /// <param name="address">The address of the device executing the traceroute operation.</param>
 /// <param name="tikConnection">The Mikrotik API connection.</param>
 /// <param name="remoteIp">The target of the traceroute operation.</param>
 /// <param name="count">The number of packets to send for tracing the route.</param>
 /// <param name="timeout">The timeout of a single ping.</param>
 /// <param name="maxHops">The maximum number of hops.</param>
 public MikrotikApiTracerouteOperation(IpAddress address, ITikConnection tikConnection, IpAddress remoteIp, uint count, TimeSpan timeout, int maxHops)
 {
     this.maxHops       = maxHops;
     this.timeout       = timeout;
     this.address       = address ?? throw new System.ArgumentNullException(nameof(address), "address of executing device is null when creating a MikrotikApiTracerouteOperation");
     this.tikConnection = tikConnection ?? throw new System.ArgumentNullException(nameof(tikConnection), "tikConnection is null when creating a MikrotikApiTracerouteOperation");
     this.remoteIp      = remoteIp ?? throw new System.ArgumentNullException(nameof(remoteIp), "address of the traceroute destination is null when creating a MikrotikApiTracerouteOperation");
     this.count         = count;
 }
Пример #31
0
        private static void PrintIpAddresses(ITikConnection connection)
        {
            var ipAddresses = connection.LoadList <IpAddress>();

            foreach (var addr in ipAddresses)
            {
                Console.WriteLine(addr.EntityToString());
            }
        }
Пример #32
0
        private static void AddFirewalFilter(ITikConnection connection)
        {
            var firewallFilter = new FirewallFilter()
            {
                Chain = FirewallFilter.ChainType.Forward,
                Action = FirewallFilter.ActionType.Accept,
            };

            connection.Save(firewallFilter);

            var loaded = connection.LoadAll<FirewallFilter>().First();
            loaded.Comment = "TEST";
            connection.Save(loaded);
        }
Пример #33
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);
            }
        }
Пример #34
0
        private static void QueueTreeMerge(ITikConnection connection)
        {
            var original = connection.LoadAll<QueueTree>().Where(q=> q.Name == "Q1" || q.Name == "Q2" || q.Name.StartsWith("Q3"));

            string unique = Guid.NewGuid().ToString();
            List<QueueTree> expected = new List<QueueTree>()
            {
                new QueueTree() { Name = "Q1", Parent = "global", PacketMark = "PM1" },
                new QueueTree() { Name = "Q2", Parent = "global", PacketMark = "PM2", Comment = unique }, //always update
                new QueueTree() { Name = "Q3 " + unique, Parent = "global", PacketMark = "PM3" }, // always insert + delete from previous run
            };

            //Merge with Name as key - can not save via SaveListDifferences because all items in 'expected' are new (.id=null) => insert will be done, not CUD
            connection.CreateMerge(expected, original)
                .WithKey(queue => queue.Name)
                .Field(q => q.Parent)
                .Field(q => q.PacketMark)
                .Field(q => q.Comment)
                .Save();
        }
Пример #35
0
 private static void PrintIpAddresses(ITikConnection connection)
 {
     var ipAddresses = connection.LoadList<IpAddress>();
     foreach(var addr in ipAddresses)
     {
         Console.WriteLine(addr.EntityToString());
     }
 }
Пример #36
0
 private static void ModifyIpAccounting(ITikConnection connection)
 {
     var accounting = connection.LoadSingle<IpAccounting>();
     accounting.Threshold = 257;
     connection.Save(accounting);
 }
Пример #37
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);
     }
 }
Пример #38
0
        private static void FirewallMangleMerge(ITikConnection connection)
        {
            //manage just subset before rules marked with comment =START= and =END=

            //Create subset boundaries if not present
            const string startComment = "=START=";
            const string endComment = "=END=";
            var startMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", startComment));
            if (startMangle == null)
            {
                startMangle = new FirewallMangle()
                {
                    Chain = "forward",
                    Action = FirewallMangle.ActionType.Passthrough,
                    Comment = startComment,
                    Disabled = true,
                };
                connection.Save(startMangle);
            };
            var endMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", endComment));
            if (endMangle == null)
            {
                endMangle = new FirewallMangle()
                {
                    Chain = "forward",
                    Action = FirewallMangle.ActionType.Passthrough,
                    Comment = endComment,
                    Disabled = true,
                };
                connection.Save(endMangle);
            };

            //Merge subset between boundaries
            string unique = Guid.NewGuid().ToString();
            List<FirewallMangle> original = connection.LoadAll<FirewallMangle>().SkipWhile(m=>m.Comment != startComment).TakeWhile(m=>m.Comment != endComment)
                .Concat(new List<FirewallMangle> { endMangle})
                .ToList(); //just subset between =START= and =END= (not very elegant but functional and short ;-) )
            List<FirewallMangle> expected = new List<FirewallMangle>();
            expected.Add(startMangle);
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.1",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-001",
                Passthrough = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.2",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-002" + "-" +  unique,
                Passthrough = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.3",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-003",
                Passthrough = false,
                Comment = unique,
            });
            expected.Add(endMangle);

            connection.CreateMerge(expected, original)
                .WithKey(mangle => mangle.SrcAddress + ":" + mangle.Comment) //Use src-address as key
                .Field(q => q.Chain)
                .Field(q => q.SrcAddress) //Do not forget include also key fields !!!
                .Field(q => q.Action)
                .Field(q => q.NewPacketMark)
                .Field(q => q.Passthrough)
                .Field(q => q.Comment)
                .Save();
        }
Пример #39
0
 private static void DhcpClientRelease(ITikConnection connection)
 {
     connection.LoadAll<IpDhcpClient>().First().Release(connection);
 }
Пример #40
0
 /// <summary>
 /// Take new snapshot
 /// </summary>
 /// <param name="connection"></param>
 public static void Take(ITikConnection connection)
 {
     var cmd = connection.CreateCommand("/ip/accounting/snapshot/take");
     cmd.ExecuteNonQuery();
 }
Пример #41
0
 /// <summary>
 /// Check status of a given busy dynamic lease, and free it in case of no response
 /// </summary>
 public void CheckStatus(ITikConnection connection)
 {
     connection.CreateCommandAndParameters("ip/dhcp-server/lease/check-status",
         TikSpecialProperties.Id, Id).ExecuteNonQuery();
 }
Пример #42
0
 /// <summary>
 /// Convert a dynamic lease to a static one
 /// </summary>
 public void MakeStatic(ITikConnection connection)
 {
     connection.CreateCommandAndParameters("ip/dhcp-server/lease/make-static",
         TikSpecialProperties.Id, Id).ExecuteNonQuery();
 }
Пример #43
0
 protected void RecreateConnection()
 {
     _connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);
 }
Пример #44
0
 /// <summary>
 /// clears internal DNS cache 
 /// </summary>
 public void Flush(ITikConnection connection)
 {
     connection.CreateCommand("ip/dns/cache/flush").ExecuteNonQuery();
 }
Пример #45
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);
        }
Пример #46
0
 public void Init()
 {
     _connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);
 }
Пример #47
0
 private static void DnsCachePrint(ITikConnection connection)
 {
     var cache = connection.LoadAll<IpDns.DnsCache>();
     foreach(var c in cache)
     {
         Console.WriteLine(c.EntityToString());
     }
 }
Пример #48
0
 public ApiCommand(ITikConnection connection)
     : this()
 {
     Connection = connection;
 }
Пример #49
0
        private static void Identity(ITikConnection connection)
        {
            ITikCommand cmd = connection.CreateCommand("/system/identity/print");
            var identity = cmd.ExecuteScalar(); //cmd.ExecuteSIngleRow()
            Console.WriteLine("Identity: " + /*identity.GetResponseField("name")*/ identity);

            Console.WriteLine("Press ENTER");
            Console.ReadLine();
        }
Пример #50
0
 public ApiCommand(ITikConnection connection, TikCommandParameterFormat defaultParameterFormat)
     : this(defaultParameterFormat)
 {
     Connection = connection;
 }
Пример #51
0
 public ApiCommand(ITikConnection connection, string commandText)
     : this(connection)
 {
     CommandText = commandText;
 }
Пример #52
0
 public ApiCommand(ITikConnection connection, string commandText, TikCommandParameterFormat defaultParameterFormat)
     : this(connection, defaultParameterFormat)
 {
     CommandText = commandText;
 }
Пример #53
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);
     }
 }
Пример #54
0
 public ApiCommand(ITikConnection connection, string commandText, TikCommandParameterFormat defaultParameterFormat, params ITikCommandParameter[] parameters)
     : this(connection, commandText, defaultParameterFormat)
 {
     _parameters.AddRange(parameters);
 }
Пример #55
0
 private static void PrintSystemResource(ITikConnection connection)
 {
     var sysRes = connection.LoadSingle<SystemResource>();
     Console.WriteLine(sysRes.EntityToString());
 }
Пример #56
0
 /// <summary>
 /// Renew current leases. If the renew operation was not successful, client tries to reinitialize lease (i.e. it starts lease request procedure (rebind) as if it had not received an IP address yet)
 /// </summary>
 public void Renew(ITikConnection connection)
 {
     connection.CreateCommandAndParameters("ip/dhcp-client/renew",
         TikSpecialProperties.Id, Id).ExecuteNonQuery();
 }
Пример #57
0
 private static void Torch(ITikConnection connection)
 {
     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.CancelAndJoin();
 }
Пример #58
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);
        }
Пример #59
0
 private static void WriteToLog(ITikConnection connection, string message, string logLevelCommandSufix)
 {
     var cmd =connection.CreateCommand("/log/" + logLevelCommandSufix,
         connection.CreateParameter("message", message));
     cmd.ExecuteNonQuery();
 }
Пример #60
0
 /// <summary>
 /// Convert a dynamic lease to a static one
 /// </summary>
 public void ResetAlert(ITikConnection connection)
 {
     connection.CreateCommandAndParameters("ip/dhcp-server/alert/reset-alert",
         TikSpecialProperties.Id, Id).ExecuteNonQuery();
 }