Search code examples
javaspringsshsftpprivate-key

SFTP with DefaultSftpSessionFactory by SSH trust throws exception


I have requirement to download/upload all txt file from SFTP server. I am using Spring configuration as org.springframework.integration.sftp.session.DefaultSftpSessionFactory and inbound its throws ServletContext resource not found. Here password would be blank

<bean id="acceptAllFileListFilter" class="org.springframework.integration.file.filters.AcceptAllFileListFilter" />


<bean id="inboundSftpSessionFactory" class="org.springframework.integration.file.remote.session.CachingSessionFactory">
    <constructor-arg ref="inboundDefaultSftpSessionFactory" />
</bean>

<bean id="inboundDefaultSftpSessionFactory" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="${sftp.host}" />
        <property name="privateKey" value="/home/tech/id_rsa"/>
        <property name="privateKeyPassphrase" value="${sftp.private.key.passphrase}"/>
        <property name="port" value="${sftp.port}" />       
        <property name="user" value="${sftp.user}" /> 
        <property name="password" value="${sftp.password}" />
    </bean>

....

Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/home/tech/id_rsa]

        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)

        at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.initJschSession(DefaultSftpSessionFactory.java:371)

        at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:347)

        ... 27 more

File is exist at specified location

when i tried with password configuration then its working fine.


Solution

  • The file isn't at the specified location, as it tries to load the file from the root of the application and it isn't located there. It is located on the file system but that isn't what you specified.

    Prefix the property value with file:.

    <bean id="inboundDefaultSftpSessionFactory" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="${sftp.host}" />
        <property name="privateKey" value="file:/home/tech/id_rsa"/>
        <property name="privateKeyPassphrase" value="${sftp.private.key.passphrase}"/>
        <property name="port" value="${sftp.port}" />       
        <property name="user" value="${sftp.user}" /> 
        <property name="password" value="${sftp.password}" />
    </bean>
    

    See the reference guide for more information on resource loading.