通过代理连接sftp

通过nginx代理连接sftp

  • 1.问题描述
  • 2.代码实现
  • 3.nginx配置
    • 3.1 创建sftp.stream文件
    • 3.2 修改nginx配置
  • 4.重启nginx生效

1.问题描述

问题是这样的。我们现在需要在微服务所在内网的A机器连接到外网的sftp,但是网络又不能直接到达。然后A机器到B机器是通过的,B机器到sftp的网络是通的,所以我们需要借助B机器进行转发。

通过代理连接sftp_第1张图片

2.代码实现

我们的代码是通过java的JSch实现的,下面给出简易实现

import com.jcraft.jsch.*;

class SFTPThroughTunnelExample {
    public static void main(String[] args) {
    	// 这个ip为B机器所在ip
        String host = "100.100.932.267";
        // 这个端口为B机器nginx所监听的端口
        int port = 66;
        String user = "sftp_user";
        String password = "sftp_passward";
        String remoteFilePath = "/path/to/remote/file.txt";
        String localFilePath = "/path/to/local/file.txt";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            System.out.println("连接上了");
            // 下载文件
            channelSftp.get(remoteFilePath, localFilePath);
            System.out.println("File downloaded successfully.");
            // 关闭连接
            channelSftp.exit();
            session.disconnect();
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
}

3.nginx配置

B机器的nginx配置如下:

3.1 创建sftp.stream文件

我的nginx部署路径在

 /usr/local/nginx/

文件所处路径为

/usr/local/nginx/conf/myconf/sftp.stream
server {
        listen 66;
        # 这里的ip为sftp机器真正的ip
        proxy_pass 471.121.194.34:667;
        proxy_connect_timeout 30s;
        proxy_timeout  24h;
}

3.2 修改nginx配置

nginx.conf 的路径在

/usr/local/nginx/conf/nginx.conf

修改nginx.conf,在最下面的位置新增如下内容

stream{
	include myconf/*.stream;	
}

4.重启nginx生效

cd /usr/local/nginx/sbin/
service nginx restart

重启之后运行java代码,即可以实现通过代理连接sftp

你可能感兴趣的:(问题处理,开发语言,java)