locked
Example for RouterOs Connection RRS feed

  • Question

  • User443548635 posted

    Hi
    I've installed on my pc IIS7 and c:/inetpub folder is my web folder. I'd like to connect a Router trough my aspx page, but i don't now how i can do it. I've this example but i don't know basically how i have to do.

    Example code is:

    Public Class Mikrotik
    	Dim tcpStream As IO.Stream
    	Dim tcpCon As New Net.Sockets.TcpClient
    
    	Public Sub New(ByVal ipOrDns As String, Optional ByVal port As Integer = -1)
    		Dim ips = Net.Dns.GetHostEntry(ipOrDns)
    
    		tcpCon.Connect(ips.AddressList(0), If(port = -1, 8728, port))
    		tcpStream = tcpCon.GetStream()
    	End Sub
    
    	Public Sub New(ByVal endP As System.Net.IPEndPoint)
    		tcpCon.Connect(endP)
    		tcpStream = tcpCon.GetStream()
    	End Sub
    
    	Public Sub Close()
    		tcpStream.Close()
    		tcpCon.Close()
    	End Sub
    
    	Public Function Login(ByVal user As String, ByVal pass As String) As Boolean
    		Send("/login", True)
    		Dim hash = Read()(0).Split(New String() {"ret="}, StringSplitOptions.None)(1)
    		Send("/login")
    		Send("=name=" + user)
    		Send("=response=00" + EncodePassword(pass, hash), True)
    		Dim res = Read()
    		If (res(0) = "!done") Then Return True Else Return False
    	End Function
    
    	Function EncodePassword(ByVal pass As String, ByVal challange As String) As String
    		Dim hash_byte(challange.Length / 2 - 1) As Byte
    		For i = 0 To challange.Length - 2 Step 2
    			hash_byte(i / 2) = Byte.Parse(challange.Substring(i, 2), Globalization.NumberStyles.HexNumber)
    		Next
    		Dim response(pass.Length + hash_byte.Length) As Byte
    		response(0) = 0
    		Text.Encoding.ASCII.GetBytes(pass.ToCharArray()).CopyTo(response, 1)
    		hash_byte.CopyTo(response, 1 + pass.Length)
    
    
    		Dim md5 = New System.Security.Cryptography.MD5CryptoServiceProvider()
    
    		Dim hash = md5.ComputeHash(response)
    
    		Dim hashStr As New Text.StringBuilder()
    		For Each h In hash
    			hashStr.Append(h.ToString("x2"))
    		Next
    		Return hashStr.ToString()
    	End Function
    
    	Public Sub Send(ByVal command As String, Optional ByVal EndSentence As Boolean = False)
    		Dim bytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray())
    		Dim size = EncodeLength(bytes.Length)
    
    		tcpStream.Write(size, 0, size.Length)
    		tcpStream.Write(bytes, 0, bytes.Length)
    		If EndSentence Then tcpStream.WriteByte(0)
    	End Sub
    
    	Public Function Read() As List(Of String)
    		Dim output As New List(Of String)
    		Dim o = ""
    		Dim tmp(4) As Byte
    		Dim count As Long
    
    		While True
    			tmp(3) = tcpStream.ReadByte()
    			Select Case tmp(3)
    				Case 0
    					output.Add(o)
    					If o.Substring(0, 5) = "!done" Then
    						Exit While
    					Else
    						o = ""
    						Continue While
    					End If
    				Case Is < &H80
    					count = tmp(3)
    				Case Is < &HC0
    					count = BitConverter.ToInt32(New Byte() {tcpStream.ReadByte(), tmp(3), 0, 0}, 0) ^ &H8000
    				Case Is < &HE0
    					tmp(2) = tcpStream.ReadByte()
    					count = BitConverter.ToInt32(New Byte() {tcpStream.ReadByte(), tmp(2), tmp(3), 0}, 0) ^ &HC00000
    				Case Is < &HF0
    					tmp(2) = tcpStream.ReadByte()
    					tmp(1) = tcpStream.ReadByte()
    					count = BitConverter.ToInt32(New Byte() {tcpStream.ReadByte(), tmp(1), tmp(2), tmp(3)}, 0) ^ &HE0000000
    				Case &HF0
    					tmp(3) = tcpStream.ReadByte()
    					tmp(2) = tcpStream.ReadByte()
    					tmp(1) = tcpStream.ReadByte()
    					tmp(0) = tcpStream.ReadByte()
    					count = BitConverter.ToInt32(tmp, 0)
    				Case Else
    					Exit While	 'err
    			End Select
    
    			For i = 0 To count - 1
    				o += ChrW(tcpStream.ReadByte())
    			Next
    		End While
    		Return output
    	End Function
    
    	Function EncodeLength(ByVal l As Integer) As Byte()
    		If l < &H80 Then
    			Dim tmp = BitConverter.GetBytes(l)
    			Return New Byte() {tmp(0)}
    		ElseIf l < &H4000 Then
    			Dim tmp = BitConverter.GetBytes(l Or &H8000)
    			Return New Byte() {tmp(1), tmp(0)}
    		ElseIf l < &H200000 Then
    			Dim tmp = BitConverter.GetBytes(l Or &HC00000)
    			Return New Byte() {tmp(2), tmp(1), tmp(0)}
    		ElseIf l < &H10000000 Then
    			Dim tmp = BitConverter.GetBytes(l Or &HE0000000)
    			Return New Byte() {tmp(3), tmp(2), tmp(1), tmp(0)}
    		Else
    			Dim tmp = BitConverter.GetBytes(l)
    			Return New Byte() {&HF0, tmp(3), tmp(2), tmp(1), tmp(0)}
    		End If
    	End Function
    End Class



    And ASPX page code (i think is):


    Module Module1 Sub Main() Dim mk = New Mikrotik("mikrotik") If Not mk.Login("admin", "PpAaSsWwOoRrDd") Then Console.WriteLine("Cant log in") mk.Close() Console.ReadLine() Return End If mk.Send("/system/clock/getall", True) For Each row In mk.Read() Console.WriteLine(row) Next Console.ReadLine() End Sub End Module


    Well, what i can do for execute this code? i'dlike call an aspx page that connect me to router (i've to pass command line to router and receive response from it).
    basically what i have to do?
    i work with an web editor page (i can use also notepad)
    where i have to save this page? how i can rename the pages? (mikrotik.vb? mikrotik.class?.....)

    Thank you for any help to me


    Sunday, June 4, 2017 3:30 PM

