1 | initial version |
To open multiple local port forwarding using C#, you can use the following code snippet:
using System;
using System.Linq;
using System.Diagnostics;
using System.Net.Sockets;
public class LocalPortForwarding
{
private readonly Process _sshProcess;
private readonly int _localPort;
public LocalPortForwarding(string sshPath, int localPort, string remoteHost, int remotePort, string username, string password)
{
_localPort = localPort;
_sshProcess = new Process
{
StartInfo =
{
FileName = sshPath,
Arguments = $"-L {localPort}:{remoteHost}:{remotePort} {username}@{remoteHost}",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
// start SSH connection process
_sshProcess.Start();
// send the password to the SSH process
_sshProcess.StandardInput.WriteLine(password);
_sshProcess.StandardInput.Flush();
}
public void Dispose()
{
_sshProcess?.Dispose();
}
public static void OpenLocalPortForwardings(int[] localPorts, string remoteHost, int[] remotePorts, string username, string password)
{
// check inputs
if (localPorts.Length != remotePorts.Length)
{
throw new ArgumentException("Local and remote port arrays must have the same length.");
}
// start forwarding for each port
for (int i = 0; i < localPorts.Length; i++)
{
int localPort = localPorts[i];
int remotePort = remotePorts[i];
var forwarding = new LocalPortForwarding("ssh", localPort, remoteHost, remotePort, username, password);
if (forwarding._sshProcess != null)
{
Console.WriteLine($"Local port forwarding opened: {localPort} -> {remoteHost}:{remotePort}");
}
}
}
}
You can call the OpenLocalPortForwardings
method to open multiple local port forwardings, passing in the local ports, remote host, remote ports, username, and password. The method creates a LocalPortForwarding
object for each port and starts the SSH connection process in the constructor. The Dispose
method is used to clean up the SSH process when the LocalPortForwarding
object is no longer needed.