Ejemplo n.º 1
0
        protected void Act()
        {
            _forwardedPort.Stop();

            _stopwatch.Stop();
            _elapsedTimeOfStop = _stopwatch.Elapsed;
        }
Ejemplo n.º 2
0
        public T executeQuery <T>(Func <T> executeMySqlQuery)
        {
            T t = default(T);

            try
            {
                using (SshClient client = new SshClient(conn))
                {
                    client.Connect();
                    ForwardedPortLocal port = new ForwardedPortLocal("127.0.0.1", 22, "13.94.138.165", 3306);

                    client.AddForwardedPort(port);
                    port.Start();

                    t = executeMySqlQuery();

                    port.Stop();

                    client.Disconnect();
                }

                return(t);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("ERROR caught in SSH.cs");
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 3
0
        public void Disconnect()
        {
            _connected = false;

            if (Browsers.Explorer.BackupExists)
            {
                Browsers.Explorer.Revert();
            }

            if (Browsers.Firefox.BackupExists)
            {
                Browsers.Firefox.Revert();
            }

            if (_shell != null)
            {
                _shell.Stop();
            }

            if (_forwardedPort != null)
            {
                _forwardedPort.Stop();
            }

            if (_ssh != null)
            {
                _ssh.Disconnect();
            }

            _keyStream.CloseIfNotNull();

            _inStream.CloseIfNotNull();

            _outStream.CloseIfNotNull();
        }
        protected void Arrange()
        {
            var random = new Random();

            _closingRegister = new List<EventArgs>();
            _exceptionRegister = new List<ExceptionEventArgs>();
            _localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122);
            _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"),
                random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));

            _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);

            _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port);
            _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Stop();

            _closingRegister.Clear();
        }
        private async Task <SshClient> CreateSshClient()
        {
            AuthenticationMethod auth = providerConfig.SshAuthentication.AuthenticationMethod switch
            {
                SshAuthenticationConfig.AuthenticationType.Password => new PasswordAuthenticationMethod(providerConfig.SshAuthentication.Username, providerConfig.SshAuthentication.AuthenticationSecret),
                SshAuthenticationConfig.AuthenticationType.PrivateKeyFile => new PrivateKeyAuthenticationMethod(providerConfig.SshAuthentication.Username, new PrivateKeyFile(providerConfig.SshAuthentication.AuthenticationSecret)),
                _ => throw new NotSupportedException("The given authentication method is not supported."),
            };
            var client = new SshClient(new ConnectionInfo(providerConfig.SshHost, providerConfig.SshPort, providerConfig.SshAuthentication.Username, auth));

            // looks like there's no ConnectAsync
            await Task.Run(() => client.Connect());

            var portFwd = new ForwardedPortLocal("127.0.0.1", "127.0.0.1", providerConfig.RconPort);

            client.AddForwardedPort(portFwd);

            portFwd.Exception += (o, e) => { portFwd.Stop(); client.Disconnect(); };

            portFwd.Start();

            localRconPort = (ushort)portFwd.BoundPort;

            // TODO nicer error and disconnect handling
            return(client);
        }
        protected void Arrange()
        {
            var random = new Random();

            _closingRegister   = new List <EventArgs>();
            _exceptionRegister = new List <ExceptionEventArgs>();
            _localEndpoint     = new IPEndPoint(IPAddress.Loopback, 8122);
            _remoteEndpoint    = new IPEndPoint(IPAddress.Parse("193.168.1.5"),
                                                random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));

            _connectionInfoMock = new Mock <IConnectionInfo>(MockBehavior.Strict);
            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _channelMock        = new Mock <IChannelDirectTcpip>(MockBehavior.Strict);

            _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);

            _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port,
                                                    _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port);
            _forwardedPort.Closing   += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session    = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Stop();

            _closingRegister.Clear();
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // 踏み台サーバのホスト名
            string bastionServer = "XXXXXXXXXX";
            // 踏み台サーバのアカウント名
            string userName = "******";
            // 踏み台サーバのパスワード
            string password = "******";

            ConnectionInfo info = new ConnectionInfo(bastionServer, 22, userName,
                                                     new AuthenticationMethod[] {
                new PasswordAuthenticationMethod(userName, password)
            }
                                                     );

            // SQL Server 接続文字列
            string connectionString = @"Data Source=127.0.0.1;Integrated Security=False;User ID=XXXXXXXXXX;Password=XXXXXXXXXX";
            // データベースサーバのホスト名
            string dbServer = "XXXXXXXXXX";

            using (var client = new SshClient(info))
            {
                client.Connect();
                var forward = new ForwardedPortLocal("127.0.0.1", 1433, dbServer, 1433);
                client.AddForwardedPort(forward);
                forward.Start();
                using (var connection = new SqlConnection(connectionString))
                {
                    using (var command = connection.CreateCommand())
                    {
                        try
                        {
                            connection.Open();

                            command.CommandText = @"SELECT count(*) AS count FROM employee";

                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                DataTable table = new DataTable();
                                table.Load(reader);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception.Message);
                            throw;
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                    forward.Stop();
                }
            }
        }
