Ejemplo n.º 1
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;
        }
Ejemplo 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);
        }
Ejemplo n.º 3
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();
            }
        }
Ejemplo n.º 4
0
        //
        // Button Connect
        //
        private void btnConnect_MouseClick(object sender, MouseEventArgs e)
        {
            string host     = txtHost.Text;
            string user     = txtUser.Text;
            string password = txtPassword.Text;

            if (!host.IsNullOrWhiteSpace() && !user.IsNullOrWhiteSpace())
            {
                try
                {
                    connection.OnReadRow  += Connection_OnReadRow;
                    connection.OnWriteRow += Connection_OnWriteRow;
                    connection.Open(host, user, password);
                    btnSubmit.Enabled         = true;
                    btnSystem.Enabled         = true;
                    btnMenu.Enabled           = true;
                    txtCommand.ReadOnly       = false;
                    lblConnectionStatus.Color = Color.GreenYellow;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("Please Enter Your Host and Password.");
            }
        }
Ejemplo n.º 5
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");
 }
Ejemplo n.º 6
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
            {
            }
        }
Ejemplo n.º 7
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не доступты!");
            }
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
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();
        }
Ejemplo n.º 11
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());
     }
 }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.OnReadRow  += Connection_OnReadRow;  // logging commands to cosole
                connection.OnWriteRow += Connection_OnWriteRow; // logging commands to cosole
                connection.Open(ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);

                //------------------------------------------------
                //  LOW LEVEL API (hint: uncomment any example call and debug)
                Identity(connection);

                Torch(connection);

                Log(connection);

                //-------------------------------------------------
                // HIGHLEVEL API (hint: uncomment any example call and debug)

                PrintAddressList(connection);
                CreateOrUpdateAddressList(connection);
                PrintAddressList(connection);
                CreateOrUpdateAddressList(connection);
                PrintAddressList(connection);
                DeleteAddressList(connection);
                PrintAddressList(connection);

                PrintAddressList(connection);
                CreateOrUpdateAddressListMulti(connection);
                PrintAddressList(connection);
                CreateOrUpdateAddressListMulti(connection);
                PrintAddressList(connection);
                DeleteAddressListMulti(connection);
                PrintAddressList(connection);

                PrintIpAddresses(connection);

                PrintSystemResource(connection);

                ModifyIpAccounting(connection);

                AddFirewalFilter(connection);

                DhcpClientRelease(connection);

                DnsCachePrint(connection);

                //---------------------------------------------------------
                // Advanced merge support (hint: uncomment any example call and debug)
                QueueTreeMerge(connection);
                FirewallMangleMerge(connection);

                Console.WriteLine("Finito - press ENTER");
                Console.ReadLine();
            }
        }
Ejemplo n.º 13
0
        public static void test()
        {
            using (ITikConnection 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");

                //------------------------------------------------
                //  LOW LEVEL API (hint: uncomment any example call and debug)
                Identity(connection);

                Torch(connection);

                Log(connection);

                //-------------------------------------------------
                // HIGHLEVEL API (hint: uncomment any example call and debug)

                PrintAddressList(connection);
                CreateOrUpdateAddressList(connection);
                PrintAddressList(connection);
                CreateOrUpdateAddressList(connection);
                PrintAddressList(connection);
                DeleteAddressList(connection);
                PrintAddressList(connection);

                PrintAddressList(connection);
                CreateOrUpdateAddressListMulti(connection);
                PrintAddressList(connection);
                CreateOrUpdateAddressListMulti(connection);
                PrintAddressList(connection);
                DeleteAddressListMulti(connection);
                PrintAddressList(connection);

                PrintIpAddresses(connection);

                //PrintSystemResource(connection);

                ModifyIpAccounting(connection);

                AddFirewalFilter(connection);

                DhcpClientRelease(connection);

                DnsCachePrint(connection);

                //---------------------------------------------------------
                // Advanced merge support (hint: uncomment any example call and debug)
                QueueTreeMerge(connection);
                FirewallMangleMerge(connection);

                Console.WriteLine("Finito - press ENTER");
                Console.ReadLine();
            }
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.OnReadRow  += Connection_OnReadRow;
                connection.OnWriteRow += Connection_OnWriteRow;
                connection.Open(ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]);

                List <string> commandRows = new List <string>();
                string        command;
                Console.WriteLine("MIKROTIK CONTROLLER");
                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);
                                }
                            }

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

            Console.WriteLine("Press [ENTER] to close.");
            Console.ReadLine();
        }
