elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Tutorial básico de Quickjs


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Ayuda con este código !!
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ayuda con este código !!  (Leído 2,226 veces)
TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Ayuda con este código !!
« en: 15 Noviembre 2017, 15:46 pm »

Holas,

Con este codigo puedo hacer una conexión a un servidor SSH y abrir un PORT FORWARDING DYNAMIC asi navegar por ese Tunnel, todo eso trabaja perfecto lo único que necesito implementar es un metodo para que reconnecte en caso de que falle la conexión, hasta ahora logré manejar el evento OnDisconnect y activar un Timer cada 10 segundos pero tengo mis dudas para llamar al Main del Modulo pues cuando genero un error de conexión el se queda esperando en la consola a que se presione ESC para entonces ejecutar

Código
  1. client.Disconnect(New ProgressHandler)

y

terminar con

Código
  1. SshNet.Shutdown()

supongo que primero tengo que cerrar bien la conexion osea ejecutar esas lineas antes de volver a llamar al Main quizas declarandolas como global y ejecutarlas en el manejador seria la solución?

Saludos y gracias cualquier ayuda...

Código
  1. Imports Bitvise.FlowSshNet
  2.  
  3.  
  4. Public Enum ExitCodes
  5.    Success = 0
  6.    UsageError = 1
  7.    SessionError = 2
  8.    FatalError = 3
  9. End Enum
  10.  
  11. Public Enum DisconnectReason
  12.    Exception = 0
  13.    FlowError = 1
  14.    ConnectionError = 2
  15.    ConnectionLost = 3
  16.    ByServer = 4
  17.    ByClient = 5
  18. End Enum
  19.  
  20. Public Class MyClient
  21.    Inherits Client
  22.  
  23.  
  24.    Dim aTimer As New System.Timers.Timer
  25.  
  26.    Private Sub tick(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
  27.        aTimer.Stop()
  28.        FlowSshNet_VbTnl.Main()
  29.    End Sub
  30.  
  31.    Public Sub New()
  32.        AddHandler OnHostKey, AddressOf OnMyHostKey
  33.        AddHandler OnForwardingLog, AddressOf OnMyForwardingLog
  34.        AddHandler OnDisconnect, AddressOf OnMyDisconnect
  35.  
  36.        AddHandler aTimer.Elapsed, AddressOf tick
  37.    End Sub
  38.  
  39.    Sub Main()
  40.        aTimer.AutoReset = True
  41.        aTimer.Interval = 10000 '10 seconds
  42.    End Sub
  43.  
  44.    Public Sub OnMyDisconnect(ByVal sender As Object, ByVal reason As DisconnectReason, ByVal desc As String)
  45.        aTimer.Start()
  46.  
  47.    End Sub
  48.  
  49.    Public Function OnMyHostKey(ByVal sender As Object, ByVal publicKey As PublicKey) As Boolean
  50.        Console.WriteLine("Received the following host key: ")
  51.        Console.WriteLine("  MD5 Fingerprint: {0}", publicKey.GetMd5())
  52.        Console.WriteLine("  Bubble-Babble: {0}", publicKey.GetBubbleBabble())
  53.        Console.WriteLine("  SHA-256: {0}", publicKey.GetSha256())
  54.        Return True
  55.    End Function
  56.  
  57.    Public Sub OnMyForwardingLog(ByVal sender As Object, ByVal log As ForwardingLog)
  58.        Console.WriteLine(log.Desc)
  59.    End Sub
  60.  
  61. End Class
  62.  
  63.  
  64. Module FlowSshNet_VbTnl
  65.  
  66.    Sub OnUncaughtExceptionInEvent(ByVal sender As Object, ByVal fatal As Boolean, ByVal e As System.Exception)
  67.        Console.WriteLine("Error: {0}", e.ToString())
  68.        Environment.Exit(ExitCodes.FatalError)
  69.    End Sub
  70.  
  71.    Function Main() As Integer
  72.        Try
  73.  
  74.            AddHandler SshNet.OnExceptionInEvent, AddressOf OnUncaughtExceptionInEvent
  75.  
  76.            Dim client As MyClient = New MyClient
  77.            client.SetAppName("FlowSshNet_VbTnl")
  78.            client.SetHost("1.1.1.1")
  79.            client.SetPort(22)
  80.            client.SetUserName("user")
  81.            client.SetPassword("password")
  82.  
  83.            client.SetProxyType(ProxyType.HttpConnect)
  84.            client.SetProxyHost("1.1.1.5")
  85.            client.SetProxyPort("8080")
  86.            client.SetProxyUserName("userproxy")
  87.            client.SetProxyPassword("userpass")
  88.  
  89.            Dim progress As ProgressHandler = New ProgressHandler
  90.            client.Connect(progress)
  91.            progress.WaitDone()
  92.  
  93.            If Not progress.Success() Then
  94.                Dim connectStep As UInt32 = progress.GetTaskSpecificStep()
  95.                Dim auxInfo As String = progress.GetAuxInfo()
  96.                Dim connErr As String = ProgressHandler.DescribeConnectError(connectStep, auxInfo)
  97.                Console.WriteLine("{0}", connErr)
  98.            Else
  99.  
  100.                Dim proxy As ProxyForwarding = New ProxyForwarding
  101.                proxy.ListInterface = "127.0.0.1"
  102.                proxy.ListPort = 1080
  103.  
  104.                Dim enableProxyHandler As ForwardingHandler = New ForwardingHandler
  105.                client.EnableProxyForwarding(proxy, enableProxyHandler)
  106.  
  107.                enableProxyHandler.WaitDone()
  108.                If (enableProxyHandler.Success()) Then
  109.                    Console.WriteLine("Proxy forwarding enabled, listening port: {0}", enableProxyHandler.GetListPort().ToString())
  110.                Else
  111.                    Console.WriteLine("Error enabling proxy forwarding: {0}", enableProxyHandler.GetError().Desc)
  112.                End If
  113.  
  114.                Console.WriteLine("Press Esc to stop forwarding")
  115.                While Console.ReadKey(True).Key <> ConsoleKey.Escape
  116.                End While
  117.  
  118.                If (enableProxyHandler.Success()) Then
  119.                    Dim handler As ForwardingHandler = New ForwardingHandler
  120.                    client.DisableProxyForwarding(handler)
  121.  
  122.                    handler.WaitDone()
  123.                    If (handler.Success()) Then
  124.                        Console.WriteLine("Proxy forwarding disabled")
  125.                    Else
  126.                        Console.WriteLine("Error disabling proxy forwarding: {0}", handler.GetError().Desc)
  127.                    End If
  128.                End If
  129.  
  130.                client.Disconnect(New ProgressHandler)
  131.  
  132.                Console.WriteLine("Press Esc to exit")
  133.                While Console.ReadKey(True).Key <> ConsoleKey.Escape
  134.                End While
  135.  
  136.            End If
  137.  
  138.        Catch e As System.Exception
  139.            Console.WriteLine(e.Message)
  140.            Return ExitCodes.FatalError
  141.        Finally
  142.            SshNet.Shutdown()
  143.        End Try
  144.  
  145.        Return ExitCodes.Success
  146.    End Function
  147.  
  148. End Module
  149.  
  150.  


En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Ayuda con este código !! Conexión SSH !!
« Respuesta #1 en: 15 Noviembre 2017, 17:25 pm »

Ok lo solucioné  :xD :xD :xD ;-) ;-) ;-) ;-)

