RemoteSshd.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. namespace Renci.SshNet.IntegrationTests
  2. {
  3. internal class RemoteSshd
  4. {
  5. private readonly IConnectionInfoFactory _connectionInfoFactory;
  6. public RemoteSshd(IConnectionInfoFactory connectionInfoFactory)
  7. {
  8. _connectionInfoFactory = connectionInfoFactory;
  9. }
  10. public RemoteSshdConfig OpenConfig()
  11. {
  12. return new RemoteSshdConfig(this, _connectionInfoFactory);
  13. }
  14. public RemoteSshd Restart()
  15. {
  16. // Restart SSH daemon
  17. using (var client = new SshClient(_connectionInfoFactory.Create()))
  18. {
  19. client.Connect();
  20. // Kill all processes that start with 'sshd' and that run as root
  21. var stopCommand = client.CreateCommand("sudo pkill -9 -U 0 sshd.pam");
  22. var stopOutput = stopCommand.Execute();
  23. if (stopCommand.ExitStatus != 0)
  24. {
  25. throw new ApplicationException($"Stopping ssh service failed with exit code {stopCommand.ExitStatus}.\r\n{stopOutput}\r\n{stopCommand.Error}");
  26. }
  27. var resetFailedCommand = client.CreateCommand("sudo /usr/sbin/sshd.pam");
  28. var resetFailedOutput = resetFailedCommand.Execute();
  29. if (resetFailedCommand.ExitStatus != 0)
  30. {
  31. throw new ApplicationException($"Reset failures for ssh service failed with exit code {resetFailedCommand.ExitStatus}.\r\n{resetFailedOutput}\r\n{resetFailedCommand.Error}");
  32. }
  33. }
  34. // Socket fails on Linux, reporting inability early. This is the Linux behavior by design.
  35. // https://github.com/dotnet/runtime/issues/47484#issuecomment-769239699
  36. // At this point we have to wait until the ssh server in the container is available after reconfiguration.
  37. if (Environment.OSVersion.Platform == PlatformID.Unix)
  38. {
  39. Thread.Sleep(300);
  40. }
  41. return this;
  42. }
  43. }
  44. }