Thursday, 19 September 2013

Upload via SFTP in Java

1. Add Maven dependency:
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.42</version>
        </dependency>

2. Java code:

import java.io.File;
import java.io.FileInputStream;

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


public class TestJSftp {
      
    public static void upload(String username,
                              String password,
                              String host,
                              int port,
                              String workingDir,
                              String localFilename){
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, port);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp channelSftp = (ChannelSftp) channel;
            channelSftp.cd(workingDir);
   
            File f1 = new File(localFilename);
            channelSftp.put(new FileInputStream(f1), f1.getName(), ChannelSftp.OVERWRITE);
               
            channelSftp.exit();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}







3 comments:

  1. Is there a way to use ChannelSftp with sudo command?

    ReplyDelete
    Replies
    1. There is a post here: http://stackoverflow.com/questions/13152627/is-there-any-jsch-channelsftps-function-work-like-command-cp

      Delete
  2. http://www.jcraft.com/jsch/examples/Sudo.java.html

    ReplyDelete