Ejemplo n.º 15
0
        private void label1_Click(object sender, EventArgs e)
        {
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(HOST, USER, PASS);

                    int n = 1;

                    var natRule = connection.CreateCommandAndParameters("/ip/route/print", "dst-address", route).ExecuteList();
                    var value   = natRule.Count();
                    if (value == n)
                    {
                        Color colorOn = Color.Blue;
                        label1.ForeColor = colorOn;
                        label1.Text      = ("Текущий статус сервера\n          ДОСТУПЕН!");
                    }
                }
            }
            catch
            {
                Color colorOff_n = Color.Red;
                label1.ForeColor = colorOff_n;
                label1.Text      = ("Возникло исключение!\n Имя сервера или порт \nне доступты!");
            }

            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(HOST, USER, PASS);

                    int i = 0;

                    var natRule = connection.CreateCommandAndParameters("/ip/route/print", "dst-address", route).ExecuteList();
                    var value   = natRule.Count();
                    if (value == i)
                    {
                        Color colorOff_n = Color.Red;
                        label1.ForeColor = colorOff_n;
                        label1.Text      = ("Текущий статус сервера\n        НЕ ДОСТУПЕН!");
                    }
                }
            }
            catch
            {
                Color colorOff_n = Color.Red;
                label1.ForeColor = colorOff_n;
                label1.Text      = ("Возникло исключение!\nИмя сервера или порт \nне доступты!");
            }
        }
Ejemplo n.º 16
0
 public void TikConnectionTest()
 {
     using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
     {
         connection.Open("44.224.10.78", "monitoring", "");
         var traceroute = connection.HamnetTraceroute("44.137.62.114");
         //var advertisements = connection.LoadAll<BgpAdvertisement>();
         //var instances = connection.LoadAll<BgpInstance>();
         //var peers = connection.LoadAll<BgpPeer>();
         //var networks = connection.LoadAll<BgpNetwork>();
         //var routes = connection.LoadAll<IpRoute>();
     }
 }
Ejemplo n.º 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(HOST, USER, PASS);

                    int i = 0;

                    var natRule = connection.CreateCommandAndParameters("/ip/route/print", "dst-address", route).ExecuteList();
                    var value   = natRule.Count();
                    if (value == i)
                    {
                        Color colorOff_n = Color.Red;
                        label1.ForeColor = colorOff_n;
                        label1.Text      = ("Сервер уже отключен,\n      включите его.");
                        return;
                    }
                }
            }
            catch
            {
                Color colorOff_n = Color.Red;
                label1.ForeColor = colorOff_n;
                label1.Text      = ("Возникло исключение!\nИмя сервера или порт \nне доступты!");
            }

            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(HOST, USER, PASS);

                    var natRule = connection.CreateCommandAndParameters("/ip/address/print", "comment", nameRule).ExecuteList();
                    var id      = natRule.Single().GetId();

                    var disableRule = connection.CreateCommandAndParameters("/ip/address/disable", TikSpecialProperties.Id, id);
                    disableRule.ExecuteNonQuery();
                    Color colorOff = Color.Red;
                    label1.ForeColor = colorOff;
                    label1.Text      = ("Вы отключили сервер.");
                }
            }
            catch
            {
                Color colorOff_n = Color.Red;
                label1.ForeColor = colorOff_n;
                label1.Text      = ("Возникло исключение!\nИмя сервера или порт \nне доступты!");
            }
        }
Ejemplo n.º 18
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            btnGenerate.Enabled = false;
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(tbHost.Text, tbUser.Text, tbPass.Text);

                    var cmd = connection.CreateCommand(tbPath.Text);
                    if (cbIncludeDetails.Checked)
                    {
                        cmd.AddParameter("detail", "");
                    }
                    if (!string.IsNullOrWhiteSpace(tbParameters.Text))
                    {
                        cmd.AddParameterAndValues(tbParameters.Text.Split(';', '|'));
                    }

                    List <ITikReSentence> rows;
                    if (!cbExecuteAsync.Checked)
                    {
                        rows = cmd.ExecuteList().ToList();
                    }
                    else
                    {
                        rows = cmd.ExecuteListWithDuration(10).ToList();
                    }

                    if (rows.Any())
                    {
                        tbSourceCode.Text = Generate(tbPath.Text, cbIncludeDetails.Checked, rows);
                        tbSourceCode.SelectAll();
                        tbSourceCode.Focus();
                    }
                    else
                    {
                        MessageBox.Show("Empty response");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            btnGenerate.Enabled = true;
        }
