ssh-handler.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // SSH Handler
  2. //
  3. // Douglas Thrift
  4. //
  5. // ssh-handler.cs
  6. /* Copyright 2013 Douglas Thrift
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Diagnostics;
  23. using System.IO;
  24. using System.Text;
  25. using System.Text.RegularExpressions;
  26. using System.Windows.Forms;
  27. using Microsoft.Win32;
  28. public class SshHandler
  29. {
  30. private enum Handler { Unspecified, Putty };
  31. private static Handler handler = Handler.Unspecified;
  32. private static string puttyPath = null;
  33. public static int Main(string[] args)
  34. {
  35. Application.EnableVisualStyles();
  36. try
  37. {
  38. Regex usage = new Regex(@"^(?:/|--?)(?:h|help|usage|\?)$", RegexOptions.IgnoreCase);
  39. Regex putty = new Regex(@"^(?:/|--?)putty(?:[:=](?<putty_path>.*))?$", RegexOptions.IgnoreCase);
  40. Uri uri = null;
  41. foreach (string arg in args)
  42. {
  43. if (usage.IsMatch(arg))
  44. return Usage(0);
  45. Match match;
  46. if ((match = putty.Match(arg)).Success)
  47. {
  48. handler = Handler.Putty;
  49. Group group = match.Groups["putty_path"];
  50. if (group.Success)
  51. puttyPath = group.Value;
  52. }
  53. else
  54. uri = new Uri(arg, UriKind.Absolute);
  55. }
  56. if (uri != null)
  57. switch (handler)
  58. {
  59. case Handler.Unspecified:
  60. if (FindPutty())
  61. Putty(uri);
  62. else
  63. throw new Exception("Could not find a suitable SSH application.");
  64. break;
  65. case Handler.Putty:
  66. Putty(uri);
  67. break;
  68. }
  69. else
  70. return Usage(1);
  71. }
  72. catch (Exception exception)
  73. {
  74. MessageBox.Show(exception.Message, "SSH Handler Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  75. return 2;
  76. }
  77. return 0;
  78. }
  79. private static int Usage(int code)
  80. {
  81. MessageBox.Show("ssh-handler [/putty[:<putty-path>]] <ssh-url>\n\n" +
  82. "/putty[:<putty-path>] -- Use PuTTY to connect", "SSH Handler Usage", MessageBoxButtons.OK, MessageBoxIcon.Information);
  83. return code;
  84. }
  85. private static void UserPassword(Uri uri, out string user, out string password)
  86. {
  87. if (uri.UserInfo.Length != 0)
  88. {
  89. string[] userInfo = uri.UserInfo.Split(new char[] { ':' }, 2);
  90. user = userInfo[0];
  91. password = userInfo.Length == 2 ? userInfo[1] : null;
  92. }
  93. else
  94. {
  95. user = null;
  96. password = null;
  97. }
  98. }
  99. private static bool FindPutty()
  100. {
  101. if (puttyPath != null)
  102. goto found;
  103. foreach (RegistryHive hive in new RegistryHive[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine })
  104. {
  105. IList<RegistryView> views = new List<RegistryView>(new RegistryView[] { RegistryView.Registry32 });
  106. if (Environment.Is64BitOperatingSystem)
  107. views.Insert(0, RegistryView.Registry64);
  108. foreach (RegistryView view in views)
  109. using (RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view), key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\PuTTY_is1"))
  110. if (key != null)
  111. {
  112. string path = (string)key.GetValue("InstallLocation");
  113. if (path == null)
  114. continue;
  115. puttyPath = Path.Combine(path, "putty.exe");
  116. if (File.Exists(puttyPath))
  117. {
  118. Debug.WriteLine("Found PuTTY in registry: {0}", puttyPath, null);
  119. goto found;
  120. }
  121. else
  122. puttyPath = null;
  123. }
  124. }
  125. foreach (string path in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator))
  126. {
  127. puttyPath = Path.Combine(path, "putty.exe");
  128. if (File.Exists(puttyPath))
  129. {
  130. Debug.WriteLine("Found PuTTY in path: {0}", puttyPath, null);
  131. goto found;
  132. }
  133. else
  134. puttyPath = null;
  135. }
  136. return false;
  137. found:
  138. puttyPath = puttyPath.Trim();
  139. return true;
  140. }
  141. private static void Putty(Uri uri)
  142. {
  143. if (!FindPutty())
  144. throw new Exception("Could not find PuTTY executable.");
  145. string user, password;
  146. UserPassword(uri, out user, out password);
  147. StringBuilder args = new StringBuilder();
  148. if (password != null)
  149. args.AppendFormat("-pw {0} ", password);
  150. if (uri.Port != -1)
  151. args.AppendFormat("-P {0} ", uri.Port);
  152. if (user != null)
  153. args.AppendFormat("{0}@", user);
  154. args.Append(uri.Host);
  155. Debug.WriteLine("Running PuTTY command: {0} {1}", puttyPath, args);
  156. Process.Start(puttyPath, args.ToString());
  157. }
  158. }