0 votes
by (270 points)

Hello.
I want to add a button to connect VPN and also receive an obtained IP address.
The code is below:

var virtualssh = new Rebex.Net.Ssh();
virtualssh.Connect(IP);
virtualssh.Login(user, password);
var vterminal = new VirtualTerminal(80, 25);
vterminal.Bind(virtualssh);
vterminal.Scripting.Prompt = "$ ";
vterminal.Scripting.SendCommand("sudo openvpn ~/vpn/file.ovpn");

The output is the following

2023-04-08 06:52:22 WARNING: Compression for receiving enabled. Compression has been used in the past to break encryption. Sent packets are not compressed unless "allow-compression yes" is also set.
....
2023-04-08 06:52:24 net_addr_v4_add: 10.10.16.48/23 dev tun2
....
2023-04-08 06:52:24 Initialization Sequence Completed

How to read this output from the virtual terminal? ReadUntilPrompt doesn't fit because the command doesn't return to prompt
Many thanks

1 Answer

0 votes
by (73.5k points)
selected by
 
Best answer

You can process the openvpn command like this:

var scripting = virtualssh.StartScripting();
scripting.DetectPrompt();

scripting.SendCommand("sudo openvpn ~/vpn/file.ovpn");

var completed = ScriptEvent.FromString("Initialization Sequence Completed");
var response = scripting.ReadUntil(completed, ScriptEvent.Prompt, ScriptEvent.Timeout);
if (scripting.LastResult.IsEventMatched(completed))
{
    Console.WriteLine("Operation completed successfully. Parsing IP address from:");
    Console.WriteLine(response);

    IPAddress ipAddress;
    if (!TryParseIpAddressFromResponse(response, out ipAddress))
    {
        Console.WriteLine("Cannot parse IP address.");
    }
    else
    {
        Console.WriteLine("Obtained IP address is: {0}", ipAddress);
    }
}
else
{
    Console.WriteLine("Operation failed:");
    Console.WriteLine(response);
}

Then parse the IP address from received response as you like. It can be done fore example like this (but I am not sure how you want to handle the 10.10.16.48/23 value):

private static bool TryParseIpAddressFromResponse(string response, out IPAddress ipAddress)
{
    string find = "net_addr_v4_add: ";
    int idx1 = response.IndexOf(find) + find.Length;
    int idx2 = response.IndexOf('/', idx1);
    if (idx1 < find.Length || idx2 < idx1)
    {
        ipAddress = null;
        return false;
    }
    return IPAddress.TryParse(response.Substring(idx1, idx2 - idx1), out ipAddress);
}
...