-
Notifications
You must be signed in to change notification settings - Fork 15
/
SSHManager.cs
65 lines (58 loc) · 2.16 KB
/
SSHManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.Configuration;
using System.Diagnostics;
namespace YSGM
{
public class SSHManager
{
string host;
string user;
string exePath;
public static SSHManager Instance = new();
private SSHManager()
{
#if DEBUG
host = "hk4e-storage.mihoyo.com";
user = ConfigurationManager.AppSettings.Get("SSH_USER")!;
#else
string? host = ConfigurationManager.AppSettings.Get("SSH_HOST")!;
string? user = ConfigurationManager.AppSettings.Get("SSH_USER")!;
#endif
// I can't use SSH.NET...
// FINE. I'll just make a child process
var enviromentPath = Environment.GetEnvironmentVariable("PATH");
if (enviromentPath == null) throw new Exception("PATH is null");
var paths = enviromentPath.Split(';');
exePath = paths.Select(x => Path.Combine(x, "ssh.exe"))
.Where(x => File.Exists(x))
.FirstOrDefault()!;
if (string.IsNullOrWhiteSpace(exePath) == true) throw new Exception("SSH not found");
}
public string Execute(string cmd)
{
Process p = new Process();
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
p.StartInfo.FileName = exePath;
p.StartInfo.Arguments = $"{user}@{host} -o LogLevel=error -q /bin/bash";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.Write(cmd);
p.StandardInput.Flush();
p.StandardInput.Close();
var output = "";
while (p.StandardOutput.EndOfStream == false)
{
string? line = p.StandardOutput.ReadLine();
if (line == null) break;
output += line;
#if DEBUG
Console.WriteLine($"[SSH] {line}");
#endif
}
return output!;
}
}
}