public void AddForwardedPortTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value ForwardedPort port = null; // TODO: Initialize to an appropriate value target.AddForwardedPort(port); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public void Test_AddForwardedPort_Invalid_PortNumber() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortRemote>("localhost", IPEndPoint.MaxPort+1, "www.renci.org", IPEndPoint.MaxPort+1); client.Disconnect(); } }
public void Test_AddForwardedPort_Remote_Hosts_Are_Null() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortRemote>(null, 8080, null, 80); client.Disconnect(); } }
public void Test_AddForwardedPort_Local_Hosts_Are_Empty() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortLocal>(string.Empty, 8080, string.Empty, 80); client.Disconnect(); } }
public ForwardedPortLocal GetForwardedPortInfo(TunnelRequest request) { if (_client == null) { var uri = new Uri(request.SshTunnelInfo); if (uri.Scheme != "ssh") { throw new ArgumentException("Invalid scheme, should be 'ssh'."); } var split = uri.UserInfo.Split(':'); var username = split[0].Trim(); var password = split[1].Trim(); _client = new SshClient(uri.Host, uri.Port == -1 ? 22 : uri.Port, username, password) { KeepAliveInterval = request.KeepAliveInterval, ConnectionInfo = { Timeout = request.ConnectionTimeout } }; _client.Connect(); } var forwardedPortLocal = _forwardedPortLocals.FirstOrDefault(i => i.Host == request.RemoteHost && i.Port == request.RemotePort); if (forwardedPortLocal == null) { while (true) { var localPort = Convert.ToUInt32(PortNumberRandom.Next(49152, 65535)); try { forwardedPortLocal = new ForwardedPortLocal("127.0.0.1", localPort, request.RemoteHost, request.RemotePort); _client.AddForwardedPort(forwardedPortLocal); forwardedPortLocal.Start(); _forwardedPortLocals.Add(forwardedPortLocal); return(forwardedPortLocal); } catch (SocketException socketException) { //port already used. just ignore it and try another if (socketException.ErrorCode != 10013) { throw; } } } } return(forwardedPortLocal); }
/// <summary> /// Open connection for DB /// </summary> /// <returns>Object opened MySqlConnection</returns> public MySqlConnection OpenConnection() { client.Connect(); if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); this.conn = new MySqlConnection(DataPath); conn.Open(); } return(conn); }
static int ExecuteMySqlDump(SshClient client) { if (Configuration.USE_SSH_TUNNEL_FOR_MYSQL) { if (client == null) { throw new Exception("SSH Client cannot be null when tunnel is expected!"); } var port = new ForwardedPortLocal("127.0.0.1", uint.Parse(Configuration.MYSQL_PORT), "localhost", uint.Parse(Configuration.MYSQL_LOCAL_PORT)); client.AddForwardedPort(port); port.Start(); } return(MysqlDump()); }
private void ConnectSSH(string ip, string port, string dbname, string account, string pw, string sshhostname, string sshuser, string sshpw) { SshClient_ = new SshClient(ip, sshuser, sshpw); SshClient_.Connect(); var fowardport = new ForwardedPortLocal("127.0.0.1", sshhostname, Convert.ToUInt32(port)); //var fowardport = new ForwardedPortLocal("127.0.0.1", 25251, sshhostname, Convert.ToUInt32(port)); SshClient_.AddForwardedPort(fowardport); //private string connection_string_ssh_ = "server={0};user={1};database={2};port={3};password={4};"; fowardport.Start(); real_connection_string_ = string.Format(connection_string_ssh_, "127.0.0.1", account, dbname, fowardport.BoundPort, pw); MySqlConnection_ = new MySqlConnection(real_connection_string_); }
/* * public void Tooltip(ListControl lc) * { * foreach (ListViewItem item in lc.) * { * item.ToolTipText = QuoteInformation[Convert.ToInt16(item.Text)]; * } * } */ void sshConnection(Func <Boolean> function) { PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("stellarismysql.ddns.net", 7846, "gregyoung", "stellaris"); //replace "192.168.2.52" with "stellarismysql.ddns.net", 7846 for connections from offsite connectionInfo.Timeout = TimeSpan.FromSeconds(30); using (var client = new SshClient(connectionInfo)) { try { Console.WriteLine("Trying SSH connection..."); client.Connect(); if (client.IsConnected) { Console.WriteLine("SSH connection is active: {0}", client.ConnectionInfo.ToString()); } else { Console.WriteLine("SSH connection has failed: {0}", client.ConnectionInfo.ToString()); } Console.WriteLine("\r\nTrying port forwarding..."); var portFwld = new ForwardedPortLocal("127.0.0.1", 1000, "localhost", 3306); client.AddForwardedPort(portFwld); portFwld.Start(); if (portFwld.IsStarted) { Console.WriteLine("Port forwarded: {0}", portFwld.ToString()); } else { Console.WriteLine("Port forwarding has failed."); } function(); client.Disconnect(); } catch (SshException err) { Console.WriteLine("SSH client connection error: {0}", err.Message); } catch (System.Net.Sockets.SocketException err) { Console.WriteLine("Socket connection error: {0}", err.Message); } } }
public static (SshClient SshClient, uint Port) ConnectSsh(string sshHostName, string sshUserName, string sshPassword = null, string sshKeyFile = null, string sshPassPhrase = null, int sshPort = 22007, string databaseServer = "localhost", int databasePort = 22007) { // check arguments if (string.IsNullOrEmpty(sshHostName)) { throw new ArgumentException($"{nameof(sshHostName)} must be specified.", nameof(sshHostName)); } if (string.IsNullOrEmpty(sshHostName)) { throw new ArgumentException($"{nameof(sshUserName)} must be specified.", nameof(sshUserName)); } if (string.IsNullOrEmpty(sshPassword) && string.IsNullOrEmpty(sshKeyFile)) { throw new ArgumentException($"One of {nameof(sshPassword)} and {nameof(sshKeyFile)} must be specified."); } if (string.IsNullOrEmpty(databaseServer)) { throw new ArgumentException($"{nameof(databaseServer)} must be specified.", nameof(databaseServer)); } // define the authentication methods to use (in order) var authenticationMethods = new List <AuthenticationMethod>(); if (!string.IsNullOrEmpty(sshKeyFile)) { authenticationMethods.Add(new PrivateKeyAuthenticationMethod(sshUserName, new PrivateKeyFile(sshKeyFile, string.IsNullOrEmpty(sshPassPhrase) ? null : sshPassPhrase))); } if (!string.IsNullOrEmpty(sshPassword)) { authenticationMethods.Add(new PasswordAuthenticationMethod(sshUserName, sshPassword)); } // connect to the SSH server var sshClient = new SshClient(new ConnectionInfo(sshHostName, sshPort, sshUserName, authenticationMethods.ToArray())); sshClient.Connect(); // forward a local port to the database server and port, using the SSH server var forwardedPort = new ForwardedPortLocal("localhost", 6789, databaseServer, (uint)databasePort); sshClient.AddForwardedPort(forwardedPort); forwardedPort.Start(); return(sshClient, forwardedPort.BoundPort); }
private static void OpenTunnel(CommandLineOptions opts) { var client = new SshClient(opts.SshServer, opts.UserName, new PrivateKeyFile(opts.KeyFile)); client.Connect(); client.KeepAliveInterval = new TimeSpan(0, 0, 5); if (!client.IsConnected) { Log.Error("Can't start tunnel, try again."); } var connectionPort = new ForwardedPortRemote(Convert.ToUInt32(opts.RemotePort), "localhost", Convert.ToUInt32(opts.LocalPort)); client.AddForwardedPort(connectionPort); connectionPort.Start(); }
private async Task EstablishForwardedPorts() { foreach (var fp in ForwardedPorts) { try { SshClient.AddForwardedPort(fp.ForwardedPort.Value); await fp.Connect(); this.WriteLog($"Port Forwarding Established ({fp.ToString()})."); } catch (Exception ex) { this.WriteLog($"Failed to Establish Port Forwarding: ({fp.ToString()}).", ex); } } }
/// <summary> /// Thread /// </summary> /// <param name="o">Parameters</param> void jobRun(object o) { SshClient ssh = (SshClient)((object[])o)[0]; ForwardedPort port = (ForwardedPort)((object[])o)[1]; ssh.AddForwardedPort(port); port.RequestReceived += (sender2, e2) => { WriteInfo(e2.OriginatorHost + ":" + e2.OriginatorPort); }; port.Start(); while (port.IsStarted) { Thread.Sleep(10); } }
private ClientSsh() { uint port = uint.Parse(SSHInfo.Instance.local_port); string host = SSHInfo.Instance.local_ip; PasswordConnectionInfo passwordConnectionInfo = new PasswordConnectionInfo(SSHInfo.Instance.publish_ip, int.Parse(SSHInfo.Instance.publish_port), SSHInfo.Instance.publish_usr, SSHInfo.Instance.publish_pws); passwordConnectionInfo.Timeout = TimeSpan.FromSeconds(30); sshClient = new SshClient(passwordConnectionInfo); if (!sshClient.IsConnected) { sshClient.Connect(); } ForwardedPortLocal localFwdPort = new ForwardedPortLocal(host, port, host, port); sshClient.AddForwardedPort(localFwdPort); localFwdPort.Start(); }
public void AddForwardedPort_NeverConnected() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password")) { var port = new ForwardedPortLocal(50, "host", 8080); try { client.AddForwardedPort(port); Assert.Fail(); } catch (SshConnectionException ex) { Assert.IsNull(ex.InnerException); Assert.AreEqual("Client not connected.", ex.Message); } } }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { _connection.Server = "localhost"; _connection.Port = 22; _connection.UserID = "syroeshka_yar"; _connection.Password = "******"; _connection.Database = "mg23sx"; if (!_ssh.IsConnected) { _ssh.Connect(); ForwardedPortLocal port = new ForwardedPortLocal("127.0.0.1", 22, "localhost", 3306); _ssh.AddForwardedPort(port); port.Start(); } optionsBuilder.UseMySQL(_connection.ConnectionString); }
private bool Reconnect() { _client.ErrorOccurred -= OnErrorHandler; var retryCount = NUMBERS_OF_RETRIES; foreach (var port in _ports) { _client.RemoveForwardedPort(port.NativePort); } while (!_client.IsConnected && retryCount-- > 0) { Thread.Sleep(1500); _loggerProvider.Write("Reconnect... Attempt: " + (NUMBERS_OF_RETRIES - retryCount)); try { ConnectionStatusChanged?.Invoke(ConnectionStatus.Reconnecting); _client.Connect(); } catch (Exception e) { _loggerProvider.Write("Reconnect exception: " + e); ConnectionStatusChanged?.Invoke(ConnectionStatus.Failed); } if (_client.IsConnected) { _loggerProvider.Write("Connection established."); ConnectionStatusChanged?.Invoke(ConnectionStatus.Established); foreach (var p in _ports) { p.Init(); _client.AddForwardedPort(p.NativePort); p.Start(); } _client.ErrorOccurred += OnErrorHandler; } } return(_client.IsConnected); }
public string[] UserInfo(string username) { string[] userInfo = new string[10]; try { using (var client = new SshClient("softeng.cs.uwosh.edu", 1022, "heidem57", "cs341SoftEngg@486257")) { client.Connect(); string connectDB = ConfigurationManager.ConnectionStrings["MySQLDB"].ConnectionString; var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection conn = new MySqlConnection(connectDB)) { using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM `Renters` WHERE Username = @Username", conn)) { conn.Open(); cmd.Parameters.AddWithValue("@Username", username);//Insert all parameters. MySqlDataReader reader = cmd.ExecuteReader(); reader.Read(); userInfo[0] = reader.GetValue(0).ToString(); userInfo[1] = reader.GetValue(3).ToString(); userInfo[2] = reader.GetValue(4).ToString(); userInfo[3] = reader.GetValue(5).ToString(); userInfo[4] = reader.GetValue(6).ToString(); userInfo[5] = reader.GetValue(7).ToString(); userInfo[6] = reader.GetValue(8).ToString(); userInfo[7] = reader.GetValue(9).ToString(); userInfo[8] = reader.GetValue(10).ToString(); userInfo[9] = reader.GetValue(11).ToString(); conn.Close(); } client.Disconnect(); } } } catch (Exception error) { return(userInfo); } return(userInfo); }
public int LoginUser(string username, string password) { int result = 0; try { using (var client = new SshClient("softeng.cs.uwosh.edu", 1022, "heidem57", "cs341SoftEngg@486257")) { client.Connect(); string connectDB = ConfigurationManager.ConnectionStrings["MySQLDB"].ConnectionString; var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection conn = new MySqlConnection(connectDB)) { using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM `Renters` WHERE Username = @Username", conn)) { conn.Open(); cmd.Parameters.AddWithValue("@Username", username);//Insert all parameters. MySqlDataReader reader = cmd.ExecuteReader(); reader.Read(); //result string sqlPass = reader.GetValue(1).ToString(); string salt = reader.GetValue(2).ToString(); string finalPass = CreateHash(password, salt); //Convert.ToBase64String(bytHash); if (sqlPass == finalPass) { result = 1; } conn.Close(); } client.Disconnect(); } } } catch (Exception error) { return(result); } return(result); }
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(); } }
public static (SshClient SshClient, uint Port) ConnectSsh(string sshHostName, string sshUserName, string sshPassword = null, string sshKeyFile = null, string sshPassPhrase = null, int sshPort = 63222, string databaseServer = "localhost", int databasePort = 3306) { if (string.IsNullOrEmpty(sshHostName)) { throw new ArgumentException($"{nameof(sshHostName)} must be specified.", nameof(sshHostName)); } if (string.IsNullOrEmpty(sshHostName)) { throw new ArgumentException($"{nameof(sshUserName)} must be specified.", nameof(sshUserName)); } if (string.IsNullOrEmpty(sshPassword) && string.IsNullOrEmpty(sshKeyFile)) { throw new ArgumentException($"One of {nameof(sshPassword)} and {nameof(sshKeyFile)} must be specified."); } if (string.IsNullOrEmpty(databaseServer)) { throw new ArgumentException($"{nameof(databaseServer)} must be specified.", nameof(databaseServer)); } var authenticationMethods = new List <AuthenticationMethod>(); if (!string.IsNullOrEmpty(sshKeyFile)) { authenticationMethods.Add(new PrivateKeyAuthenticationMethod(sshUserName, new PrivateKeyFile(sshKeyFile, string.IsNullOrEmpty(sshPassPhrase) ? null : sshPassPhrase))); } if (!string.IsNullOrEmpty(sshPassword)) { authenticationMethods.Add(new PasswordAuthenticationMethod(sshUserName, sshPassword)); } var sshClient = new SshClient(new ConnectionInfo(sshHostName, sshPort, sshUserName, authenticationMethods.ToArray())); sshClient.Connect(); var forwardedPort = new ForwardedPortLocal("127.0.0.1", databaseServer, (uint)databasePort); sshClient.AddForwardedPort(forwardedPort); forwardedPort.Start(); return(sshClient, forwardedPort.BoundPort); }
/// <summary> /// establishing ssh connection to server where MySql is hosted /// </summary> public void Connection() { try { if (!Client.IsConnected) { Client.Connect(); ForwardedPortLocal portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); Client.AddForwardedPort(portForwarded); portForwarded.Start(); Con = new MySqlConnection("SERVER=127.0.0.1;PORT=3306;UID=root;PASSWORD=darkmaster;DATABASE=firefly"); Con.Open(); } } catch (Exception e) { MessageBox.Show("You need a working internet connection, application will be closed!:" + e); } }
//public DataTable getMerchantDetailsLocal() //{ // //try // //{ // // objAgentDetails_Local = new List<tbl_RemittanceAgentDetails>; // // HostedCheckout_UDIO.Models.DMTNewAPIModels obj = new DMTNewAPIModels(); // // HostedCheckout_UDIO.EF. // // dtRecord = new DataTable(); // // return dtRecord; // //} // //catch (Exception ex) // //{ // // throw ex; // //} // //finally // //{ // // dtRecord.Dispose(); // //} //} public DataSet getAgentDetail() { DataSet ds = new DataSet(); try { using (var client = new SshClient("52.74.21.139", "anils", "P&ssw0rd1122")) // establishing ssh connection to server where MySql is hosted { client.Connect(); if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection con = new MySqlConnection("SERVER=127.0.0.1;PORT=3306;UID=anils;PASSWORD=$Tran$erv891;DATABASE=transerv_db")) { using (MySqlCommand com = new MySqlCommand("select * from rmt_api_user", con)) { com.CommandType = CommandType.Text; MySqlDataAdapter da = new MySqlDataAdapter(com); da.Fill(ds); } } client.Disconnect(); } //else //{ // Console.WriteLine("Client cannot be reached..."); //} return(ds); } } catch (Exception ex) { throw ex; } finally { ds.Dispose(); } }
//(string name, IPAddress address, ushort port) /// <summary> /// Connects To A Remote Node VIA SSH! /// </summary> /// <param name="name">Node Name</param> /// <param name="username">SSH Login</param> /// <param name="password">SSH Password</param> /// <param name="sshServerAddress">IP Address of SSH Server</param> /// <param name="sshPort">SSH Server Port (Default: 22)</param> /// <param name="nodeIPAddress">IP Address x42 Node Is Bound To (Default: 127.0.0.1)</param> /// <param name="nodePort">Port x42 Node Is Bound To (Default: 42220 - MainNet)</param> /// <param name="localBoundAddress">IP Address To Bind Locally (Default: 127.0.0.1)</param> /// <param name="localBoundPort">Local Port To Bind To (Default: 42220 - MainNet)</param> public x42Node(string name, string username, string password, string sshServerAddress, ushort sshPort = 22, string nodeIPAddress = "127.0.0.1", uint nodePort = 42220, string localBoundAddress = "127.0.0.1", uint localBoundPort = 42220) { try { Guard.Null(name, nameof(name), "Node Name Cannot Be Null"); Guard.Null(username, nameof(username), "SSH Username Cannot Be Null"); Guard.Null(password, nameof(password), "SSH Password Cannot Be Null"); Guard.AssertTrue(IPAddress.TryParse(sshServerAddress, out IPAddress sshAddress), $"Invalid SSH IP Address Provided '{sshServerAddress}'"); Guard.AssertTrue(IPAddress.TryParse(nodeIPAddress, out IPAddress nodeAddress), $"Invalid x42 Node IP Address Provided '{sshServerAddress}'"); Guard.AssertTrue(IPAddress.TryParse(localBoundAddress, out IPAddress localBoundIP), $"Invalid Local Bound IP Address Provided '{sshServerAddress}'"); Guard.AssertTrue(sshPort.IsValidPortRange(), $"Invalid Port Specified For The SSH Server, Value Provided Is '{sshPort}'"); Guard.AssertTrue(nodePort.IsValidPortRange(), $"Invalid Port Specified For The x42 Node, Value Provided Is '{nodePort}'"); Guard.AssertTrue(localBoundPort.IsValidPortRange(), $"Invalid Port Specified For Binding Locally, Value Provided Is '{localBoundPort}'"); _SSHClient = new SshClient(sshServerAddress, username, password); _SSHClient.KeepAliveInterval = new TimeSpan(0, 0, 5); _SSHClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20); _SSHClient.Connect(); if (!_SSHClient.IsConnected) { throw new Exception($"An Error Occured When Connecting To SSH Server '{username}'@'{sshServerAddress}':'{sshPort}'"); } _SSHForwardPort = new ForwardedPortLocal(localBoundPort, nodeIPAddress, nodePort); _SSHClient.AddForwardedPort(_SSHForwardPort); _SSHForwardPort.Start(); SetupNodeConnection(name, localBoundIP, (ushort)localBoundPort); OnConnected(sshAddress, sshPort, ConnectionType.SSH); } catch (Exception ex) { Logger.Fatal($"Node '{Name}' ({Address}:{Port}) An Error Occured When Connecting To The Remote Node Via SSH '{username}'@'{sshServerAddress}':'{sshPort}'", ex); throw; } //end of try-catch } //end of public x42Node(string name, string sshServerAddress, int port = 22, string nodeIPAddress = "127.0.0.1", int nodePort = 422220)
public static void test3() { using (var client = new SshClient("219.245.64.4", "root", "123456")) { try { Console.WriteLine("Trying SSH connection..."); client.Connect(); if (client.IsConnected) { Console.WriteLine("SSH connection is active: {0}", client.ConnectionInfo.ToString()); } else { Console.WriteLine("SSH connection has failed: {0}", client.ConnectionInfo.ToString()); } Console.WriteLine("\r\nTrying port forwarding..."); var port = new ForwardedPortLocal("127.0.0.1", Convert.ToUInt32(19999), "219.245.64.4", Convert.ToUInt32(3306)); //ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 3306); client.AddForwardedPort(port); port.Start(); if (port.IsStarted) { Console.WriteLine("Port forwarded: {0}", port.ToString()); } else { Console.WriteLine("Port forwarding has failed."); } } catch (SshException e) { Console.WriteLine("SSH client connection error: {0}", e.Message); } catch (System.Net.Sockets.SocketException e) { Console.WriteLine("Socket connection error: {0}", e.Message); } } }
static void Main(string[] args) { Console.WriteLine("SSH Client!"); using (var client = new SshClient("52.231.201.187", "<SSH username>", "<SSH password>")) { try { client.Connect(); } catch (Exception ex2) { Console.WriteLine("SSH connection error!"); Console.WriteLine(ex2.ToString()); } // SSH Remote Port Forwarding // 1234 : SSH server side port(remote port) // 554 : local service port (ex, 80, 3389 ...) // localhost: local service hostname or ipaddress var port = new ForwardedPortRemote(1234, "127.0.0.1", 8554); client.AddForwardedPort(port); port.Exception += delegate(object sender, ExceptionEventArgs e) { Console.WriteLine(e.Exception.ToString()); }; port.RequestReceived += delegate(object sender, PortForwardEventArgs e) { Console.WriteLine(e.OriginatorHost); }; port.Start(); // ... hold the port open ... // Console.WriteLine("Press any key to close."); Console.ReadLine(); port.Stop(); client.Disconnect(); } }
public void SSHConnectMySql() { //string SSHHost = "10.10.1.21"; string SSHHost = "210.75.21.106"; // SSH地址 int SSHPort = 8888; // SSH端口 string SSHUser = "******"; // SSH用户名 string SSHPassword = "******"; // SSH密码 string sqlIPA = "127.0.0.1"; // 映射地址 实际上也可以写其它的 Linux上的MySql的my.cnf bind-address 可以设成0.0.0.0 或者不设置 string sqlHost = "127.0.0.1"; // mysql安装的机器IP 也可以是内网IP 比如:192.168.1.20 uint sqlport = 3306; // 数据库端口及映射端口 string sqlConn = "Database='ums';Data Source=" + sqlIPA + ";Port=" + sqlport + ";User Id='root';Password='******';CharSet='utf8'"; //string sqlSELECT = "select * from user"; PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword); connectionInfo.Timeout = TimeSpan.FromSeconds(30); this.client = new SshClient(connectionInfo); try { client.Connect(); if (!client.IsConnected) { MessageBox.Show("SSH connect failed"); } var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); //映射到本地端口sqlHost, client.AddForwardedPort(portFwdL); portFwdL.Start(); if (!client.IsConnected) { MessageBox.Show("port forwarding failed"); } this.conn = new MySqlConnection(sqlConn); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
// Token: 0x0600054B RID: 1355 RVA: 0x00032964 File Offset: 0x00030B64 //public static bool SetSSH2(string host, string username, string password, string ipforward, string portforward, ref SshTunnel tunnel) //{ // try // { // tunnel.StopAccepting(true); // tunnel.CloseTunnel(true); // tunnel = null; // GC.Collect(); // } // catch (Exception) // { // } // tunnel = new SshTunnel(); // int port = 22; // bool flag = tunnel.Connect(host, port); // bool flag2 = !flag; // bool result; // if (flag2) // { // Console.WriteLine(tunnel.LastErrorText); // result = false; // } // else // { // flag = tunnel.AuthenticatePw(username, password); // bool flag3 = !flag; // if (flag3) // { // Console.WriteLine(tunnel.LastErrorText); // result = false; // } // else // { // tunnel.DynamicPortForwarding = true; // flag = tunnel.BeginAccepting(Convert.ToInt32(portforward)); // bool flag4 = !flag; // if (flag4) // { // Console.WriteLine(tunnel.LastErrorText); // result = false; // } // else // { // result = true; // } // } // } // return result; //} // Token: 0x0600054C RID: 1356 RVA: 0x00032A40 File Offset: 0x00030C40 public static bool SetSSH1(string host, string username, string password, string ipforward, string portforward, ref SshClient cursshclient) { SshClient sshClient = null; try { bool flag = cursshclient != null; if (flag) { foreach (ForwardedPort forwardedPort in cursshclient.ForwardedPorts) { forwardedPort.Stop(); } cursshclient.Disconnect(); } sshClient = new SshClient(host, username, password); sshClient.KeepAliveInterval = new TimeSpan(0, 0, 30); sshClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, 30); sshClient.Connect(); ForwardedPortDynamic forwardedPortDynamic = new ForwardedPortDynamic(ipforward, Convert.ToUInt32(portforward)); sshClient.AddForwardedPort(forwardedPortDynamic); forwardedPortDynamic.Exception += delegate(object sender1, ExceptionEventArgs e1) { Console.WriteLine(e1.Exception.ToString()); }; forwardedPortDynamic.Start(); } catch (Exception ex) { cursshclient = sshClient; bool flag2 = ex.Message == "Only one usage of each socket address (protocol/network address/port) is normally permitted"; if (flag2) { MessageBox.Show("Port " + portforward + " đã được sử dụng, hãy đổi sang port khác", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Hand); return(true); } return(false); } cursshclient = sshClient; return(true); }
public JokeContext(string auroraAddress, string auroraPassword, string sshTunnelAddress, string sshUserName, string keyFileName, bool isDebug = false) { var builder = new MySqlConnectionStringBuilder(); builder.UserID = "root"; builder.Password = auroraPassword; builder.Database = "jokes"; builder.PersistSecurityInfo = true; builder.Port = 3306; if (isDebug) { // We are using our PEM file to securely access our SSH tunnel // and forward all the traffic coming in to our local port // that gets automatically bound then forwarding it to our Aurora cluster. var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); PrivateKeyFile pkfile = new PrivateKeyFile($@"{dir}/{keyFileName}"); _client = new SshClient(sshTunnelAddress, 22, sshUserName, pkfile); _client.Connect(); if (_client.IsConnected) { _local = new ForwardedPortLocal("127.0.0.1", auroraAddress, 3306); _client.AddForwardedPort(_local); _local.Start(); } builder.Port = _local.BoundPort; builder.Server = "127.0.0.1"; } else { builder.Server = System.Net.Dns.GetHostEntry(auroraAddress) .AddressList[0] .MapToIPv4() .ToString(); // builder.Server = "127.0.0.1"; } _connection = new MySqlConnection(builder.ConnectionString); }
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"); }
public void Test_ForwardedPortRemote() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { #region Example SshClient AddForwardedPort Start Stop ForwardedPortRemote client.Connect(); var port = new ForwardedPortRemote(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"); }
private void Connect() { retryPolicy.Execute(() => { try { logger?.LogInformation($"Connecting to {sshClient.ConnectionInfo.Host}:{sshClient.ConnectionInfo.Port}..."); sshClient.Connect(); logger?.LogInformation($"Connected."); foreach (PortForwardingSettings portForwardingSettings in settings.ForwardedPorts) { ForwardedPortLocal forwardedPortLocal = new ForwardedPortLocal(portForwardingSettings.LocalHost, portForwardingSettings.LocalPort, portForwardingSettings.RemoteHost, portForwardingSettings.RemotePort); sshClient.AddForwardedPort(forwardedPortLocal); logger?.LogInformation($"Starting port forwarding from {forwardedPortLocal.BoundHost}:{forwardedPortLocal.BoundPort} " + $"to server's {forwardedPortLocal.Host}:{forwardedPortLocal.Port}..."); try { forwardedPortLocal.Start(); } catch (SocketException e) when(e.SocketErrorCode == SocketError.AddressAlreadyInUse && portForwardingSettings.IgnorePortInUseError) { logger?.LogWarning($"Port forwarding from {forwardedPortLocal.BoundHost}:{forwardedPortLocal.BoundPort} " + $"to server's {forwardedPortLocal.Host}:{forwardedPortLocal.Port} could not be started: {e.Message}."); } } } catch (Exception exception) { logger?.LogWarning($"Failed to forward ports: {exception}"); StopPortForwarding(); throw; } }); logger?.LogInformation($"All port forwarding started."); }
void startssh() { ssh = setupThis(); if (verbose) { ssh.HostKeyReceived += (object sender, Renci.SshNet.Common.HostKeyEventArgs e) => { Console.WriteLine(String.Join(" ,", new object[] { e.CanTrust, e.FingerPrint, e.HostKey, e.HostKeyName, e.KeyLength, e.ToString() })); } } ; try { ssh.Connect(); } catch (Exception e) { errors.Enqueue(e); } ssh.ErrorOccurred += (object sender, Renci.SshNet.Common.ExceptionEventArgs e) => { errors.Enqueue(e); }; Check.Start(); //if (ssh.IsConnected) ssh.AddForwardedPort(new ForwardedPortDynamic("localhost", this.Cientport)); if (ssh.IsConnected) { foreach (var f in ssh.ForwardedPorts) { if (verbose) { f.RequestReceived += (object sender, Renci.SshNet.Common.PortForwardEventArgs e) => { Console.WriteLine(String.Join(" ", new object[] { e.OriginatorHost, e.OriginatorPort, e.ToString() })); } } ; f.Start(); Console.WriteLine("port forwarded: " + f.IsStarted); } } ssh.KeepAliveInterval = keepalive; } void ErrorCatch(object sender, Renci.SshNet.Common.ExceptionEventArgs e, out bool starting) { errors.Enqueue(e); starting = false; }
public void ForwardPort(int boundPort, int port, bool remoteForward = false) { EnsureSshConnection(); var forwardedPort = default(ForwardedPort); if (remoteForward) { forwardedPort = new ForwardedPortRemote(IPAddress.Parse("127.0.0.1"), (uint)boundPort, IPAddress.Parse("127.0.0.1"), (uint)port); } else { // IPAddress.Loopback.ToString() is the string 127.0.0.1. Don't change this unless you've also changed // port forwarding in XMA/XVS to match--you'll break inspection if you make things dependent on this // behavior without fixing XMA/XVS too. forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(), (uint)boundPort, IPAddress.Loopback.ToString(), (uint)port); } sshClient.AddForwardedPort(forwardedPort); forwardedPort.Start(); }
/// <summary> /// SSH连接端口转发 /// </summary> /// <param name="server">服务器地址</param> /// <param name="port">服务器端口</param> /// <param name="uid">用户名</param> /// <param name="pwd">密码</param> /// <returns></returns> public static bool sshConnected(string server, int port, string uid, string pwd) { bool sshState = false; var client = new SshClient(server, port, uid, pwd); try { client.Connect(); Constant.sshConnected = client.IsConnected; } catch (Exception ex) { throw ex; } var porcik = new ForwardedPortLocal("localhost", 3306, "localhost", 3306); try { client.AddForwardedPort(porcik); porcik.Start(); sshState = true; } catch (Exception ex) { throw ex; } return(sshState); }
protected void Arrange() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); var sequence = new MockSequence(); _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _forwardedPortMock = new Mock<ForwardedPort>(MockBehavior.Strict); _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.Connect()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Start()); _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Stop()); _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); _sshClient.Connect(); _sshClient.AddForwardedPort(_forwardedPortMock.Object); _forwardedPortMock.Object.Start(); }
public void Test_PortForwarding_Remote() { // ****************************************************************** // ************* Tests are still in not finished ******************** // ****************************************************************** using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate(object sender, ExceptionEventArgs e) { Assert.Fail(e.Exception.ToString()); }; port1.Start(); var boundport = port1.BoundPort; System.Threading.Tasks.Parallel.For(0, 5, //new ParallelOptions //{ // MaxDegreeOfParallelism = 1, //}, (counter) => { var cmd = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport)); var result = cmd.Execute(); var end = DateTime.Now; Debug.WriteLine(string.Format("Length: {0}", result.Length)); } ); Thread.Sleep(1000 * 100); port1.Stop(); } }
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 = client.AddForwardedPort<ForwardedPortLocal>("localhost", 8084, "www.google.com",80); 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."); } }
public void Test_PortForwarding_Local() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate(object sender, ExceptionEventArgs e) { Assert.Fail(e.Exception.ToString()); }; port1.Start(); System.Threading.Tasks.Parallel.For(0, 100, //new ParallelOptions //{ // MaxDegreeOfParallelism = 20, //}, (counter) => { var start = DateTime.Now; var req = HttpWebRequest.Create("http://localhost:8084"); using (var response = req.GetResponse()) { var data = ReadStream(response.GetResponseStream()); var end = DateTime.Now; Debug.WriteLine(string.Format("Request# {2}: Length: {0} Time: {1}", data.Length, (end - start), counter)); } } ); } }