All replies

  • User991499041 posted

    Hi polparao,

    Well, what i can do for execute this code? i'dlike call an aspx page that connect me to router (i've to pass command line to router and receive response from it).
    basically what i have to do?
    i work with an web editor page (i can use also notepad)
    where i have to save this page? how i can rename the pages? (mikrotik.vb? mikrotik.class?.....)

    This is VB.NET class for connecting and working with Mikrotik API. You could name Mikrotik.vb. A simple way to execute this code is to add click event. The Click event is raised when the Button control is clicked.

    <asp:Button id="Button1"
               Text="Click here for executing..."
               OnClick="ExecutingBtn_Click" 
               runat="server"/>

    Sub ExecutingBtn_Click(ByVal sender As Object, _
                              ByVal e As EventArgs)
    
         ' When the button is clicked,
         ' executing the code.
         Dim mk = New Mikrotik("xxx.xxx.x.x")
            If Not mk.Login('xxx', 'xxx') Then
                Return False
            Else
                Return True
            End If
    
    
     End Sub

    Regards,

    zxj

    Monday, June 5, 2017 2:50 AM
  • User443548635 posted

    Thank you for your reply.

    i'have put the mikrotik.vb file in c:/inetpub/wwwroot/ directory and the file (prova.aspx) in same directory. when i call localhost/vai.aspx i receive this error:

    **************************************************************

    Errore di compilazione

    Descrizione: Errore durante la compilazione di una risorsa necessaria per soddisfare la richiesta. Rivedere i dettagli relativi all'errore e modificare in modo appropriato il codice sorgente.

    Messaggio di errore del compilatore: BC30002: Tipo 'Mikrotik' non definito.

    Errore nel codice sorgente:

    Riga 7:       ' When the button is clicked,
    Riga 8:       ' executing the code.
    Riga 9:       Dim mk = New Mikrotik("192.168.0.2")
    Riga 10:         If Not mk.Login('', '') Then
    Riga 11:             Return False


    File di origine: C:\inetpub\wwwroot\vai.aspx    Riga: 9

    ***********************************************************************
    My vai.aspx file is:

    <%@ Page Language="VB" %>
    <script runat="server">
       Private Sub ExecutingBtn_Click(ByVal sender As Object, _
                              ByVal e As EventArgs)

         ' When the button is clicked,
         ' executing the code.
         Dim mk = New Mikrotik("192.168.0.2")
            If Not mk.Login('', '') Then
                Return False
            Else
                Return True
            End If

     End Sub
        
    </script>

     <html>
    <body> 
    <asp:Button id="Button1"
               Text="Click here for executing..."
               OnClick="ExecutingBtn_Click"
               runat="server"/>
    </body>
    </html>

    what i wrong? i don't understand why i receive this error message (mi router is on 192.168.0.2 and without password)

    Thank you very much for help me

    Pietro

    Monday, June 5, 2017 4:52 PM
  • User991499041 posted

    Hi polparo,

    i'have put the mikrotik.vb file in c:/inetpub/wwwroot/ directory and the file (prova.aspx) in same directory.

    For clarification, are you trying to add this to an already compiled site? If so it won't work, you will need the project and add this page, then re-compile the site.

    <script runat="server">
       Private Sub ExecutingBtn_Click(ByVal sender As Object, _
                              ByVal e As EventArgs)

         ' When the button is clicked,
         ' executing the code.
         Dim mk = New Mikrotik("192.168.0.2")
            If Not mk.Login('', '') Then
                Return False
            Else
                Return True
            End If

     End Sub
        
    </script>

    Please remove these codes from xxx.aspx page, and add it to xxx.aspx.vb.

    The code behind should be something like this

    Public Class WebForm1
    	Inherits System.Web.UI.Page
    
    	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
    	End Sub
    
    	Protected Sub ExecutingBtn_Click(sender As Object, e As EventArgs)
    		' When the button is clicked,
    		' executing the code.
    		Dim mk = New Mikrotik("192.168.0.2")
    
    	End Sub
    End Class

    It works well on my side. If you have any other issue, please feel free let me know.

    Regards,

    zxj

    Tuesday, June 6, 2017 2:08 AM
  • User443548635 posted

    Hi
    Very thank you to help me in this project.

    I write this code in notepad and i put the Mikrotik.vb in c:/inepub/wwwroot/ folder. Then i write vai.aspx, with code that i wrote behind, in the same directory. I don't use a specific software to develope .net because i need only connect me to router to enable/disable router user. I was a ASP programmer but now i need to use ASP.NET (for me all news..).

    Do i have use a software to do this? which software i best? all i need is istructions point point to call an aspx file that control if an user is active or non active, and disable or enable user.

    Thank you very much

    Pietro

    Tuesday, June 6, 2017 4:08 PM
  • User991499041 posted

    Hi Pietro,

    Do i have use a software to do this? which software i best? all i need is istructions point point to call an aspx file that control if an user is active or non active, and disable or enable user.

    Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs for Microsoft Windows, as well as web sites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such as Windows API, Windows Forms, Windows Presentation Foundation, Windows Store and Microsoft Silverlight. It can produce both native code and managed code.

    https://www.visualstudio.com/ 

    Regards,

    zxj

    Wednesday, June 7, 2017 1:49 AM