public static (string HttpResponseContent, bool TunnelState) SshPortForwardState(SshClient client) { // Tunnel:PortForward:HTTP ForwardedPortLocal _webPort = new ForwardedPortLocal( "127.0.0.1", "http://checkip.amazonaws.com", 80); client.AddForwardedPort(_webPort); _webPort.Exception += (sender, e) => throw new ArgumentException(e.Exception.ToString()); _webPort.Start(); // Check:Tunnel State using HttpClient http = new HttpClient(); HttpResponseMessage response = http.GetAsync($"{_webPort.BoundHost}:{_webPort.BoundPort}") .GetAwaiter().GetResult(); string content = response.Content .ReadAsStringAsync() .GetAwaiter().GetResult(); bool state = !string.IsNullOrEmpty(content); _logger.LogInformation($"Tunnel Endpoint Response: {content} \n Tunnel State: {state}"); return(content, state); }
public static bool EstablishExternalConnection() { if (Externalconnection != null) { return(false); } try { PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("premium59.web-hosting.com", 21098, "tfariyiy", "streamingvf@123"); connectionInfo.Timeout = TimeSpan.FromSeconds(30); sshclient = new SshClient(connectionInfo); sshclient.Connect(); portFwld = new ForwardedPortLocal("127.0.0.1" /*your computer ip*/, "127.0.0.1" /*server ip*/, 3306 /*server mysql port*/); sshclient.AddForwardedPort(portFwld); portFwld.Start(); //// using Renci.sshNet Externalconnection = new MySqlConnection("server = " + "127.0.0.1" /*you computer ip*/ + "; Database = tfariyiy_wp443; UID = tfariyiy_wp443; PWD =D)1pS14(Ts; Port = " + portFwld.BoundPort /*very important !!*/); return(true); } catch (Exception e) { MessageBox.Show(e.Message); return(false); } }
public static (SshClient TunnelClient, ForwardedPortLocal PortLocal) HookDatabase( SshClient client, string endpoint, uint port) { try { // Connect:SshTunnel client.HostKeyReceived += (sender, e) => e.CanTrust = true; client.Connect(); _logger.LogInformation("Established tunnel to client."); // Tunnel:PortForward:Endpoint ForwardedPortLocal portLocal = new ForwardedPortLocal( "127.0.0.1", endpoint, port); client.AddForwardedPort(portLocal); portLocal.Exception += (sender, e) => _logger.LogInformation(e.Exception.ToString()); portLocal.Start(); // Return:SshTunnel:DatabaseHookClient return(client, portLocal); } catch (Exception ex) { throw new ArgumentException($"Could not establish tunnel. {ex}"); } }
protected void ConnectSsh(string server, string password) { if (ssh == null) // if the ssh object is not null, then a tunnel has already been created { ssh = new SshClient(server, 22, "youthbot", password); SqlMessageEvent?.Invoke(this, new SqlMessageArgs("Connecting to SSH server...")); try { ssh.Connect(); } catch (Exception ex) { string text = "failure\n" + ex.ToString(); SqlMessageEvent?.Invoke(this, new SqlMessageArgs(text)); return; } if (ssh.IsConnected) { SqlMessageEvent?.Invoke(this, new SqlMessageArgs("connected\n")); var tunnel = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); ssh.AddForwardedPort(tunnel); tunnel.Start(); } } }
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; } }
public void start_Connection() { sshClient = new SshClient(connectionInfo); sshClient.Connect(); if (sshClient.IsConnected) { uint sqlPort = 3306; var portFwd = new ForwardedPortLocal("127.0.0.1", sqlPort, "localhost", sqlPort); sshClient.AddForwardedPort(portFwd); portFwd.Start(); label1.Text = "SSH connection successful"; if (portFwd.IsStarted) { // toolStripButton1.Image = @("./assets/Connect_greenOverlay_16x32.bmp"); label1.Text = "Port Forwarding has started : BoundPort " + portFwd.BoundPort + " Host: " + portFwd.Host; } else { label1.Text = "Port Forwarding has failed"; sshClient.Disconnect(); sshClient.Dispose(); } button2.Visible = true; } }
public void MySQLConnection() { 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; DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter(com); da.Fill(ds); foreach (DataRow drow in ds.Tables[0].Rows) { // Console.WriteLine("From MySql: " + drow[1].ToString()); strData = strData + "-----" + drow[1].ToString(); } HttpContext.Current.Response.Write("API User Details Data - " + strData); } } client.Disconnect(); } else { Console.WriteLine("Client cannot be reached..."); } } }
public void SshConnect() { if (ip != "" && port != 0 && user != "" && password != "") { PasswordConnectionInfo sshinfo = new PasswordConnectionInfo(ip, port, user, password); sshinfo.Timeout = TimeSpan.FromSeconds(30); SshClient client = new SshClient(sshinfo); client.Connect(); Console.WriteLine(sshinfo.ClientVersion); if (!client.IsConnected) { Console.WriteLine("SSH connect failed"); } else { var portfwd = new ForwardedPortLocal("127.0.0.1", 51741, mysqlip, mysqlport); client.AddForwardedPort(portfwd); portfwd.Start(); if (!client.IsConnected) { Console.WriteLine("port mapping failed"); } else { mysqlconnectstr = "server=127.0.0.1;port=51741;user="******";password="******";Sslmode=none;"; } } } else { throw new Exception("Without Ssh Connect Info"); } }
static void Main(string[] args) { Sha1Hasher hashObj = new Sha1Hasher(); using (var client = new SshClient("shell1.sigmatic.fi", "shakkili", "2600_Chess_GM")) { string connectionStr = "server=mysql2.sigmatic.fi;user=shakkili_master;database=shakkili_avainsiirto;port=22;password=abckukko"; client.Connect(); if (client.IsConnected) { Console.WriteLine("Connected to SSH Tunnel"); var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 22); client.AddForwardedPort(portForwarded); portForwarded.Start(); MySqlConnection conn = new MySqlConnection(connectionStr); try { Console.WriteLine("Connecting to mySQL DB"); conn.Open(); Console.WriteLine("Managed to connect to DB"); } catch (Exception exc) { Console.WriteLine(exc.ToString()); } ConsoleKeyInfo a = Console.ReadKey(); conn.Close(); } Console.WriteLine("Connection to SSH Tunnel failed"); } }
public async Task <string> checkSSH(string ip, string user, string pwd, string host, int timeout) { return(await Task.Run(() => { try { uint port = (uint)new Random().Next(1080, 9999); //uint port = 1080; ConnectionInfo ConnNfo = new ConnectionInfo(ip, 22, user, new AuthenticationMethod[] { new PasswordAuthenticationMethod(user, pwd) }); fwPort = new ForwardedPortLocal("127.0.0.1", port, host, 80); client = new SshClient(ConnNfo); client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(timeout); client.Connect(); if (client.IsConnected) { client.AddForwardedPort(fwPort); fwPort.Start(); if (fwPort.IsStarted) { closeAll(); return "live"; } } } catch (Exception) { } return "Die"; })); }
public static void Connect() { try { _session = new SshClient(Settings.SSHHost, Settings.SSHPort, Settings.SSHUsername, Settings.SSHPassword); _session.Connect(); uint port; if (!uint.TryParse(Settings.Port, out port)) { port = 3306; } var portForward = new ForwardedPortLocal((uint)Settings.SSHLocalPort, "127.0.0.1", port); _session.AddForwardedPort(portForward); portForward.Start(); Enabled = _session.IsConnected; } catch (Exception ex) { Enabled = false; Trace.WriteLine(ex.Message + " at ssh connect."); Disconnect(); } }
static bool ForwardPort() { try { Console.WriteLine("\r\n[PF] Trying port forwarding...\r\n"); var portFwld = new ForwardedPortLocal("127.0.0.1", Convert.ToUInt32(3306), "127.0.0.1", Convert.ToUInt32(3306)); Console.WriteLine("[PF] Bound Host : {0}:{1}", ((ForwardedPortLocal)portFwld).BoundHost, ((ForwardedPortLocal)portFwld).BoundPort); Console.WriteLine("[PF] Local Host : {0}:{1}\r\n", ((ForwardedPortLocal)portFwld).Host, ((ForwardedPortLocal)portFwld).Port); client.AddForwardedPort(portFwld); portFwld.Start(); if (!portFwld.IsStarted) { Console.WriteLine("[PF] Port forwarding has failed.\r\n"); Console.ReadLine(); return(false); } else { Console.WriteLine("[PF] Port forwarded: {0}\r\n", portFwld.ToString()); return(true); } } catch (Exception ex) { Console.WriteLine("[PF] Port Forwarding is ERROR !!\r\n\r\n[PF] Error Message : {0}\r\n[PF] Stack Trace : {1}\r\n", ex.Message, ex.StackTrace); return(false); } }
private void btnDisconnect_Click(object sender, EventArgs e) { if (!Connected) { return; } MysqlConn.Close(); 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; //Disconnect Done Connected = false; FlashState(); }
/* * Calls SQL command to return the income for a certain county and household size. * Specifically the 30% Bracket. */ public static int County30Check(int hhSize, string id) { //string household = hhSize.ToString(); int incomeLimit = 0; using (var client = new SshClient("softeng.cs.uwosh.edu", 1022, "heidem57", "cs341SoftEngg@486257")) // establishing ssh connection to server where MySql is hosted { 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)) { string sql = "SELECT * FROM `County_30` WHERE Counties = @id"; using (MySqlCommand county30 = new MySqlCommand(sql, conn)) { conn.Open(); county30.Parameters.AddWithValue("@id", id); county30.ExecuteNonQuery(); MySqlDataReader reader = county30.ExecuteReader(); reader.Read(); incomeLimit = int.Parse(reader.GetValue(hhSize).ToString()); conn.Close(); } } client.Disconnect(); } return(incomeLimit); }
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); _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.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(); }
public static void Database(string hexId, bool isVip) { using (SshClient client = new SshClient(sshServerIp, sshUsername, sshPasswd)) { client.Connect(); // Connect to ssh server if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); string connString = $"SERVER={dbServerIp};PORT={dbPort};UID={dbUsername};PASSWORD={dbPasswd};DATABASE={dbName}"; // MySQL connection string MySqlConnection conn = new MySqlConnection(connString); // Create new mysql connection conn.Open(); // Open mysql connection MySqlCommand connCmd = conn.CreateCommand(); connCmd.CommandText = "INSERT INTO `whitelist`(steamId, isVip) VALUES (@steamId, @isVip)"; // Mysql Query connCmd.Parameters.AddWithValue("@steamId", hexId); // Mysql steamId variable connCmd.Parameters.AddWithValue("@isVip", isVip); // Mysql isVip variable // Console.WriteLine("User " + hexId + " added to database!"); // Nice info to user connCmd.ExecuteNonQuery(); // Execute sql query conn.Close(); // Close database / ssh connection } else { Console.WriteLine("Cannot establish mysql connection!"); // Tell user if we cant establish connection to server } } }
/// <summary> /// /// </summary> /// <param name="sshIp">ssh主机ip</param> /// <param name="sshPort">ssh主机端口</param> /// <param name="username">ssh主机用户名</param> /// <param name="password">ssh主机密码</param> /// <param name="lanIp">本地或者远程主机ip</param> /// <param name="lanPort">本地或者远程主机端口</param> /// <returns></returns> public static SshClient GetSshClient(EsConnectionInfo connInfo) { SshClient client; //input.localPort = 8001;//todo:需要去获取本机未用端口 try { PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(connInfo.sshIp, connInfo.sshPort, connInfo.username, connInfo.password); connectionInfo.Timeout = TimeSpan.FromSeconds(30); client = new SshClient(connectionInfo); //client.ErrorOccurred += Client_ErrorOccurred; client.Connect(); if (!client.IsConnected) { throw new Exception("SSH connect failed"); } var portFwdL = new ForwardedPortLocal(connInfo.localIp, (uint)connInfo.localPort, connInfo.esIp, (uint)connInfo.esPort); //映射到本地端口 client.AddForwardedPort(portFwdL); portFwdL.Start(); if (!client.IsConnected) { throw new Exception("Port forwarding failed"); } } catch (Exception ex) { throw ex; } return(client); }
private con_inf() { //主 SqlConn_master = "Database=person;Data Source=" + SqlIPA_master + ";Port=" + Sqlport_master + ";User Id=itoffice;Password=mrt123A/;CharSet=utf8";//这里的密码root是登陆数据库密码 connectionInfo_master = new PasswordConnectionInfo(SSHHost_master, SSHPort_master, SSHUser_master, SSHPassword_master); client_master = new SshClient(connectionInfo_master); client_master.Connect(); portFwdL_master = new ForwardedPortLocal(SqlIPA_master, Sqlport_master, SqlHost_master, Sqlport_master); //映射到本地端口 client_master.AddForwardedPort(portFwdL_master); portFwdL_master.Start(); conn_master = new MySqlConnection(SqlConn_master); myDataAdapter_master = new MySqlDataAdapter(); //从 SqlConn_node_1 = "Database=person;Data Source=" + SqlIPA_node_1 + ";Port=" + Sqlport_node_1 + ";User Id=itoffice;Password=mrt123A/;CharSet=utf8";//这里的密码root是登陆数据库密码 connectionInfo_node_1 = new PasswordConnectionInfo(SSHHost_node_1, SSHPort_node_1, SSHUser_node_1, SSHPassword_node_1); client_node_1 = new SshClient(connectionInfo_node_1); client_node_1.Connect(); portFwdL_node_1 = new ForwardedPortLocal(SqlIPA_node_1, Sqlport_node_1, SqlHost_node_1, Sqlport_node_1); //映射到本地端口 client_node_1.AddForwardedPort(portFwdL_node_1); portFwdL_node_1.Start(); conn_node_1 = new MySqlConnection(SqlConn_node_1); myDataAdapter_node_1 = new MySqlDataAdapter(); }
public static void updateItem(ItemModel item) { try { // ssh 접속 using (var client = new SshClient("106.10.57.242", 5000, "root", "qawzsx351")) { client.Connect(); if (client.IsConnected) { try { // 내부 db 접속을 위한 포트포워딩 var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); // db 접속 using (MySqlConnection con = new MySqlConnection("SERVER=localhost;PORT=3306;UID=root;PASSWORD=qawzsx351;DATABASE=codibook;SslMode=None")) { con.Open(); string query1 = "UPDATE item SET NAME='" + item.Name + "', LINK='" + item.Link + "', MEMO='" + item.Memo + "', SHOP='" + item.Shop_Name + "', PRICE=" + item.Price + ", LIKED=" + item.Liked + ", TEMP=" + item.Temp + " WHERE ITEM_ID=" + item.Item_ID; MySqlCommand sqlCom = new MySqlCommand(query1, con); sqlCom.ExecuteNonQuery(); for (int i = 0; i < item.Category.Count(); i++) { query1 = "UPDATE category SET CATEGORY='" + item.Category[i] + "' WHERE ITEM_ID=" + item.Item_ID; sqlCom = new MySqlCommand(query1, con); sqlCom.ExecuteNonQuery(); } con.Close(); client.Disconnect(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Client cannot be reached..."); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void A01_FirstTest() { var connectionInfo = new PasswordConnectionInfo(FIRST_HOP_HOST, FIRST_HOP_PORT, SSH_USERNAME1, SSH_PASSWORD1); using (var client = new SshClient(connectionInfo)) { client.Connect(); using (var forward = new ForwardedPortLocal(LOCAL_HOST, SECOND_HOP_HOST, SECOND_HOP_PORT)) { client.AddForwardedPort(forward); forward.Start(); var connectionInfo2 = new PasswordConnectionInfo(forward.BoundHost, (int)forward.BoundPort, SSH_USERNAME1, SSH_PASSWORD1); using (var client2 = new SshClient(connectionInfo2)) { client2.Connect(); var command = client2.RunCommand("ls -la"); Assert.That(command.Result, Is.Not.Empty); command.Dispose(); using (var forward2 = new ForwardedPortLocal(LOCAL_HOST, REMOTE_IP, REMOTE_PORT)) { client2.AddForwardedPort(forward2); forward2.Start(); Assert.That(forward2.IsStarted, Is.True); Assert.That(forward2.BoundHost, Is.EqualTo(LOCAL_HOST)); Assert.That(forward2.BoundPort, Is.GreaterThan(0)); } } } } }
public static void testc() { using (var client = new SshClient("101.132.76.165", "root", "ZhgZt20170904$$")) // establishing ssh connection to server where MySql is hosted { client.Connect(); if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3356, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection con = new MySqlConnection("Database = book_filing; Data Source =localhost; User Id = root; Password = 123456; charset = utf8; pooling = true")) { using (MySqlCommand com = new MySqlCommand("SELECT * FROM book_info", con)) { com.CommandType = CommandType.Text; DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter(com); da.Fill(ds); foreach (DataRow drow in ds.Tables[0].Rows) { Console.WriteLine("From MySql: " + drow[1].ToString()); } } } client.Disconnect(); } else { Console.WriteLine("Client cannot be reached..."); } } }
public MainWindow() { try { Client = new SshClient(sshHost, sshPort, sshUser, sshPassword); Client.KeepAliveInterval = new TimeSpan(0, 0, 30); // set interval to keep ssh thread alive. Client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20); // set timeout on trying the ssh connection Client.Connect(); } catch (Exception e) { var dlg = new ErrorBox("Please connect to the internet and try again."); dlg.ShowDialog(); Application.Current.Shutdown(); return; } var port = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); // local IP, local port, remote IP, remote port (need to explicitly state local IP here because program was using the wrong network adapter) Client.AddForwardedPort(port); port.Start(); Connection = new MySqlConnection(cs); Connection.Open(); InitializeComponent(); LaunchMenu Start = new LaunchMenu(this); MainContent.Content = Start; }
public string Connect() { var gatewayParams = endpoint.gateway.url.Split(':'); var gateway = gatewayParams[0]; var gatewayPort = Convert.ToInt32(gatewayParams[1]); var connectionInfo = new ConnectionInfo(gateway, gatewayPort, endpoint.gateway.credential.name, new PasswordAuthenticationMethod(endpoint.gateway.credential.name, endpoint.gateway.credential.plainPassword)); this.client = new SshClient(connectionInfo); client.Connect(); var portNumber = PortTool.GetFreePort((new Random()).Next(12000, 13000)); this.port = new ForwardedPortLocal("localhost", Convert.ToUInt32(portNumber), endpoint.internalIp, 3389); client.AddForwardedPort(port); port.Start(); CredentialsTool.DeleteCredentials("TERMSRV/localhost"); CredentialsTool.DeleteCredentials("localhost"); CredentialsTool.AddCredential("TERMSRV/localhost", endpoint.credential.name, endpoint.credential.plainPassword); String mstscCmd = $"/v:localhost:{portNumber}"; ProcessStartInfo mstscInfo = new ProcessStartInfo("mstsc.exe", mstscCmd); this.rdcProcess = new Process(); this.rdcProcess.StartInfo = mstscInfo; this.rdcProcess.Start(); this.rdcProcess.WaitForExit(); return(String.Format("{0}{3}{1}{3}{2}", $"localhost:{portNumber}", endpoint.credential.name, endpoint.credential.plainPassword, Environment.NewLine)); }
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); }
public void SSHConnectMySql() { string SSHHost = "101.132.76.165"; // SSH地址 int SSHPort = 22; // 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 = "Server=" + sqlIPA + ";Port=" + sqlport + ";Database=wdb007_dev;Uid=root;Pwd=Zt@165_20170906##;Pooling=false"; string sqlSELECT = "select * from book_info"; PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword); connectionInfo.Timeout = TimeSpan.FromSeconds(30); using (var client = new SshClient(connectionInfo)) { try { client.Connect(); if (!client.IsConnected) { MessageBox.Show("SSH connect failed"); } var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); //映射到本地端口 client.AddForwardedPort(portFwdL); portFwdL.Start(); if (!client.IsConnected) { MessageBox.Show("port forwarding failed"); } MySqlConnection conn = new MySqlConnection(sqlConn); MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(); myDataAdapter.SelectCommand = new MySqlCommand(sqlSELECT, conn); try { conn.Open(); DataSet ds = new DataSet(); myDataAdapter.Fill(ds); } catch (Exception ee) { MessageBox.Show(ee.Message); } finally { conn.Close(); } client.Disconnect(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public static void CreateSSHTunnel(Server server) { if (server.Ssh.KeyFilePath != null) { using (var stream = new FileStream(server.Ssh.KeyFilePath, FileMode.Open, FileAccess.Read)) { var privateKeyFile = new PrivateKeyFile(stream, server.Ssh.Password); var authenticationMethod = new PrivateKeyAuthenticationMethod(server.Ssh.User, privateKeyFile); var connectionInfo = new ConnectionInfo(server.Ssh.Server, server.Ssh.Port, server.Ssh.User, authenticationMethod); server.Ssh.Client = new SshClient(connectionInfo); } } else { server.Ssh.Client = new SshClient(server.Ssh.Server, server.Ssh.Port, server.Ssh.User, server.Ssh.Password); } server.Ssh.Client.Connect(); server.Ssh.ForwardedPort = FreePort(); var forwardedPort = new ForwardedPortLocal("localhost", (uint)server.Ssh.ForwardedPort, server.Address, server.Port); server.Ssh.Client.AddForwardedPort(forwardedPort); forwardedPort.Start(); }
public bool Open() { try { using (var client = new SshClient(_server, _user, _pass)) // 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(); client.Disconnect(); } } return(true); } catch (Exception) { MessageBox.Show("Ошибка подключения к защищенному серверу!", "Ошибка подключения!", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
//everything after this is should be in its own class. public static List <Properties> PopulatePropertiesList(List <Properties> propertiesList, string currentCounty) { 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 `Properties` WHERE county = @currentCounty", conn)) { conn.Open(); cmd.Parameters.AddWithValue("@currentCounty", currentCounty); cmd.ExecuteNonQuery(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Properties property = new Properties(reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString(), reader.GetValue(3).ToString(), reader.GetValue(4).ToString(), reader.GetValue(5).ToString(), reader.GetValue(6).ToString(), reader.GetValue(7).ToString(), reader.GetValue(8).ToString(), reader.GetValue(9).ToString(), reader.GetValue(10).ToString()); propertiesList.Add(property); } conn.Close(); } } client.Disconnect(); } return(propertiesList); }
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)); } } ); } }
//Creates an SSH connection to the server public static void ConnectSSH() { try { _sshClient.Connect(); if (_sshClient.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 1433, "127.0.0.1", 1433); _sshClient.AddForwardedPort(portForwarded); portForwarded.Start(); Console.WriteLine("Server reached."); } else { Console.WriteLine("Client cannot be reached..."); } } #region Exception handling SSH Connection catch (SshConnectionException e) { throw new SshConnectionException($"SSH connection failed: {e.Message}"); } catch (SshAuthenticationException e) { throw new SshAuthenticationException($"SSH authentication failed: {e.Message}"); } catch (Exception e) { throw new Exception($"Undetermined SSH error: {e.Message}"); } #endregion }
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); _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.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(); }
public void Cleanup() { if (_forwardedPort != null) { _forwardedPort.Dispose(); _forwardedPort = null; } }
public void ForwardedPortLocalConstructorTest1() { 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); Assert.Inconclusive("TODO: Implement code to verify target"); }
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."); }
public void Cleanup() { if (_forwardedPort != null) { _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(1)); _forwardedPort.Dispose(); _forwardedPort = null; } }
protected void Arrange() { _closingRegister = new List<EventArgs>(); _exceptionRegister = new List<ExceptionEventArgs>(); _forwardedPort = new ForwardedPortLocal("boundHost", "host", 22); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args); _forwardedPort.Dispose(); }
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)); _expectedElapsedTime = TimeSpan.FromMilliseconds(random.Next(100, 500)); _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port); _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _channelMock = new Mock<IChannelDirectTcpip>(MockBehavior.Strict); Socket handlerSocket = null; _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15)); _sessionMock.Setup(p => p.IsConnected).Returns(true); _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny<Socket>())).Callback<string, uint, IForwardedPort, Socket>((address, port, forwardedPort, socket) => handlerSocket = socket); _channelMock.Setup(p => p.Bind()).Callback(() => { Thread.Sleep(_expectedElapsedTime); if (handlerSocket != null && handlerSocket.Connected) handlerSocket.Shutdown(SocketShutdown.Both); }); _channelMock.Setup(p => p.Close()); _channelMock.Setup(p => p.Dispose()); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args); _forwardedPort.Session = _sessionMock.Object; _forwardedPort.Start(); _client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 500, SendTimeout = 500, SendBufferSize = 0 }; _stopwatch = new Stopwatch(); _stopwatch.Start(); _client.Connect(_localEndpoint); // give client socket time to establish connection Thread.Sleep(50); }
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)); _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.Dispose(); }
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)); _bindSleepTime = TimeSpan.FromMilliseconds(random.Next(100, 500)); _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint) _localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint) _remoteEndpoint.Port); _channelBindStarted = new ManualResetEvent(false); _channelBindCompleted = new ManualResetEvent(false); _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); _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny<Socket>())); _channelMock.Setup(p => p.Bind()).Callback(() => { _channelBindStarted.Set(); Thread.Sleep(_bindSleepTime); _channelBindCompleted.Set(); }); _channelMock.Setup(p => p.Dispose()); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args); _forwardedPort.Session = _sessionMock.Object; _forwardedPort.Start(); _client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 100, SendTimeout = 500, SendBufferSize = 0 }; _client.Connect(_localEndpoint); // wait for SOCKS client to bind to channel Assert.IsTrue(_channelBindStarted.WaitOne(TimeSpan.FromMilliseconds(200))); }
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)); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict); _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; }
protected void Arrange() { _closingRegister = new List<EventArgs>(); _exceptionRegister = new List<ExceptionEventArgs>(); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict); var sequence = new MockSequence(); _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); _connectionInfoMock.InSequence(sequence).Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(30)); _forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(), "host", 22); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args); _forwardedPort.Session = _sessionMock.Object; _forwardedPort.Start(); _forwardedPort.Dispose(); }
public void Cleanup() { if (_client != null) { _client.Dispose(); _client = null; } if (_forwardedPort != null) { _forwardedPort.Dispose(); _forwardedPort = null; } if (_channelBindStarted != null) { _channelBindStarted.Dispose(); _channelBindStarted = null; } if (_channelBindCompleted != null) { _channelBindCompleted.Dispose(); _channelBindCompleted = null; } }
private void SetupData() { 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)); _bindSleepTime = TimeSpan.FromMilliseconds(random.Next(100, 500)); _channelBound = new ManualResetEvent(false); _channelBindCompleted = new ManualResetEvent(false); _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; _client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 100, SendTimeout = 100, SendBufferSize = 0 }; }
public void Test_AddForwardedPort_Local_Hosts_Are_Null() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortLocal(null, 8080, null, 80); client.AddForwardedPort(port1); client.Disconnect(); } }
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); } } }
public void ConstructorShouldNotThrowExceptionWhenHostIsEmpty() { var host = string.Empty; var forwardedPort = new ForwardedPortLocal(Resources.HOST, 8080, string.Empty, 80); Assert.AreSame(host, forwardedPort.Host); }
public void ConstructorShouldNotThrowExceptionWhenHostIsInvalidDnsName() { const string host = "in_valid_host."; var forwardedPort = new ForwardedPortLocal(Resources.HOST, 8080, host, 80); Assert.AreSame(host, forwardedPort.Host); }
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_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."); } }