Aquí esta como lo hice, imagino esta chapuza diganme la forma correcta....

Estuve tratando de migrarlo para una aplicación Form y tuve varios problemas a la hora de capturar los datos del servidor, parece que la clase principal espera entregar esos datos a una consola, alguna idea....

Nota: La libreria es libre siempre y cuando se respete los acuerdos del autor la pueden descargar de http://www.bitvise.com busquen SshLibrary


Código
  1. Imports System.Threading
  2. Imports Bitvise.FlowSshNet
  3.  
  4.  
  5. Public Enum ExitCodes
  6.    Success = 0
  7.    UsageError = 1
  8.    SessionError = 2
  9.    FatalError = 3
  10. End Enum
  11.  
  12. Public Enum DisconnectReason
  13.    Exception = 0
  14.    FlowError = 1
  15.    ConnectionError = 2
  16.    ConnectionLost = 3
  17.    ByServer = 4
  18.    ByClient = 5
  19. End Enum
  20.  
  21. Public Class MyClient
  22.    Inherits Client
  23.  
  24.    Public Sub New()
  25.        AddHandler OnHostKey, AddressOf OnMyHostKey
  26.        AddHandler OnForwardingLog, AddressOf OnMyForwardingLog
  27.    End Sub
  28.  
  29.    Public Function OnMyHostKey(ByVal sender As Object, ByVal publicKey As PublicKey) As Boolean
  30.        Console.WriteLine("Received the following host key: ")
  31.        Console.WriteLine("  MD5 Fingerprint: {0}", publicKey.GetMd5())
  32.        Console.WriteLine("  Bubble-Babble: {0}", publicKey.GetBubbleBabble())
  33.        Console.WriteLine("  SHA-256: {0}", publicKey.GetSha256())
  34.        Return True
  35.    End Function
  36.  
  37.    Public Sub OnMyForwardingLog(ByVal sender As Object, ByVal log As ForwardingLog)
  38.        Console.WriteLine(log.Desc)
  39.    End Sub
  40.  
  41. End Class
  42.  
  43.  
  44. Module FlowSshNet_VbTnl
  45.  
  46.    Dim client As MyClient = New MyClient
  47.    Dim progress As ProgressHandler
  48.  
  49.    Sub OnUncaughtExceptionInEvent(ByVal sender As Object, ByVal fatal As Boolean, ByVal e As System.Exception)
  50.        Console.WriteLine("Error: {0}", e.ToString())
  51.        Environment.Exit(ExitCodes.FatalError)
  52.    End Sub
  53.  
  54.    Public Sub OnMyDisconnect(ByVal sender As Object, ByVal reason As DisconnectReason, ByVal desc As String)
  55.        If reason <> 5 Then     'Exepto cuando sea una desconexión voluntaria, reconecto...
  56.            Console.WriteLine("Reconectando...")
  57.  
  58.            Reconectar()     'Espero 10 segundos
  59.        End If
  60.    End Sub
  61.  
  62.    Sub New()
  63.        AddHandler SshNet.OnExceptionInEvent, AddressOf OnUncaughtExceptionInEvent
  64.        AddHandler client.OnDisconnect, AddressOf OnMyDisconnect
  65.    End Sub
  66.  
  67.    Function Main() As Integer
  68.        Try
  69.  
  70.            If IsNothing(client) Then
  71.                client = New MyClient
  72.            End If
  73.  
  74.            client.SetAppName("FlowSshNet_VbTnl")
  75.            client.SetHost("1.1.1.1")
  76.            client.SetPort(22)
  77.            client.SetUserName("user")
  78.            client.SetPassword("pass")
  79.  
  80.            client.SetProxyType(ProxyType.HttpConnect)
  81.            client.SetProxyHost("1.1.1.5")
  82.            client.SetProxyPort("8080")
  83.            client.SetProxyUserName("userproxy")
  84.            client.SetProxyPassword("proxypass")
  85.  
  86.            progress = New ProgressHandler
  87.            client.Connect(progress)
  88.            progress.WaitDone()
  89.  
  90.            If Not progress.Success() Then
  91.                Dim connectStep As UInt32 = progress.GetTaskSpecificStep()
  92.                Dim auxInfo As String = progress.GetAuxInfo()
  93.                Dim connErr As String = ProgressHandler.DescribeConnectError(connectStep, auxInfo)
  94.                Console.WriteLine("{0}", connErr)
  95.  
  96.                Reconectar()
  97.  
  98.            Else
  99.  
  100.                Dim proxy As ProxyForwarding = New ProxyForwarding
  101.                proxy.ListInterface = "127.0.0.1"
  102.                proxy.ListPort = 1080
  103.  
  104.                Dim enableProxyHandler As ForwardingHandler = New ForwardingHandler
  105.                client.EnableProxyForwarding(proxy, enableProxyHandler)
  106.  
  107.                enableProxyHandler.WaitDone()
  108.                If (enableProxyHandler.Success()) Then
  109.                    Console.WriteLine("Proxy forwarding enabled, listening port: {0}", enableProxyHandler.GetListPort().ToString())
  110.                Else
  111.                    Console.WriteLine("Error enabling proxy forwarding: {0}", enableProxyHandler.GetError().Desc)
  112.                End If
  113.  
  114.                Console.WriteLine("Press Esc to stop forwarding")
  115.                While Console.ReadKey(True).Key <> ConsoleKey.Escape
  116.                End While
  117.  
  118.                If (enableProxyHandler.Success()) Then
  119.                    Dim handler As ForwardingHandler = New ForwardingHandler
  120.                    client.DisableProxyForwarding(handler)
  121.  
  122.                    handler.WaitDone()
  123.                    If (handler.Success()) Then
  124.                        Console.WriteLine("Proxy forwarding disabled")
  125.                    Else
  126.                        Console.WriteLine("Error disabling proxy forwarding: {0}", handler.GetError().Desc)
  127.                    End If
  128.                End If
  129.  
  130.                client.Disconnect(New ProgressHandler)
  131.  
  132.            End If
  133.  
  134.        Catch e As System.Exception
  135.            Console.WriteLine(e.Message)
  136.            Return ExitCodes.FatalError
  137.        Finally
  138.            SshNet.Shutdown()
  139.        End Try
  140.  
  141.        Return ExitCodes.Success
  142.    End Function
  143.  
  144.    Sub Reconectar()
  145.  
  146.        Dim cursT As Integer
  147.        Dim cursL As Integer
  148.        cursT = Console.CursorTop
  149.        cursL = Console.CursorLeft
  150.        Const countDownFrom As Integer = 10
  151.        Dim cdfW As Integer = countDownFrom.ToString.Length + 1
  152.        For x As Integer = countDownFrom To 0 Step -1
  153.            Console.SetCursorPosition(cursL, cursT)
  154.            Console.Write(x.ToString.PadLeft(cdfW, " "c))
  155.            Thread.Sleep(1000) 'for example only
  156.        Next
  157.  
  158.        client.Disconnect(New ProgressHandler)
  159.  
  160.        progress = Nothing
  161.  
  162.        client = Nothing
  163.  
  164.        Main()
  165.  
  166.    End Sub
  167.  
  168. End Module
  169.  


« Última modificación: 15 Noviembre 2017, 17:32 pm por TrashAmbishion » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Ayuda con este codigo
Programación Visual Basic
5v5 2 2,739 Último mensaje 31 Mayo 2005, 22:56 pm
por 5v5
ayuda con este codigo
Programación Visual Basic
<housedir> 3 2,129 Último mensaje 17 Noviembre 2007, 03:05 am
por mos-k
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines