Java e SFTP - resolvido

Estou tentando o usar o JSch()

package br.com.ghnetsoft.gestaovendasatendimento.crud.service;

import java.io.File;
import java.io.Serializable;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import br.com.ghnetsoft.gestaovendasatendimento.model.enuns.TipoArquivoServidorEnum;
import br.com.ghnetsoft.principal.exception.GeralException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ServidorArquivoService implements Serializable {

    private static final long serialVersionUID = 7798947448926686641L;
    @Value("${usuario.servidor.arquivo}")
    private String usuario;
    @Value("${senha.servidor.arquivo}")
    private String senha;
    @Value("${host.servidor.arquivo}")
    private String host;
    @Value("${porta.servidor.arquivo}")
    private Integer porta;
    @Value("${tipo.servidor.arquivo}")
    private String tipoArquivo;

    public String importar(final File arquivo, final TipoArquivoServidorEnum tipo) {
        try {
            final JSch jsch = new JSch();
            final String caminho = host + tipo.getDescricao() + tipoArquivo + arquivo.getName();
            log.info("caminho: " + caminho);
            log.info("porta: " + porta);
            log.info("senha: " + senha);
            log.info("usuario: " + usuario);
            log.info("tipo: " + tipo.getDescricao());
            final Session jschSession = jsch.getSession(usuario, host, porta);
            jschSession.setPassword(senha);
            jschSession.setConfig("StrictHostKeyChecking", "no");
            jschSession.connect();
            final Channel channel = jschSession.openChannel("sftp");
            final ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get("remote-file", "local-file");
            channel.connect();
            sftpChannel.exit();
            jschSession.disconnect();
            return caminho;
        } catch (final JSchException | SftpException e) {
            log.error(e.getMessage(), e);
            throw new GeralException("Erro ao salvar arquivo no servidor !");
        }
    }
}

Só que dá este erro

com.jcraft.jsch.SftpException: 
	at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1003)
	at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:888)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.ServidorArquivoService.importar(ServidorArquivoService.java:51)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.ArquivoService.servidorArquivo(ArquivoService.java:66)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.ArquivoService$$FastClassBySpringCGLIB$$bbf69a5c.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.ArquivoService$$EnhancerBySpringCGLIB$$22098875.servidorArquivo(<generated>)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselArquivoService.salvar(CarouselArquivoService.java:49)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselArquivoService$$FastClassBySpringCGLIB$$e8e18bdc.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselArquivoService$$EnhancerBySpringCGLIB$$446d4cf5.salvar(<generated>)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselService.salvar(CarouselService.java:64)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselService$$FastClassBySpringCGLIB$$e0cdd8a1.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.service.CarouselService$$EnhancerBySpringCGLIB$$c2f1d664.salvar(<generated>)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.resource.CarouselResource.inserir(CarouselResource.java:48)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
	at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at br.com.ghnetsoft.gestaovendasatendimento.crud.config.SmpleCORSFilter.doFilter(SmpleCORSFilter.java:48)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException: null
	at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:901)
	... 129 common frames omitted

AInda não coneguir entender como faço a tranaferencia do arquivo

Alterar de

sftpChannel.get(“remote-file”, “local-file”);

para

sftpChannel.get(arquivo.getPath(), caminhoServidor);

Esta variável caminhoServidor esta assim

final String caminhoServidor = tipo.getDescricao() + tipoArquivo + arquivo.getName();, que é o caminho para onde vai a imagem

Essa lib JSch é para tentar resolver o problema que vc estava nesse post: Alterar nome do arquivo MultipartFile - resolvido?

Esse lugar onde vc está tentando gravar esse arquivo é simplesmente uma pasta compartilhada na rede?

Resolvi abrir outro tópico porque entendi que são diferentes

Com comandos SSH o pessoal da rede diz que consegue incluir arquivos na pasta.

É que já precisei adicionar arquivos em um compartilhamento na rede, e usei o JCIFS, mas não sei se é o seu caso, pq o compartilhamento que precisei gravar aqruivos era de uma rede windows.

Mas como fazer o que preciso ?

Alguma outra biblioteca ?

O compartilhamento onde vc precisa gravar e arquivo pode ser acessado via samba (SMB), ex.: smb://caminho/pasta/compartilhada?

1 curtida

Quando usei o JCIFS, para gravar um arquivo, o código ficou mais ou menos assim:

String url = "smb://caminho/arquivo/compartilhamento/arquivo.txt";
SmbFileOutputStream out = null;

try {
  NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
    null, 
    null, 
    null
  ); // sem autenticação

  SmbFile file = new SmbFile(url, auth);
  out = new SmbFileOutputStream(file);
  out.write(text.getBytes());
  out.flush();
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (out != null) {
    out.close();
  }
}
1 curtida

De acordo com o pessoal da infra, este SMB, tem que ser SFTP

1 curtida

Pior que nunca usei esse JSCH. Mas nesse link: https://www.baeldung.com/java-file-sftp, ele tem exemplos do JSHC e outras libs.

1 curtida

Fiz assim

public String importar(final File arquivo, final TipoArquivoServidorEnum tipo) {
    try {
        final JSch jsch = new JSch();
        jsch.setKnownHosts("/Users/john/.ssh/known_hosts");
        final String caminhoServidor = tipo.getDescricao() + tipoArquivo + arquivo.getName();
        final String caminho = host + caminhoServidor;
        final Session jschSession = jsch.getSession(usuario, ip, porta);
        jschSession.setPassword(senha);
        jschSession.setConfig("StrictHostKeyChecking", "no");
        jschSession.connect();
        final Channel channel = jschSession.openChannel("sftp");
        final ChannelSftp sftpChannel = (ChannelSftp) channel;
        sftpChannel.put(arquivo.getPath(), caminhoServidor);
        channel.connect();
        sftpChannel.exit();
        jschSession.disconnect();
        return caminho;
    } catch (final JSchException | SftpException e) {
        log.error(e.getMessage(), e);
        throw new GeralException("Erro ao salvar arquivo no servidor !");
    }
}
1 curtida

Está com este erro

2021-12-17 12:50:43 - b.c.g.g.c.s.ServidorArquivoService - java.net.UnknownHostException: "ip"
com.jcraft.jsch.JSchException: java.net.UnknownHostException: "ip"

Este erro é bem autoexplicativo. Em algum lugar onde deverias ter o ip da máquina de destino, tens a String "ip"

Provavelmente tens String ip = "ip";

2 curtidas

Não coloquei o IP. Mas tem uma variavel ip

@Value("${ip.servidor.arquivo}")
private String ip;

Aqui aparece é o ip mesmo

com.jcraft.jsch.JSchException: java.net.UnknownHostException: "ip"

Qual o valor dessa prop: ip.servidor.arquivo?

O problema é o ip estava com aspas

A própria mensagem de erro mostra …

1 curtida

Agora o erro é este

2021-12-17 14:49:22 - b.c.g.g.c.s.ServidorArquivoService - java.lang.NullPointerException
com.jcraft.jsch.SftpException: java.lang.NullPointerException
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:487)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:365)
at br.com.ghnetsoft.gestaovendasatendimento.crud.service.ServidorArquivoService.importar(ServidorArquivoService.java:50)

Estava assim

sftpChannel.put(arquivo.getPath(), caminhoServidor);
channel.connect();

Mudei para

channel.connect();
sftpChannel.put(arquivo.getPath(), caminhoServidor);
1 curtida

E deu certo?

1 curtida

Deu sim

Valeu novamente @Lucas_Camara

1 curtida