forked from wubbl0rz/VmChamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SshCommand.cs
57 lines (42 loc) · 1.54 KB
/
SshCommand.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
using System.CommandLine;
using System.CommandLine.Completions;
using Spectre.Console;
namespace VmChamp;
public class SshCommand : Command
{
private readonly AppConfig _appConfig;
public SshCommand(AppConfig appConfig) : base("ssh", "connect to vm via ssh")
{
_appConfig = appConfig;
Argument<string> nameArgument = new("name",
() => appConfig.DefaultVmName,
"Name of the new VM");
this.AddArgument(nameArgument);
nameArgument.AddCompletions((ctx) =>
Helper.GetAllVmInDirectory(_appConfig.DataDir)
.Select(vmName => new CompletionItem(vmName ?? "")));
nameArgument.AddCompletions((ctx) =>
Helper.GetAllVmInDirectory(_appConfig.DataDir)
.Select(vmName => new CompletionItem(vmName ?? "")));
this.SetHandler((vmName) =>
{
var user = _appConfig.DefaultUser;
var vmDir = Path.Combine(_appConfig.DataDir, vmName);
var userFromIso = Helper.GetUserFromIso(vmDir);
if (userFromIso != "N/A" && userFromIso != _appConfig.DefaultUser)
{
user = userFromIso;
}
AnsiConsole.MarkupLine($"✈️ Connect to: {vmName}. USER: {user}");
using var libvirtConnection = LibvirtConnection.CreateForSession();
var vmId = Interop.virDomainLookupByName(libvirtConnection.NativePtr, vmName);
var vmIp = Interop.GetFirstIpById(vmId);
if (vmIp == null)
{
AnsiConsole.MarkupLine($"No network found for VM: {vmName}");
return;
}
Helper.ConnectViaSsh(user, vmIp)?.WaitForExit();
}, nameArgument);
}
}