HostConfig.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 (line.StartsWith("#"))
  27. {
  28. continue;
  29. }
  30. var hostEntryMatch = HostsEntryRegEx.Match(line);
  31. if (!hostEntryMatch.Success)
  32. {
  33. continue;
  34. }
  35. var entryIPAddress = hostEntryMatch.Groups["IPAddress"].Value;
  36. var entryAliasesGroup = hostEntryMatch.Groups["Aliases"];
  37. var entry = new HostEntry(IPAddress.Parse(entryIPAddress), hostEntryMatch.Groups["HostName"].Value);
  38. if (entryAliasesGroup.Success)
  39. {
  40. var aliases = entryAliasesGroup.Value.Split(' ');
  41. foreach (var alias in aliases)
  42. {
  43. entry.Aliases.Add(alias);
  44. }
  45. }
  46. hostConfig.Entries.Add(entry);
  47. }
  48. }
  49. }
  50. return hostConfig;
  51. }
  52. public void Write(ScpClient scpClient, string path)
  53. {
  54. using (var ms = new MemoryStream())
  55. using (var sw = new StreamWriter(ms, Encoding.ASCII))
  56. {
  57. // Use linux line ending
  58. sw.NewLine = "\n";
  59. foreach (var hostEntry in Entries)
  60. {
  61. sw.Write(hostEntry.IPAddress);
  62. sw.Write(" ");
  63. sw.Write(hostEntry.HostName);
  64. if (hostEntry.Aliases.Count > 0)
  65. {
  66. sw.Write(" ");
  67. for (var i = 0; i < hostEntry.Aliases.Count; i++)
  68. {
  69. if (i > 0)
  70. {
  71. sw.Write(' ');
  72. }
  73. sw.Write(hostEntry.Aliases[i]);
  74. }
  75. }
  76. sw.WriteLine();
  77. }
  78. sw.Flush();
  79. ms.Position = 0;
  80. scpClient.Upload(ms, path);
  81. }
  82. }
  83. }
  84. public class HostEntry
  85. {
  86. public HostEntry(IPAddress ipAddress, string hostName)
  87. {
  88. IPAddress = ipAddress;
  89. HostName = hostName;
  90. Aliases = new List<string>();
  91. }
  92. public IPAddress IPAddress { get; private set; }
  93. public string HostName { get; set; }
  94. public List<string> Aliases { get; }
  95. }
  96. }