Ejemplo n.º 8
0
        public void StopTest()
        {
            uint               boundPort = 0;                                             // TODO: Initialize to an appropriate value
            string             host      = string.Empty;                                  // TODO: Initialize to an appropriate value
            uint               port      = 0;                                             // TODO: Initialize to an appropriate value
            ForwardedPortLocal target    = new ForwardedPortLocal(boundPort, host, port); // TODO: Initialize to an appropriate value

            target.Stop();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
 protected void Act()
 {
     try
     {
         _forwardedPort.Stop();
         Assert.Fail();
     }
     catch (ObjectDisposedException ex)
     {
         _actualException = ex;
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Post CheckIn hacia MySQL Server
        /// </summary>
        /// <param name="matricula">folio certificado</param>
        /// <param name="rfc">rfc usaurio</param>
        /// <returns></returns>
        public static bool PostCheckIn(string matricula, string rfc)
        {
            bool insertado = false;

            try
            {
                //Open SSH tunnel
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ssh_ip, ssh_port, ssh_user, ssh_password);
                using (var client = new SshClient(connectionInfo))
                {
                    client.Connect();
                    if (client.IsConnected)
                    {
                        //Agregar puerto de escucha
                        var portForwarded = new ForwardedPortLocal(mysql_host, mysql_port, mysql_host, mysql_port);
                        client.AddForwardedPort(portForwarded);
                        portForwarded.Start();
                        using (var mysql_Con = new MySqlConnection("host=" + mysql_host + ";user="******";password=\"" + mysql_password + "\";database=" + mysql_db))
                            using (var mysql_cmd = mysql_Con.CreateCommand())
                            {
                                //Get data info
                                mysql_Con.Open();
                                mysql_cmd.CommandText = "INSERT INTO mProcesoEntrega (mpe_fechareg, mc_matrnu, mpe_rfcfigura, st_id) " +
                                                        "VALUES (@FECHA, @MATRICULA, @RFC, @STATUS)";
                                mysql_cmd.Parameters.Add("@FECHA", System.DateTime.Now.ToLongDateString());
                                mysql_cmd.Parameters.Add("@MATRICULA", matricula);
                                mysql_cmd.Parameters.Add("@RFC", rfc);
                                mysql_cmd.Parameters.Add("@STATUS", 9);
                                mysql_cmd.CommandType = CommandType.Text;
                                //Reportar inserción
                                insertado = (mysql_cmd.ExecuteNonQuery() > 0) ? true : false;
                                //Cerrar conexiones
                                mysql_Con.Close();
                                portForwarded.Stop();
                                client.Disconnect();
                            }
                    }
                    else
                    {
                        insertado = false;
                    }
                }
            }
            catch
            {
                insertado = false;
            }
            return(insertado);
        }
Ejemplo n.º 11
0
        private void SshConnect(string useremail, string userpassword)
        {
            string username = "******";
            string password = "******";
            string host     = "server226.web-hosting.com";
            int    port     = 21098;

            using (var client = new SshClient(host, port, username, password))
            {
                client.Connect();
                var tunnel = new ForwardedPortLocal("127.0.0.1", 21098, "127.0.0.1", 3306);
                client.AddForwardedPort(tunnel);
                tunnel.Start();
                TryToConnectDatabase(useremail, userpassword);
                TryToGetMacs(id);
                tunnel.Stop();
                client.Disconnect();
            }
        }
Ejemplo n.º 12
0
        public void Test_ForwardedPortRemote()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshClient AddForwardedPort Start Stop ForwardedPortLocal
                client.Connect();
                var port = new ForwardedPortLocal(8082, "www.cnn.com", 80);
                client.AddForwardedPort(port);
                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.Start();

                Thread.Sleep(1000 * 60 * 20); //	Wait 20 minutes for port to be forwarded

                port.Stop();
                #endregion
            }
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 13
0
 protected void Act()
 {
     _forwardedPort.Stop();
 }
Ejemplo n.º 14
0
        public void Test_PortForwarding_Local_Stop_Hangs_On_Wait()
        {
            using (var client = new SshClient(Resources.HOST, Int32.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

                var port1 = new ForwardedPortLocal("localhost", 8084, "www.google.com", 80);
                client.AddForwardedPort(port1);
                port1.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Assert.Fail(e.Exception.ToString());
                };

                port1.Start();

                bool hasTestedTunnel = false;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
                {
                    try
                    {
                        var url = "http://www.google.com/";
                        Debug.WriteLine("Starting web request to \"" + url + "\"");
                        HttpWebRequest request   = (HttpWebRequest)HttpWebRequest.Create(url);
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        Assert.IsNotNull(response);

                        Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString());

                        response.Close();

                        hasTestedTunnel = true;
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail(ex.ToString());
                    }
                });

                // Wait for the web request to complete.
                while (!hasTestedTunnel)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                try
                {
                    // Try stop the port forwarding, wait 3 seconds and fail if it is still started.
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
                    {
                        Debug.WriteLine("Trying to stop port forward.");
                        port1.Stop();
                        Debug.WriteLine("Port forwarding stopped.");
                    });

                    System.Threading.Thread.Sleep(3000);
                    if (port1.IsStarted)
                    {
                        Assert.Fail("Port forwarding not stopped.");
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.ToString());
                }
                client.Disconnect();
                Debug.WriteLine("Success.");
            }
        }
