2
0

HostConfig.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System.Net;
  2. using System.Text.RegularExpressions;
  3. namespace Renci.SshNet.IntegrationTests
  4. {
  5. class HostConfig
  6. {
  7. private static readonly Regex HostsEntryRegEx = new Regex(@"^(?<IPAddress>[\S]+)\s+(?<HostName>[a-zA-Z]+[a-zA-Z\-\.]*[a-zA-Z]+)\s*(?<Aliases>.+)*$", RegexOptions.Singleline);
  8. public List<HostEntry> Entries { get; }
  9. private HostConfig()
  10. {
  11. Entries = new List<HostEntry>();
  12. }
  13. public static HostConfig Read(ScpClient scpClient, string path)
  14. {
  15. HostConfig hostConfig = new HostConfig();
  16. using (var ms = new MemoryStream())
  17. {
  18. scpClient.Download(path, ms);
  19. ms.Position = 0;
  20. using (var sr = new StreamReader(ms, Encoding.ASCII))
  21. {
  22. string line;
  23. while ((line = sr.ReadLine()) != null)
  24. {
  25. // skip comments
  26. #if NET
  27. if (line.StartsWith('#'))
  28. #else
  29. if (line.StartsWith("#"))
  30. #endif
  31. {
  32. continue;
  33. }
  34. var hostEntryMatch = HostsEntryRegEx.Match(line);
  35. if (!hostEntryMatch.Success)
  36. {
  37. continue;
  38. }
  39. var entryIPAddress = hostEntryMatch.Groups["IPAddress"].Value;
  40. var entryAliasesGroup = hostEntryMatch.Groups["Aliases"];
  41. var entry = new HostEntry(IPAddress.Parse(entryIPAddress), hostEntryMatch.Groups["HostName"].Value);
  42. if (entryAliasesGroup.Success)
  43. {
  44. var aliases = entryAliasesGroup.Value.Split(' ');
  45. foreach (var alias in aliases)
  46. {
  47. entry.Aliases.Add(alias);
  48. }
  49. }
  50. hostConfig.Entries.Add(entry);
  51. }
  52. }
  53. }
  54. return hostConfig;
  55. }
  56. public void Write(ScpClient scpClient, string path)
  57. {
  58. using (var ms = new MemoryStream())
  59. using (var sw = new StreamWriter(ms, Encoding.ASCII))
  60. {
  61. // Use linux line ending
  62. sw.NewLine = "\n";
  63. foreach (var hostEntry in Entries)
  64. {
  65. sw.Write(hostEntry.IPAddress);
  66. sw.Write(" ");
  67. sw.Write(hostEntry.HostName);
  68. if (hostEntry.Aliases.Count > 0)
  69. {
  70. sw.Write(" ");
  71. for (var i = 0; i < hostEntry.Aliases.Count; i++)
  72. {
  73. if (i > 0)
  74. {
  75. sw.Write(' ');
  76. }
  77. sw.Write(hostEntry.Aliases[i]);
  78. }
  79. }
  80. sw.WriteLine();
  81. }
  82. sw.Flush();
  83. ms.Position = 0;
  84. scpClient.Upload(ms, path);
  85. }
  86. }
  87. }
  88. }