public void Dispose() { _shell?.Dispose(); _shell?.Close(); _sshClient?.Disconnect(); _sshClient?.Dispose(); }
public void Dispose() { ForwardedPort.Stop(); ForwardedPort.Dispose(); Ssh.Disconnect(); Ssh?.Dispose(); }
public void Dispose() { m_scpAdminClient?.Dispose(); m_sshUserClient?.Dispose(); m_scpUserClient?.Dispose(); m_scpAdminClient?.Dispose(); }
//Dispose implementation & Destructor public void Dispose() { _sftpClient?.Disconnect(); _sftpClient?.Dispose(); _sshClient?.Disconnect(); _sshClient?.Dispose(); }
public void Dispose() { sshClient?.Disconnect(); sshClient?.Dispose(); scpClient?.Disconnect(); scpClient?.Dispose(); }
public void Dispose() { lock (_lockObj) { _client?.Dispose(); _client = null; } }
protected virtual void Dispose(bool disposing) { if (disposing) { _sshClient?.Dispose(); _sshClient = null; } }
public void Dispose() { client?.Dispose(); shell?.Dispose(); outputReader?.Dispose(); textUpdater?.Dispose(); outputStreamWriter?.Dispose(); extendedOuput?.Dispose(); output?.Dispose(); input?.Dispose(); }
public void Dispose() { _shellStream?.Close(); _shellStream = null; _client?.Dispose(); _client = null; _sftp?.Dispose(); _sftp = null; _fsw?.Dispose(); _fsw = null; }
/// <inheritdoc /> public void Dispose() { try { ShellStream?.Dispose(); ShellStream = null; SshClient?.Dispose(); SshClient = null; Lines.Dispose(); } catch { // } }
/// <summary> /// Disconnects. /// </summary> /// <returns></returns> public override async Task Disconnect() { if (SshClient == null) { return; } this.WriteLog("Disconnecting..."); var ports = ForwardedPorts?.ToList(); if (ports?.Count > 0) { foreach (var pf in ports) { try { await pf.Disconnect(); } catch (Exception ex) { MyLogger.Log("Failed to close a forwarded port.", ex); } } ports.ForEach(x => Children.Remove(x)); this.WriteLog("Closed All Forwarded Ports."); } if (SshClient != null) { try { await Task.Run(() => { SshClient?.Disconnect(); SshClient?.Dispose(); SshClient = null; }); this.WriteLog("Disconnected."); } catch (Exception ex) { this.WriteLog("Failed to disconnect or dispose.", ex); } } await DisconnectRequiredConnection(); IsConnecting.Value = false; IsConnected.Value = false; }
public static async Task <SshClient> ConnectAsync(this SSHSettings sshSettings, CancellationToken cancellationToken = default) { if (sshSettings == null) { throw new ArgumentNullException(nameof(sshSettings)); } TaskCompletionSource <SshClient> tcs = new TaskCompletionSource <SshClient>(TaskCreationOptions.RunContinuationsAsynchronously); new Thread(() => { SshClient sshClient = null; try { sshClient = new SshClient(sshSettings.CreateConnectionInfo()); sshClient.HostKeyReceived += (object sender, Renci.SshNet.Common.HostKeyEventArgs e) => { if (sshSettings.TrustedFingerprints.Count == 0) { e.CanTrust = true; } else { e.CanTrust = sshSettings.IsTrustedFingerprint(e.FingerPrint, e.HostKey); } }; sshClient.Connect(); tcs.TrySetResult(sshClient); } catch (Exception ex) { tcs.TrySetException(ex); try { sshClient?.Dispose(); } catch { } } }) { IsBackground = true }.Start(); using (cancellationToken.Register(() => { tcs.TrySetCanceled(); })) { return(await tcs.Task); } }
protected void Arrange() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); var sequence = new MockSequence(); _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.Connect()); _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); _sshClient.Connect(); _sshClient.Dispose(); }
public SshClient CreateClient(TerminalOptions opts) { SshClient?.Dispose(); host = opts.Parameters[0]; SshConfig config = SshConfig.ParseFile(opts.ConfigFile); SshHost hostConfig = config.Compute(host); keypath = opts.Keypath ?? hostConfig.IdentityFile; if (keypath.Contains("~")) { keypath = keypath.Replace("~", homePath); } host = hostConfig.HostName; username = opts.User ?? hostConfig.User ?? Environment.UserName; password = opts.Password; ushort port = opts.Port; if (opts.Port == 0) { port = hostConfig["Port"] is string portStr?ushort.Parse(portStr) : (ushort)22; } bool PasswordAuthUsed = false; if (keypath == null) { if (password != null) { PasswordAuthUsed = true; } else { PasswordAuthUsed = hostConfig["PasswordAuthentication"] as string == "Yes"; } } if (PasswordAuthUsed) { return(new SshClient(host, port, username, password)); } PrivateKeyFile privateKeyFile = new PrivateKeyFile(keypath, password); return(new SshClient(host, port, username, privateKeyFile)); }
/// <summary> /// Disconnect SSH client from Host /// </summary> private static void DisconnectSSHClient() { try { if (client?.IsConnected ?? false) { client.Disconnect(); } } catch (Exception e) { } finally { client?.Dispose(); client = null; } }
private bool Reset(bool connect = true) { _ssh?.Dispose(); _ssh = null; SSHError = null; _sftp?.Dispose(); _sftp = null; SFTPError = null; if (connect) { bool cssh = false, csftp = false; try { cssh = SSH.IsConnected; } catch {} try { csftp = SFTP.IsConnected; } catch {} return(cssh && csftp); } else { return(false); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _shellStream?.Dispose(); _shellStream = null; _sshClient?.Dispose(); _sshClient = null; } _disposed = true; }
/// <summary> /// Disconnect SSH client from Host /// </summary> private static void DisconnectSSHClient() { try { if (client?.IsConnected ?? false) { client.Disconnect(); } } catch (Exception e) { Trace.TraceError("Failed to disconnect ssh client, remote session {0} ({1})", RemoteSessionID, e); } finally { client?.Dispose(); client = null; } }
/// <summary> /// Initiate graceful disconnect from client and clean up used resources /// </summary> public void Disconnect() { if (_sshClient != null) { if (_sshClient.IsConnected) { _sshClient.Disconnect(); } _sshClient.Dispose(); } if (_sftpClient != null) { if (_sftpClient.IsConnected) { _sftpClient.Disconnect(); } _sftpClient.Dispose(); } }
public void SSHRunCommandWithBuiltClient() { var sshClient = new SshClient("test.rebex.net", "demo", "password"); sshClient.Connect(); var runCommandActivity = new SSHRunCommandActivity { Command = "help", Timeout = TimeSpan.FromSeconds(3), SSHClient = new InArgument <SshClient>((ctx) => sshClient) }; var output = WorkflowInvoker.Invoke(runCommandActivity); sshClient.Disconnect(); sshClient.Dispose(); Assert.IsTrue(string.IsNullOrEmpty(Convert.ToString(output["Error"]))); Assert.IsFalse(string.IsNullOrEmpty(Convert.ToString(output["Result"]))); Assert.IsTrue(Convert.ToInt32(output["ExitStatus"]) == 0); }
private static void RebootByNetwork(string host, string user, string pass) { // Locals string rawASIC = ""; SshClient SSHclient; SshCommand SSHcmd; // Send reboot command to linux machine try { SSHclient = new SshClient(host, 22, user, pass); SSHclient.Connect(); SSHcmd = SSHclient.RunCommand("exec /sbin/reboot"); rawASIC = SSHcmd.Result.ToString(); SSHclient.Disconnect(); SSHclient.Dispose(); } catch { // do nothing for now } }
public void Stop() { if (_data != null) { try { // If the device has been unplugged, Close will throw an IOException. This is fine, we'll just keep cleaning up. _data.Close(); } catch (IOException) { } _data = null; if (_client != null) { _client.Disconnect(); _client.Dispose(); _client = null; } } if (_timer != null) { _timer.Stop(); _timer = null; } }
/// <summary> /// Sends a command with or without arguments to a remote SSH server, and then returns the response. (Ensure the response will be a single line with no required input!) /// </summary> /// <param name="address">The address to connect to</param> /// <param name="username">The username to use to connect with</param> /// <param name="password">The password for the username to connect to</param> /// <param name="scriptName">The name of the script to run</param> /// <param name="arguments">The arguments (if any) to send after the scriptName</param> /// <returns>Either the response from the remote client (prefixed with 'P'), or the error that occurred (prefixed with 'F')</returns> public static string SendCommand(string address, string username, string password, string scriptName, string arguments = "") { string response = string.Empty; try { SshClient client = new SshClient(address, username, password); client.Connect(); if (client.IsConnected) { SshCommand command = client.CreateCommand(string.Format("{0} {1}", scriptName, arguments)); command.Execute(); response = command.Result; } client.Disconnect(); client.Dispose(); } catch (Exception exception) { return("F" + exception.Message); // F = Fail } return("P" + response); // P = Pass }
public static void Login(string Host, string Username, string Password) { var SSH = new SshClient(Host, Username, Password); try { SSH.Connect(); var Command = SSH.RunCommand("uname -a"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\t[+] Username: "******" Password: "******"@" + Username + "@" + Password); if (Program.Telegram) { TelegramReport(Host, Username, Password, Command.Result.Replace("\n", "")); } } catch (SshAuthenticationException) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\t[-] Username: "******" Password: "******"\t[-] Connection Refused By Remote Host!"); Console.ForegroundColor = ConsoleColor.White; Thread.Sleep(100); } finally { SSH.Dispose(); } }
public IList <StreamServer> Start(IList <StreamServer> servers, string preCommand, string command) { for (int i = 0; i < servers.Count; i++) { try { var client = new SshClient(servers[i].Server.Ip, "root", servers[i].Server.RootPassword); client.Connect(); client.RunCommand(preCommand); var cmd = client.CreateCommand($"nohup {command} >/dev/null 2>&1 & echo $!"); var result = cmd.Execute(); int pid = int.Parse(result); client.RunCommand($"disown -h {pid}"); client.Disconnect(); client.Dispose(); servers[i].Pid = pid; } catch { throw new Exception($"Failed to start on server {servers[i].Server.Name}@{servers[i].Server.Ip}"); } } return(servers); }
public override async Task <int> CheckLatestTemperature(CancellationToken cancellationToken) { if (!Available) { this.client = new SshClient(this.Host, this.User, this.Password); client.Connect(); Available = true; } try { using (var command = client.RunCommand("sensors")) { //(?<=Core.\d+:\W*\+)\d*\.\d+ if (command.ExitStatus == 0) { var temps = this.retrieveTempRegex.Matches(command.Result).Select(x => float.Parse(x.Value)); return((int)temps.Max()); } else { throw new Exception(command.Error); } } } catch (Exception) { Available = false; throw; } finally { client.Disconnect(); client.Dispose(); } }
public void Stop() { if (_data != null) { // This should be fine, but on disconnect it locks up everything. No closing it doesn't seem to have any adverse effects. //try //{ // If the device has been unplugged, Close will throw an IOException. This is fine, we'll just keep cleaning up. // //_data.Close(); //} //catch (IOException) { } _data = null; if (_client != null) { _client.Disconnect(); _client.Dispose(); _client = null; } } if (_timer != null) { _timer.Stop(); _timer = null; } }
private void sysmem_Click(object sender, EventArgs e) { // for debug // string test_str = "Filesystem Size Used Avail Use% Mounted on\nudev 10M 0 10M 0% /dev\ntmpfs 99M 440K 98M 1% /run\n/dev/mmcblk1p2 3.4G 2.4G 843M 74% /\ntmpfs 246M 0 246M 0% /dev/shm\ntmpfs 246M 0 246M 0% /sys/fs/cgroup\ntmpfs 100M 0 100M 0% /run/user\ntmpfs 5.0M 0 5.0M 0% /run/lock\n/dev/mmcblk0p1 30G 2.8G 27G 10% /var/APM/logs\n/dev/mmcblk1p1 96M 76M 21M 79% /boot/uboot\n"; // TODO: check system memory, status... // download syslog //update version string farring_IP = "11.0.0.1"; string user_name = "root"; string farring_pwd = "9HKBtB4K"; using (var client = new SshClient(farring_IP, user_name, farring_pwd)) { // connect try { client.Connect(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } if (!client.IsConnected) { CustomMessageBox.Show("无法连接到飞控板,请重试!"); return; } try { string res = client.RunCommand("df -h").Result; string[] info = res.Split('\n'); const int padding_len = 12; string result_str = "内存名称".PadRight(padding_len) + "总大小".PadRight(padding_len - 4) + "已使用".PadRight(padding_len - 3) + "未使用".PadRight(padding_len - 3) + "内存占用率".PadRight(padding_len / 2) + "\n\n"; string res1; foreach (string info_item in info) { // TF card if (info_item.Contains("/dev/mmcblk0p1")) { res1 = @info_item; int unused_idx = res1.LastIndexOf("%") + 1; int str_len = res1.Length; string unused_str = res1.Substring(unused_idx, (str_len - unused_idx)); res1 = res1.Replace(unused_str, ""); res1 = res1.Replace("/dev/mmcblk0p1", "日志分区".PadRight(padding_len / 4)); res1 = Regex.Replace(res1, @"\s+", " "); result_str += res1.Replace(" ", " ") + "\n\n"; } else if (info_item.Contains("/dev/mmcblk1p1")) { res1 = info_item; int unused_idx = res1.LastIndexOf("%") + 1; int str_len = res1.Length; string unused_str = res1.Substring(unused_idx, (str_len - unused_idx)); res1 = res1.Replace(unused_str, ""); res1 = res1.Replace("/dev/mmcblk1p1", "启动分区".PadRight(padding_len / 4)); res1 = Regex.Replace(res1, @"\s+", " "); result_str += res1.Replace(" ", " ") + "\n\n"; } if (info_item.Contains("/dev/mmcblk1p2")) { res1 = info_item; int unused_idx = res1.LastIndexOf("%") + 1; int str_len = res1.Length; string unused_str = res1.Substring(unused_idx, (str_len - unused_idx)); res1 = res1.Replace(unused_str, ""); res1 = res1.Replace("/dev/mmcblk1p2", "系统分区".PadRight(padding_len / 4)); res1 = Regex.Replace(res1, @"\s+", " "); result_str += res1.Replace(" ", " ") + "\n\n"; } } CustomMessageBox.Show(result_str, Strings.Done); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } client.Disconnect(); client.Dispose(); } }
private void downsyslog_Click(object sender, EventArgs e) { // if (status == SerialStatus.Done) { // AB ZhaoYJ@2017-03-28 for user-defined dir to save log // ========= start ========= string save_dir = ""; DateTime now = System.DateTime.Now; string save_file = "[系统日志]" + now.Year + "年" + now.Month + "月" + now.Day + "日" + now.Hour + "时" + now.Minute + "分" + now.Second + "秒" + ".slog"; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.RestoreDirectory = true; saveFileDialog1.Filter = "系统日志|*.slog"; saveFileDialog1.Title = "保存系统日志文件"; saveFileDialog1.FileName += save_file; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { save_dir = Path.GetDirectoryName(saveFileDialog1.FileName.ToString()); } else { return; } // download syslog //update version string farring_IP = "11.0.0.1"; string user_name = "root"; string farring_pwd = "9HKBtB4K"; using (var client = new SshClient(farring_IP, user_name, farring_pwd)) { // connect try { client.Connect(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } if (!client.IsConnected) { CustomMessageBox.Show("无法连接到飞控板,请重试!"); return; } try { // tar syslog client.RunCommand("cd /var/APM/logs"); client.RunCommand("rm -rf /var/APM/logs/tmp_syslog; mkdir -p /var/APM/logs/tmp_syslog;"); client.RunCommand("cp -rf /var/log/ /var/APM/logs/tmp_syslog; cp -f /var/APM/logs/run.log /var/APM/logs/tmp_syslog; cp -f /var/APM/logs/update_log /var/APM/logs/tmp_syslog; cp -f /root/app /var/APM/logs/tmp_syslog; cp -f /var/APM/ArduCopter.stg /var/APM/logs/tmp_syslog; cp -f /root/SN /var/APM/logs/tmp_syslog"); client.RunCommand("cd /var/APM/logs; tar -czf tmp.tar.gz tmp_syslog;sync;sync"); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } // get syslog var sftp_inst = new SftpClient(farring_IP, 22, user_name, farring_pwd); sftp_inst.Connect(); if (sftp_inst.IsConnected) { var fileStream = File.OpenWrite(@save_dir + "\\" + save_file); if (fileStream != null) { // try { sftp_inst.DownloadFile("/var/APM/logs/tmp.tar.gz", fileStream); sftp_inst.Disconnect(); sftp_inst.Dispose(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } } } else { CustomMessageBox.Show("无法连接到飞控板,请重试!"); return; } try { // clean up client.RunCommand("rm -fr /var/APM/logs/tmp.tar.gz /var/APM/logs/tmp_syslog"); client.Disconnect(); client.Dispose(); } catch (Exception ex) { CustomMessageBox.Show(ex.Message, Strings.ERROR); } CustomMessageBox.Show("系统日志文件下载成功", Strings.Done); } } }
public override void Dispose() { SshClient?.Dispose(); SshClient = null; }
private SshCommand[] SendCommand(string[] theCommands, bool WaitForResult = true) { SshCommand[] Response = new SshCommand[theCommands.Length]; Task <SshCommand>[] Tasks = new Task <SshCommand> [theCommands.Length]; var client = new SshClient(IPAddressTextBox.Text, UserNameTextBox.Text, PasswordTextBox.Text); try { client.Connect(); } catch (System.Net.Sockets.SocketException theException) { AppendTextOutputWindow(theException.Message); } catch (Renci.SshNet.Common.SshConnectionException theException) { AppendTextOutputWindow(theException.Message); } catch (Renci.SshNet.Common.SshAuthenticationException theException) { AppendTextOutputWindow(theException.Message); } if (client.IsConnected) { for (int i = 0; i < theCommands.Length; i++) { int index = i; Tasks[index] = Task.Run(() => { try { return(client.RunCommand(theCommands[index])); } catch (Exception ex) { AppendTextOutputWindow(ex.Message); return(null); } }); } if (WaitForResult) { if (!Task.WaitAll(Tasks, 5000)) { return(new SshCommand[0]); } try { client.Disconnect(); } catch (ObjectDisposedException theException) { AppendTextOutputWindow(theException.Message); } for (int i = 0; i < theCommands.Length; i++) { Response[i] = Tasks[i].Result; } client.Dispose(); } else { Task.Delay(3000).ContinueWith(T => { client.Dispose(); }); return(new SshCommand[0]); } } else { return(new SshCommand[0]); } return(Response); }