public void CreateShellStreamTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value string terminalName = string.Empty; // TODO: Initialize to an appropriate value uint columns = 0; // TODO: Initialize to an appropriate value uint rows = 0; // TODO: Initialize to an appropriate value uint width = 0; // TODO: Initialize to an appropriate value uint height = 0; // TODO: Initialize to an appropriate value int bufferSize = 0; // TODO: Initialize to an appropriate value IDictionary<TerminalModes, uint> terminalModeValues = null; // TODO: Initialize to an appropriate value ShellStream expected = null; // TODO: Initialize to an appropriate value ShellStream actual; actual = target.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModeValues); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public void CreateShellStream2_NeverConnected() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password")) { const string terminalName = "vt100"; const uint columns = 80; const uint rows = 25; const uint width = 640; const uint height = 480; var terminalModes = new Dictionary<TerminalModes, uint>(); const int bufferSize = 4096; try { client.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModes); Assert.Fail(); } catch (SshConnectionException ex) { Assert.IsNull(ex.InnerException); Assert.AreEqual("Client not connected.", ex.Message); } } }
protected override async Task <PipePoint> ConnectImplAsync(CancellationToken cancel = default) { await Task.CompletedTask; cancel.ThrowIfCancellationRequested(); SshClient ssh; switch (Settings.AuthType) { case SecureShellClientAuthType.Password: ssh = new SshClient(Settings.TargetName, Settings.TargetPort, Settings.Username, Settings.Password); break; default: throw new ArgumentException(nameof(Settings.AuthType)); } ShellStream?stream = null; PipePoint? pipePointMySide = null; PipePoint? pipePointUserSide = null; PipePointSshShellStreamWrapper?pipePointWrapper = null; try { ssh.ConnectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, Settings.ConnectTimeoutMsecs); ssh.Connect(); stream = ssh.CreateShellStream("test", uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, 65536); //while (true) //{ // byte[] data = new byte[256]; // int x = stream.Read(data, 0, data.Length); // x._Print(); //} // Stream に標準入出力を接続する pipePointMySide = PipePoint.NewDuplexPipeAndGetOneSide(PipePointSide.A_LowerSide); pipePointUserSide = pipePointMySide.CounterPart._NullCheck(); pipePointWrapper = new PipePointSshShellStreamWrapper(pipePointMySide, stream); this.PipePointMySide = pipePointMySide; this.PipePointUserSide = pipePointUserSide; this.PipePointWrapper = pipePointWrapper; this.Ssh = ssh; this.Stream = stream; return(this.PipePointUserSide); } catch { pipePointMySide._DisposeSafe(); pipePointUserSide._DisposeSafe(); pipePointWrapper._DisposeSafe(); stream._DisposeSafe(); ssh._DisposeSafe(); throw; } }
private async Task OnEvent(WatcherEvent <V1Secret> e) { var id = KubernetesObjectId.For(e.Item.Metadata()); var item = e.Item; _logger.LogTrace("[{eventType}] {kind} {@id}", e.Type, e.Item.Kind, id); if (e.Type != WatchEventType.Added && e.Type != WatchEventType.Modified) { return; } if (!e.Item.Metadata.ReflectionAllowed() || !e.Item.Metadata.FortiReflectionEnabled()) { return; } if (!e.Item.Type.Equals("kubernetes.io/tls", StringComparison.InvariantCultureIgnoreCase)) { return; } var caCrt = Encoding.Default.GetString(item.Data["ca.crt"]); var tlsCrt = Encoding.Default.GetString(item.Data["tls.crt"]); var tlsKey = Encoding.Default.GetString(item.Data["tls.key"]); var tlsCerts = tlsCrt.Split(new[] { "-----END CERTIFICATE-----" }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.TrimStart()) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => $"{s}-----END CERTIFICATE-----") .ToList(); var hostSecretIds = item.Metadata.FortiReflectionHosts().Select(s => new KubernetesObjectId(s)).ToList(); var fortiCertName = item.Metadata.FortiCertificate(); var fortiCertId = !string.IsNullOrWhiteSpace(fortiCertName) ? fortiCertName : item.Metadata.Name.Substring(0, Math.Min(item.Metadata.Name.Length, 30)); foreach (var hostSecretId in hostSecretIds) { _logger.LogDebug( "Reflecting {secretId} to FortiOS device using host secret {hostSecretId}.", id, hostSecretId, hostSecretId); string fortiHost; string fortiUsername; string fortiPassword; try { var hostSecret = await _apiClient.ReadNamespacedSecretAsync(hostSecretId.Name, string.IsNullOrWhiteSpace(hostSecretId.Namespace) ?e.Item.Metadata.NamespaceProperty : hostSecretId.Namespace); if (hostSecret.Data is null || !hostSecret.Data.Keys.Any()) { _logger.LogWarning("Cannot reflect {secretId} to {hostSecretId}. " + "Host secret {hostSecretId} has no data.", id, hostSecretId, hostSecretId); continue; } fortiHost = hostSecret.Data.ContainsKey("host") ? Encoding.Default.GetString(hostSecret.Data["host"]) : null; fortiUsername = hostSecret.Data.ContainsKey("username") ? Encoding.Default.GetString(hostSecret.Data["username"]) : null; fortiPassword = hostSecret.Data.ContainsKey("password") ? Encoding.Default.GetString(hostSecret.Data["password"]) : null; } catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { _logger.LogWarning( "Cannot reflect {secretId} to {hostSecretId}. Host secret {hostSecretId} not found.", id, hostSecretId, hostSecretId); continue; } if (string.IsNullOrWhiteSpace(fortiHost) || string.IsNullOrWhiteSpace(fortiUsername) || string.IsNullOrWhiteSpace(fortiPassword)) { _logger.LogWarning( "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " + "Host secret {hostSecretId} must contain 'host', 'username' and 'password' values.", id, hostSecretId, hostSecretId); continue; } var hostParts = fortiHost.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()) .Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); if (!hostParts.Any() || hostParts.Count > 2) { _logger.LogWarning( "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " + "Host secret {hostSecretId} contains invalid 'host' data. " + "'host' must be in the format 'host:port' where port is optional.", id, hostSecretId, hostSecretId); } var hostPort = hostParts.Count < 2 ? 22 : int.TryParse(hostParts.Last(), out var port) ? port : 22; using var client = new SshClient(hostParts.First(), hostPort, fortiUsername, fortiPassword) { ConnectionInfo = { Timeout = TimeSpan.FromSeconds(10) } }; try { _logger.LogDebug("Connecting for FortiOS device at {host}", fortiHost); client.Connect(); } catch (Exception exception) { _logger.LogError(exception, "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId} due to exception.", id, hostSecretId); continue; } _logger.LogDebug("Checking for certificate {certId} on FortiOS device {host}", fortiCertId, fortiHost); string checkOutput; await using (var shell = client.CreateShellStream(nameof(FortiMirror), 128, 1024, 800, 600, 1024)) { var lastLine = string.Empty; var outputBuilder = new StringBuilder(); shell.WriteLine("config vpn certificate local"); shell.WriteLine($"edit {fortiCertId}"); shell.WriteLine("show full"); shell.WriteLine("end"); while (!(lastLine.Contains("#") && lastLine.Contains("end"))) { lastLine = shell.ReadLine(); outputBuilder.AppendLine(lastLine); } shell.Close(); checkOutput = outputBuilder.ToString(); } var localCertificateUpToDate = true; if (!string.IsNullOrWhiteSpace(tlsKey)) { if (checkOutput.Contains("unset private-key")) { localCertificateUpToDate = false; } } if (!checkOutput.Contains("set certificate", StringComparison.InvariantCultureIgnoreCase)) { localCertificateUpToDate = false; } else { var remoteCertificate = checkOutput.Substring(checkOutput.IndexOf("set certificate \"", StringComparison.InvariantCultureIgnoreCase)); remoteCertificate = remoteCertificate.Replace("set certificate \"", string.Empty, StringComparison.InvariantCultureIgnoreCase); remoteCertificate = remoteCertificate.Substring(0, remoteCertificate.IndexOf("\"", StringComparison.InvariantCultureIgnoreCase)); remoteCertificate = remoteCertificate.Replace("\r", string.Empty); if (!tlsCerts.Select(s => s.Replace("\r", string.Empty)).Contains(remoteCertificate)) { localCertificateUpToDate = false; } } var success = true; if (!localCertificateUpToDate) { var commandBuilder = new StringBuilder(); commandBuilder.AppendLine("config vpn certificate local"); commandBuilder.AppendLine($"edit {fortiCertId}"); commandBuilder.AppendLine($"set private-key \"{tlsKey}\""); commandBuilder.AppendLine($"set certificate \"{tlsCrt}\""); commandBuilder.AppendLine("end"); var command = client.RunCommand(commandBuilder.ToString()); if (command.ExitStatus != 0 || !string.IsNullOrWhiteSpace(command.Error)) { _logger.LogWarning( "Checking for certificate {certId} could not be installed on FortiOS device {host} due to error: {error}", id, fortiHost, command.Error); success = false; } } if (!localCertificateUpToDate && success) { var caCerts = tlsCerts.ToList(); if (!string.IsNullOrWhiteSpace(caCrt)) { caCerts.Add(caCrt); } var caId = 0; for (var i = 0; i < caCerts.Count; i++) { _logger.LogDebug("Installing CA certificate {index} for {certId} on FortiOS device {host}", i + 1, id, fortiHost); var commandBuilder = new StringBuilder(); commandBuilder.AppendLine("config vpn certificate ca"); commandBuilder.AppendLine( $"edit {fortiCertId}_CA{(caId == 0 ? string.Empty : caId.ToString())}"); commandBuilder.AppendLine($"set ca \"{tlsCerts[i]}\""); commandBuilder.AppendLine("end"); var command = client.RunCommand(commandBuilder.ToString()); if (command.ExitStatus == 0 && string.IsNullOrWhiteSpace(command.Error)) { caId++; continue; } if (command.Error.Contains("This CA certificate is duplicated.")) { _logger.LogWarning( "Skipping CA certificate {index} since it is duplicated by another certificate.", i + i); } else if (command.Error.Contains("Input is not a valid CA certificate.")) { _logger.LogDebug("Skipping CA certificate {index} since it is not a valid CA certificate.", i + i); } else { _logger.LogWarning("Could not install CA {index} certificate due to error: {response}", i + 1, command.Result); success = false; } } } if (!success) { _logger.LogError( "Reflecting {secretId} to FortiOS device using host secret {hostSecretId} completed with errors.", id, hostSecretId); } else if (!localCertificateUpToDate) { _logger.LogInformation("Reflected {secretId} to FortiOS device using host secret {hostSecretId}.", id, hostSecretId); } } }
/// <summary> /// Runs in a new thread /// </summary> /// <param name="connectionData">The connection data.</param> /// <param name="command">The command string.</param> private void sshThreadRunner(ConnectionData connectionData, string command) { using (SshClient sshClient = new SshClient(connectionData.Hostname, 22, connectionData.UserName, connectionData.Password)) { try { sshClient.ErrorOccurred += SshClient_ErrorOccurred; this._eventaggregator.GetEvent <SshClientStatusMessageEvent>().Publish(new SshClientStatusMessage() { Sender = this, MessageType = SshClientStatusMessageType.Connecting }); sshClient.Connect(); IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>(); termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53); ShellStream shellStream = sshClient.CreateShellStream("text", 200, 24, 800, 600, 1024, termkvp); Console.WriteLine("Verbunden mit: {0}", connectionData.Hostname); this._eventaggregator.GetEvent <SshClientStatusMessageEvent>().Publish(new SshClientStatusMessage() { Sender = this, MessageType = SshClientStatusMessageType.Connected, MessageText = string.Format("Connected to: {0}", connectionData.Hostname) }); string response = shellStream.Expect(new Regex(@"[$>]")); //expect user prompt shellStream.WriteLine(command); Thread.Sleep(500); while (!this._terminateThread) { Console.WriteLine("Still listening on ssh..."); // Todo: read the data //response = shellStream.Expect(new Regex(@"[$>]")); //expect user prompt response = shellStream.Expect(new Regex(@"([$#>:])")); //expect password or user prompt //check to send password if (response.Contains(string.Format("password for {0}:", connectionData.UserName))) { //send password shellStream.WriteLine(connectionData.Password); } else { ParseResponseData(response); } Thread.Sleep(10); } } catch (ThreadAbortException e) { this._terminateThread = true; this._isSessionRunning = false; this._eventaggregator.GetEvent <SshClientStatusMessageEvent>().Publish(new SshClientStatusMessage() { Sender = this, MessageType = SshClientStatusMessageType.Disconnected }); Thread.ResetAbort(); } catch (Exception e) { this._terminateThread = true; this._eventaggregator.GetEvent <SshClientStatusMessageEvent>().Publish(new SshClientStatusMessage() { Sender = this, MessageType = SshClientStatusMessageType.ConnectionError, MessageText = e.Message }); sshClient.Disconnect(); this._isSessionRunning = false; } sshClient.Disconnect(); this._eventaggregator.GetEvent <SshClientStatusMessageEvent>().Publish(new SshClientStatusMessage() { Sender = this, MessageType = SshClientStatusMessageType.Disconnected }); this._isSessionRunning = false; } }
public SSHHelper() { ConnectionInfo connectionInfo = new ConnectionInfo("ru.strygwyr.top", "root", new PasswordAuthenticationMethod("root", "fanzs900839")); SshClient ssh = new SshClient(connectionInfo); var stre = ssh.CreateShellStream("a", 0, 0, 0, 0, 1024); }
// ====================================開通按鈕==================================== private void Button4_Click(object sender, EventArgs e) { OLT_DIC OLTIP = new OLT_DIC(); using (var client = new SshClient(OLTIP.Find_DIC(comboBox3.Text), 22, "admin", "123")) { // 建立連線 client.Connect(); // 連線參數 var stream = client.CreateShellStream("", 0, 0, 0, 0, 0); string GP = $@" en config t gp " ; string GP_Port = $@" gp {ONT_Profile.Slot}/{ONT_Profile.Port} " ; Thread.Sleep(5000); stream.WriteLine(GP); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.Dba_profile()); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.Vlan_profile()); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.Traffic_profile()); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.Onu_profile()); Thread.Sleep(2000); stream.WriteLine(GP_Port); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.GPON_OLT()); Thread.Sleep(2000); stream.WriteLine("exit"); stream.WriteLine("bridge"); Thread.Sleep(2000); stream.WriteLine(ONT_Profile.OLT_Vlan()); // 輸出結果 string line; while ((line = stream.ReadLine(TimeSpan.FromSeconds(2))) != null) { Console.WriteLine(line); } // 結束連線 stream.Close(); client.Disconnect(); WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer(); wplayer.URL = $@"{AppDomain.CurrentDomain.BaseDirectory}DATA/MIC03.mp3"; wplayer.controls.play(); MessageBox.Show("開通完畢!"); } }
public static ExtShellStream CreateExtShellStream(this SshClient sc, string termName, uint rows, uint cols, uint width, uint height, int bufSize) => new ExtShellStream(sc.CreateShellStream(termName, rows, cols, width, height, bufSize));
private bool ConnectToUnix() { string result = "", s; string passPhrase = null; try { if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName)) { Reporter.ToLog(eLogLevel.WARN, "One of Settings of Agent is Empty "); throw new Exception("One of Settings of Agent is Empty "); } if (Password == null) { Password = ""; } try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port); } catch (Exception) { Reporter.ToLog(eLogLevel.WARN, "Error Connecting to Host: " + Host + " with Port: " + Port); throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port); } var connectionInfo = new ConnectionInfo(Host, Port, UserName, new PasswordAuthenticationMethod(UserName, Password) ); if (!string.IsNullOrEmpty(PrivateKeyPassPhrase)) { passPhrase = PrivateKeyPassPhrase; } if (File.Exists(PrivateKey)) { connectionInfo = new ConnectionInfo(Host, Port, UserName, new PasswordAuthenticationMethod(UserName, Password), new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase) ) ); } UnixClient = new SshClient(connectionInfo); UnixClient.Connect(); if (UnixClient.IsConnected) { UnixClient.SendKeepAlive(); ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024); mConsoleDriverWindow.ConsoleWriteText("Connected!"); s = ss.ReadLine(new TimeSpan(0, 0, 2)); while (!String.IsNullOrEmpty(s)) { result = result + "\n" + s; s = ss.ReadLine(new TimeSpan(0, 0, 2)); } mConsoleDriverWindow.ConsoleWriteText(result); return(true); } else { Reporter.ToLog(eLogLevel.WARN, "Error connecting to UnixServer - " + Host); throw new Exception("Error connecting to UnixServer - " + Host); } } catch (Exception e) { ErrorMessageFromDriver = e.Message; return(false); } }