Ejemplo n.º 15
0
 public static void Dispose()
 {
     portForwarded.Stop();
     client.Disconnect();
     client.Dispose();
 }
 public void StopTunneling()
 {
     _forwardedPortLocal.Stop();
     _connected = false;
 }
Ejemplo n.º 17
0
        public void Run()
        {
            try
            {
                using (var sshClient = GetSshClient())
                {
                    bool ended = false;
                    try
                    {
                        sshClient.Connect();

                        int  triesLeft = Retries;
                        bool success   = false;
                        do
                        {
                            ProxyPort = GetPort();
                            triesLeft--;
                            try
                            {
                                using (var forwardedPortLocal = new ForwardedPortLocal(ProxyServer, (uint)ProxyPort, this.Server, (uint)Port))
                                {
                                    sshClient.AddForwardedPort(forwardedPortLocal);
                                    try
                                    {
                                        forwardedPortLocal.Start();

                                        // proxy has started
                                        lock (_usageLock)
                                        {
                                            _isStarted       = true;
                                            _isRunning       = true;
                                            _numCurrentUsers = 0;
                                        }

                                        // signal started
                                        _startedWaitEvent.Set();

                                        // keep alive while running is set to true
                                        while (_isRunning)
                                        {
                                            Thread.Sleep(PollInterval);

                                            lock (_usageLock)
                                            {
                                                TimeSpan timeSinceLastUsed = DateTime.Now - _lastUsed;
                                                // if it's under the min lifetime let it stay alive
                                                // if its other the timeout, kill it regardless
                                                // if its in between check if anybody is using it.
                                                if (sshClient.IsConnected == false)
                                                {
                                                    _isRunning = false;
                                                }
                                                else if (timeSinceLastUsed < MinAliveTime)
                                                {
                                                    _isRunning = true;
                                                }
                                                else if (Timeout <= timeSinceLastUsed)
                                                {
                                                    _isRunning = false;
                                                }
                                                else
                                                {
                                                    _isRunning = _numCurrentUsers > 0;
                                                }

                                                if (_isRunning == false)
                                                {
                                                    ended = true;
                                                }
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        throw;
                                    }
                                    finally
                                    {
                                        lock (_usageLock)
                                        {
                                            _isRunning = false;
                                        }
                                        if (forwardedPortLocal != null && forwardedPortLocal.IsStarted)
                                        {
                                            forwardedPortLocal.Stop();
                                        }
                                    }
                                }
                            }
                            catch (SocketException e)
                            {
                                if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
                                {
                                    success = false;
                                }
                                else
                                {
                                    Error = e.Message;
                                }
                            }
                        } while (success == false && triesLeft > 0 && ended == false);
                    }
                    catch (SocketException e)
                    {
                        switch (e.SocketErrorCode)
                        {
                        case SocketError.TimedOut: Error = "Connection timed out."; break;

                        case SocketError.AccessDenied: Error = "Access denied."; break;

                        case SocketError.HostNotFound: Error = string.Format("Host='{0}' could not be found.", Server); break;

                        default: Error = e.Message; break;
                        }
                    }
                    catch (SshException e)
                    {
                        if (e.Message == "User cannot be authenticated." || e.Message == "No suitable authentication method found to complete authentication.")
                        {
                            Error = string.Format("Access denied for user='******'.", SshCredentials.Username);
                        }
                        else
                        {
                            Error = e.Message;
                        }
                    }
                    catch (Exception e)
                    {
                        //Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                        Error = "An unexpected error occurred: " + e;
                    }
                    finally
                    {
                        if (sshClient != null && sshClient.IsConnected)
                        {
                            sshClient.Disconnect();
                        }
                    }
                }
            }
            catch
            {
                Error = "An unexpected error occurred.";
            }
            finally
            {
                // signal started
                _startedWaitEvent.Set();
                SSHProxyManager.RemoveProxy(this);
            }
        }
Ejemplo n.º 18
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            iSFtp = new SftpClient(txtSFtpIP.Text, Convert.ToInt32(numUpDownSFtpPort.Value), txtSFtpUsername.Text, txtSFtpPassword.Text);

            try {
                iSFtp.Connect();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                iSFtp.Dispose();
                iSFtp = null;

                FlashState();
                return;
            }

            if (checkBoxUseSSH.Checked)
            {
                // Setup SSH connection.
                iSSHClient = new SshClient(txtSSHTunnelIP.Text, Convert.ToInt32(numUpDownSSHTunnelPort.Value), txtSSHTunnelUsername.Text, txtSSHTunnelPassword.Text);

                try {
                    iSSHClient.Connect();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    iSSHClient.Dispose();
                    iSSHClient = null;

                    iSFtp.Disconnect();
                    iSFtp.Dispose();
                    iSFtp = null;

                    FlashState();
                    return;
                }

                // Setup port forwarding.
                iSSHTunnel = new ForwardedPortLocal("127.0.0.1", 0, txtDBIP.Text, Convert.ToUInt32(numUpDownDBPort.Value));
                iSSHClient.AddForwardedPort(iSSHTunnel);

                try {
                    iSSHTunnel.Start();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    iSSHClient.RemoveForwardedPort(iSSHTunnel);

                    iSSHTunnel.Dispose();
                    iSSHTunnel = null;

                    iSSHClient.Disconnect();
                    iSSHClient.Dispose();
                    iSSHClient = null;

                    iSFtp.Disconnect();
                    iSFtp.Dispose();
                    iSFtp = null;

                    FlashState();
                    return;
                }
            } // End if(checkBoxUseSSH.Checked)

            MySqlConnectionStringBuilder connStrBuilder = new MySqlConnectionStringBuilder();

            connStrBuilder.Server   = checkBoxUseSSH.Checked ? iSSHTunnel.BoundHost : txtDBIP.Text;
            connStrBuilder.Port     = checkBoxUseSSH.Checked ? iSSHTunnel.BoundPort : Convert.ToUInt32(numUpDownDBPort.Value);
            connStrBuilder.UserID   = txtDBUsername.Text;
            connStrBuilder.Password = txtDBPassword.Text;

            MysqlConn = new MySqlConnection(connStrBuilder.GetConnectionString(true));

            try {
                MysqlConn.Open();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                MysqlConn.Dispose();
                MysqlConn = null;

                if (checkBoxUseSSH.Checked)
                {
                    iSSHTunnel.Stop();

                    iSSHClient.RemoveForwardedPort(iSSHTunnel);

                    iSSHTunnel.Dispose();
                    iSSHTunnel = null;

                    iSSHClient.Disconnect();
                    iSSHClient.Dispose();
                    iSSHClient = null;
                }

                iSFtp.Disconnect();
                iSFtp.Dispose();
                iSFtp = null;

                FlashState();
                return;
            }

            // Connect Done.
            Connected = true;
            FlashState();
        }
Ejemplo n.º 19
0
        static void test()
        {
            PrivateKeyFile rsa = new PrivateKeyFile(@"E:\ftproot\ftpuser\www\ssh\OpenSSH\id_rsa_20160203");

            using (var client = new SshClient("150.63.64.101", "NMTCRMFTP", rsa))
            {
                client.Connect();
                Console.WriteLine("client.Connect()");
                var port = new ForwardedPortLocal("localhost", 60001, "150.63.64.101", 22);
                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.RequestReceived += delegate(object sender, PortForwardEventArgs e)
                {
                    Console.WriteLine(string.Format("Port request recieved from {0} : {1}", e.OriginatorHost, e.OriginatorPort));
                };

                client.AddForwardedPort(port);

                //port.Exception += delegate(object sender, ExceptionEventArgs e)
                //{
                //    Console.WriteLine(e.Exception.ToString());
                //};
                port.Start();
                Console.WriteLine("port.Start()");
                // ... hold the port open ... //

                //// create ssh forwarded client on Server2
                //var client2 = new SshClient("localhost:60001", "NMTCRMFTP04", rsa);
                ////client2.ErrorOccurred += _sshclient_ErrorOccurred;
                ////client2.HostKeyReceived += _sshclient_HostKeyReceived;

                //client2.Connect();

                //// Setup Credentials and Server Information
                //ConnectionInfo ConnNfo = new ConnectionInfo("localhost", 60001, "NMTCRMFTP04",
                //    new AuthenticationMethod[]{


                //// Key Based Authentication (using keys in OpenSSH Format)
                //new PrivateKeyAuthenticationMethod("username",rsa)
                //}
                //);

                //// Upload A File
                //using (var sftp = new SftpClient(client.ConnectionInfo))
                //{

                //    //var uploadfn = @"E:\ftproot\ftpuser\www\ssh\OpenSSH\Debug\Debug\NPPRSI001_20171020112153.DAT";


                //    sftp.Connect();
                //    Console.WriteLine("sftp.Connect()");

                //    Console.WriteLine(sftp.WorkingDirectory.ToArray());


                //    sftp.ChangeDirectory("/export/ftpdata1/ESB01/nmtcrmftp04");
                //    Console.WriteLine("sftp.ChangeDirectory()");

                //    //using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
                //    //{
                //    //    sftp.UploadFile(uplfileStream, uploadfn, true);
                //    //    Console.WriteLine("sftp.UploadFile()");
                //    //}

                //    sftp.Disconnect();
                //    Console.WriteLine("sftp.Disconnect()");
                //}

                port.Stop();
                Console.WriteLine("port.Stop()");
                client.Disconnect();
                Console.WriteLine("port.Disconnect()");
            }



            //using (var client = new SshClient("150.63.64.101",22, "NMTCRMFTP", rsa))
            //{
            //    client.Connect();

            //    // Forward the SSH-Port of Device via Server1 on the Desktop-Machine
            //    var port1 = new ForwardedPortLocal("localhost", 60001, "localhost", 22);
            //    port1.Exception += delegate(object sender, ExceptionEventArgs e)
            //    {
            //        Console.WriteLine(e.Exception.ToString());
            //    };
            //    port1.RequestReceived += delegate(object sender, PortForwardEventArgs e)
            //    {
            //        Console.WriteLine(string.Format("Port request recieved from {0} : {1}", e.OriginatorHost, e.OriginatorPort));


            //    };
            //    client.AddForwardedPort(port1);


            //    port1.Start();

            //    // create ssh forwarded client on Server2
            //    var client2 = new SshClient("localhost:60001","NMTCRMFTP04", rsa);
            //    //client2.ErrorOccurred += _sshclient_ErrorOccurred;
            //    //client2.HostKeyReceived += _sshclient_HostKeyReceived;

            //    client2.Connect();



            //}


            Console.ReadLine();
        }
Ejemplo n.º 20
0
        public static void Main(string[] args)
        {
            Output.Writeline("");
            if (!Output.ParseArguments(args))
            {
                Environment.Exit(0);
            }

            List <string> errors = new List <string>();

            if (String.IsNullOrEmpty(Config.DbHost))
            {
                errors.Add("  --mysqlhost");
            }

            if (String.IsNullOrEmpty(Config.DbUsername))
            {
                errors.Add("  --mysqluser");
            }

            if (String.IsNullOrEmpty(Config.DbPassword))
            {
                errors.Add("  --mysqlpass");
            }

            if (String.IsNullOrEmpty(Config.TunnelHost))
            {
                errors.Add("  --tunnelhost");
            }

            if (String.IsNullOrEmpty(Config.TunnelUsername))
            {
                errors.Add("  --tunneluser");
            }

            if (String.IsNullOrEmpty(Config.TunnelPassword))
            {
                errors.Add("  --tunnelpass");
            }

            if (String.IsNullOrEmpty(Config.OutputFile))
            {
                errors.Add("  --outputfile");
            }

            if (String.IsNullOrEmpty(Config.DbDatabase))
            {
                errors.Add("  --mysqldb");
            }

            if (errors.Count > 0)
            {
                Output.Write("Error: missing one or more required parameters:\n{0}", String.Join("\n", errors));
                Console.WriteLine("");
                Console.WriteLine("\nUse --help to display information about availible arguments.");
                Environment.Exit(1);
            }

            running = true;

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                running = false;
            };

            Console.WriteLine(" + Establishing connection to " + Config.TunnelHost);

            try
            {
                using (client = new SshClient(Config.TunnelHost, Config.TunnelUsername, Config.TunnelPassword))
                {
                    //client.KeepAliveInterval = new TimeSpan(0, 0, 0, 20);
                    //client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 5);

                    client.Connect();

                    Console.WriteLine(" + Forwarding connection " + Config.DbHost + ":" + Config.DbPort + " -> " + Config.TunnelBindHost + ":" + Config.TunnelPort);

                    using (var port = new ForwardedPortLocal(Config.TunnelBindHost, Config.TunnelPort, Config.DbHost, Config.DbPort))
                    {
                        port.Exception += delegate(object sender, ExceptionEventArgs e)
                        {
                            //Output.Writeline("   Error: " + e.Exception.Message);
                        };

                        client.AddForwardedPort(port);

                        port.Start();

                        Console.WriteLine(" + Connecting to MySQL " + Config.TunnelBindHost + ":" + Config.TunnelPort);

                        string connectionString = "server=" + Config.TunnelBindHost + ";AllowZeroDateTime=true;ConvertZeroDateTime=true;port=" + Config.TunnelPort + ";user="******";pwd=" + Config.DbPassword + ";database=" + Config.DbDatabase + ";charset=utf8;";
                        using (MySqlConnection conn = new MySqlConnection(connectionString))
                        {
                            using (MySqlCommand cmd = new MySqlCommand())
                            {
                                cmd.CommandTimeout = 0;

                                using (MySqlBackup mb = new MySqlBackup(cmd))
                                {
                                    Console.WriteLine(" + Starting export to file: " + Config.OutputFile);

                                    Console.WriteLine("");
                                    Console.WriteLine("");
                                    Console.WriteLine("");
                                    Console.WriteLine("");

                                    mb.ExportInfo.AddCreateDatabase    = true;
                                    mb.ExportInfo.ExportTableStructure = true;

                                    mb.ExportProgressChanged += delegate(object sender, ExportProgressArgs e)
                                    {
                                        Console.Clear();

                                        var progress  = Math.Floor(((double)(e.CurrentRowIndexInAllTables / (double)e.TotalRowsInAllTables) * 100));
                                        var maxBlocks = 50;

                                        var activeBlocks = Math.Max(1, progress * 0.50);

                                        Console.WriteLine("   TABLE: " + e.CurrentTableName);
                                        Console.WriteLine("");
                                        Console.WriteLine("   PROGRESS:");
                                        Console.Write("   ");

                                        for (var i = 0; i <= activeBlocks; i++)
                                        {
                                            Console.Write("=");
                                        }

                                        for (var i = 0; i < (maxBlocks - activeBlocks); i++)
                                        {
                                            Console.Write("-");
                                        }

                                        Console.Write(" " + progress + "%");
                                    };

                                    mb.ExportCompleted += delegate(object sender, ExportCompleteArgs e)
                                    {
                                        Output.ClearLine();

                                        Console.SetCursorPosition(0, Console.CursorTop - 1);
                                        Output.ClearLine();

                                        Console.SetCursorPosition(0, Console.CursorTop - 2);
                                        Output.ClearLine();

                                        Console.Write("   - COMPLETE!");
                                        Console.WriteLine("");

                                        running = false;
                                    };

                                    cmd.Connection = conn;

                                    conn.Open();

                                    using (var ms = new FileStream(Config.OutputFile, FileMode.Create))
                                    {
                                        using (var zip = new GZipStream(ms, CompressionMode.Compress))
                                        {
                                            using (var writer = new StreamWriter(zip, Encoding.UTF8))
                                            {
                                                mb.ExportToTextWriter(writer);
                                            }
                                        }
                                    }

                                    //mb.StopAllProcess();
                                    //conn.Close();
                                }
                            }
                        }

                        while (running)
                        {
                        }

                        if (client.IsConnected)
                        {
                            port.Stop();
                            client.Disconnect();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Output.Writeline("   - Error: " + e.Message);
            }

            return;
        }
Ejemplo n.º 21
0
 public static void Close()
 {
     localPort.Stop();
     client.Disconnect();
     OnChangeSsh(false);
 }
Ejemplo n.º 22
0
        public void Test_ForwardedPortRemote()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshClient AddForwardedPort Start Stop ForwardedPortLocal
                client.Connect();
                var port = new ForwardedPortLocal(8082, "www.cnn.com", 80);
                client.AddForwardedPort(port);
                port.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.Start();

                Thread.Sleep(1000 * 60 * 20); //	Wait 20 minutes for port to be forwarded

                port.Stop();
                #endregion
            }
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 23
0
 public void StopTest()
 {
     uint boundPort = 0; // TODO: Initialize to an appropriate value
     string host = string.Empty; // TODO: Initialize to an appropriate value
     uint port = 0; // TODO: Initialize to an appropriate value
     ForwardedPortLocal target = new ForwardedPortLocal(boundPort, host, port); // TODO: Initialize to an appropriate value
     target.Stop();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Ejemplo n.º 24
0
 //added to stop the port
 public void stopPort()
 {
     port.Stop();
 }
Ejemplo n.º 25
0
        public void Test_PortForwarding_Local_Stop_Hangs_On_Wait()
        {
            using (var client = new SshClient(Resources.HOST, Int32.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

                var port1 = new ForwardedPortLocal("localhost", 8084, "www.google.com", 80);
                client.AddForwardedPort(port1);
                port1.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Assert.Fail(e.Exception.ToString());
                };

                port1.Start();

                bool hasTestedTunnel = false;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
                {
                    try
                    {
                        var url = "http://www.google.com/";
                        Debug.WriteLine("Starting web request to \"" + url + "\"");
                        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        Assert.IsNotNull(response);

                        Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString());

                        response.Close();

                        hasTestedTunnel = true;
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail(ex.ToString());
                    }
                });

                // Wait for the web request to complete.
                while (!hasTestedTunnel)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                try
                {
                    // Try stop the port forwarding, wait 3 seconds and fail if it is still started.
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
                    {
                        Debug.WriteLine("Trying to stop port forward.");
                        port1.Stop();
                        Debug.WriteLine("Port forwarding stopped.");
                    });

                    System.Threading.Thread.Sleep(3000);
                    if (port1.IsStarted)
                    {
                        Assert.Fail("Port forwarding not stopped.");
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.ToString());
                }
                client.Disconnect();
                Debug.WriteLine("Success.");
            }
        }