SshConnectionDisruptor.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. namespace Renci.SshNet.IntegrationTests
  2. {
  3. internal class SshConnectionDisruptor
  4. {
  5. private readonly IConnectionInfoFactory _connectionInfoFactory;
  6. public SshConnectionDisruptor(IConnectionInfoFactory connectionInfoFactory)
  7. {
  8. _connectionInfoFactory = connectionInfoFactory;
  9. }
  10. public SshConnectionRestorer BreakConnections()
  11. {
  12. var client = new SshClient(_connectionInfoFactory.Create());
  13. client.Connect();
  14. PauseSshd(client);
  15. return new SshConnectionRestorer(client);
  16. }
  17. private static void PauseSshd(SshClient client)
  18. {
  19. using (var command = client.CreateCommand("sudo echo 'DenyUsers sshnet' >> /etc/ssh/sshd_config"))
  20. {
  21. var output = command.Execute();
  22. if (command.ExitStatus != 0)
  23. {
  24. throw new ApplicationException(
  25. $"Blocking user sshnet failed with exit code {command.ExitStatus}.\r\n{output}\r\n{command.Error}");
  26. }
  27. }
  28. using (var command = client.CreateCommand("sudo pkill -9 -U sshnet -f sshd-session.pam"))
  29. {
  30. var output = command.Execute();
  31. if (command.ExitStatus != 0)
  32. {
  33. throw new ApplicationException(
  34. $"Killing sshd-session.pam service failed with exit code {command.ExitStatus}.\r\n{output}\r\n{command.Error}");
  35. }
  36. }
  37. }
  38. }
  39. }