Ejemplo n.º 19
0
        //
        // Button Connect
        //
        private void btnConnect_MouseClick(object sender, MouseEventArgs e)
        {
            string action = btnConnect.Text;

            if (action == "Connect")
            {
                string host     = txtHost.Text;
                string user     = txtUser.Text;
                string password = txtPassword.Text;
                if (!host.IsNullOrWhiteSpace() && !user.IsNullOrWhiteSpace())
                {
                    try
                    {
                        connection.OnReadRow  += Connection_OnReadRow;
                        connection.OnWriteRow += Connection_OnWriteRow;
                        connection.Open(host, user, password);
                        lblStatus.Text      = "Connected";
                        lblStatus.ForeColor = System.Drawing.Color.Green;
                        tableOption.Visible = true;
                        btnSubmit.Enabled   = true;
                        txtCommand.ReadOnly = false;
                        btnConnect.Text     = "Disconnect";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Your Host and Password.");
                }
            }
            else if (action == "Disconnect")
            {
                connection.Close();
                btnConnect.Text     = "Connect";
                lblStatus.Text      = "Disconnect";
                lblStatus.ForeColor = Color.Crimson;
                rtxDisplay.Text     = "";
                tableOption.Visible = false;
                btnSubmit.Enabled   = false;
                txtCommand.ReadOnly = true;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the Mikrotik connection.
        /// </summary>
        /// <returns></returns>
        private ITikConnection GetConnection()
        {
            PackageHost.WriteInfo("Connecting to {0} ...", PackageHost.GetSettingValue("Host"));
            ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api);

            try
            {
                connection.Open(PackageHost.GetSettingValue("Host"), PackageHost.GetSettingValue("Username"), PackageHost.GetSettingValue("Password"));
                PackageHost.WriteInfo("Connected!");
            }
            catch (Exception ex)
            {
                PackageHost.WriteError($"Unable to connect to {PackageHost.GetSettingValue("Host")} : {ex.Message}");
                connection.Dispose();
                connection = null;
            }
            return(connection);
        }
Ejemplo n.º 21
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;
     }
 }
Ejemplo n.º 22
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);
            }
        }
Ejemplo n.º 23
0
        public static bool UpdateSecret()
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
            {
                connection.Open("10.19.60.1", "OrionAdmin", "Frank1e2015");

                radiusEntities     db            = new radiusEntities();
                List <RadiusEntry> radiusentries = db.RadiusEntries.ToList();
                foreach (RadiusEntry re in radiusentries)
                {
                    ITikCommand cmd = connection.CreateCommand("/ppp/secret/add",
                                                               connection.CreateParameter("name", re.username),
                                                               connection.CreateParameter("password", re.value),
                                                               connection.CreateParameter("profile", re.groupname));
                    cmd.ExecuteAsync(response =>
                    {
                        // Console.WriteLine("Row: " + response.GetResponseField("tx"));
                    });

                    cmd.Cancel();
                }
                return(true);
            }
        }
Ejemplo n.º 24
0
        public void VeriAl(string svIP, string svKulAdi, string svSifre, int serverId)
        {
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(svIP, svKulAdi, svSifre);

                    var hs = connection.LoadAll <HotspotUser>();

                    foreach (var user in hs)
                    {
                        var kuladi = user.Name;
                        var sifre  = user.Password;
                        //connection.Delete<HotspotUser>(user);
                        // 7 ağustos
                        try
                        {
                            SqlCeConnection baglanti = new SqlCeConnection(@"Data Source=Hotspot.sdf;Persist Security Info=False;");
                            SqlCeCommand    cmd      = new SqlCeCommand();
                            if (baglanti.State == ConnectionState.Closed)
                            {
                                baglanti.Open();
                            }
                            cmd.Connection  = baglanti;
                            cmd.CommandText = "select * from HotspotTBL H , ServerTBL S where H.serverId='" + serverId + "' and H.kullaniciAdi='" + kuladi + "'";
                            cmd.ExecuteNonQuery();
                            SqlCeDataReader dr = cmd.ExecuteReader();
                            if (dr.Read())
                            {
                            }
                            else
                            {
                                dr.Close();//datareader i kapattık
                                saatEkle = TimeSpan.FromDays(365);
                                //KULLANICI EKLEME

                                //gün ve saat ekleme
                                string date = string.Format("{0:yyyy/MM/dd HH:mm:ss}", DateTime.Now.Add(saatEkle));//zamanı gün olarak arttırdık
                                if (baglanti.State == ConnectionState.Closed)
                                {
                                    baglanti.Open();
                                }
                                string       kayit = "insert into HotspotTBL(serverId,kullaniciAdi,sifre,sure) values (@serverId,@kullaniciAdi,@sifre,@sure)";
                                SqlCeCommand komut = new SqlCeCommand(kayit, baglanti);
                                komut.Parameters.AddWithValue("@serverId", serverId);
                                komut.Parameters.AddWithValue("@kullaniciAdi", kuladi);
                                komut.Parameters.AddWithValue("@sifre", sifre);
                                komut.Parameters.AddWithValue("@sure", date);
                                komut.ExecuteNonQuery();
                                baglanti.Close();
                            }
                        }
                        catch (Exception hata)
                        {
                            MessageBox.Show("İşlem Sırasında Hata Oluştu." + hata.Message);
                        }
                        //
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Server bağlantısı başarısız");
            }
        }