如何通过固定出站端口连接SFTP服务器?
问题:强制SFTP连接使用指定本地端口发起通信
我用C#编写了一个命令行程序,通过Renci.SSHNet库连接不同SFTP服务器下载文件。其中某台SFTP服务器的管理员要求,连接该服务器时不仅要对接指定端口,还必须从客户端的特定本地端口发起连接。我希望通过代码实现这一要求,不想求助网管修改路由规则。
我尝试用本地端口转发做测试,但发现只有SSH ACK报文通过指定的localPort,其余通信仍然使用随机空闲端口。我的测试代码如下:
string sshSrv = "127.0.0.1"; // Local SSH server string sshUser = "user"; string sshPass = "pass"; int sshPort = 22; string sftpSrv = "192.168.1.120"; // SFTP test server string sftpUser = "tester"; string sftpPass = "password"; uint sftpPort = 2222; string localSrv = "127.0.0.1"; int localPort = 51000; // The outgoing traffic must go through this port. ConnectionInfo sshCI = new ConnectionInfo(sshSrv, sshPort, sshUser, new PasswordAuthenticationMethod(sshUser, sshPass)); using (SshClient sshClient = new SshClient(sshCI)) { ForwardedPort fwdPortL = null; try { sshClient.KeepAliveInterval = new TimeSpan(0, 0, 20); sshClient.Connect(); fwdPortL = new ForwardedPortLocal(localSrv, (uint)localPort, sftpSrv, sftpPort); fwdPortL.Exception += delegate (object sender, ExceptionEventArgs e) { Console.WriteLine("ForwardedPortLocal Exception: " + e.Exception.ToString()); }; fwdPortL.RequestReceived += delegate (object sender, PortForwardEventArgs e) { Console.WriteLine($"Request Received: {e.OriginatorHost}:{e.OriginatorPort}"); }; sshClient.AddForwardedPort(fwdPortL); fwdPortL.Start(); using (SftpClient sftpClient = new SftpClient(localSrv, localPort, sftpUser, sftpPass)) { sftpClient.Connect(); // Stuff to test SFTP connection... sftpClient.Disconnect(); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.ToString()); } finally { fwdPortL?.Stop(); sshClient.Disconnect(); } }
内容的提问来源于stack exchange,提问作者Óscar Alberto Fernández Muñoz
相关产品推荐
相关产品推荐

