scp via java

前端 未结 15 1029
粉色の甜心
粉色の甜心 2020-11-27 13:06

What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libr

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 14:00

    Here is an example to upload a file using JSch:

    ScpUploader.java:

    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 java.io.ByteArrayInputStream;
    import java.util.Properties;
    
    public final class ScpUploader
    {
        public static ScpUploader newInstance()
        {
            return new ScpUploader();
        }
    
        private volatile Session session;
        private volatile ChannelSftp channel;
    
        private ScpUploader(){}
    
        public synchronized void connect(String host, int port, String username, String password) throws JSchException
        {
            JSch jsch = new JSch();
    
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
    
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig(config);
            session.setInputStream(System.in);
            session.connect();
    
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
        }
    
        public synchronized void uploadFile(String directoryPath, String fileName, byte[] fileBytes, boolean overwrite) throws SftpException
        {
            if(session == null || channel == null)
            {
                System.err.println("No open session!");
                return;
            }
    
            // a workaround to check if the directory exists. Otherwise, create it
            channel.cd("/");
            String[] directories = directoryPath.split("/");
            for(String directory : directories)
            {
                if(directory.length() > 0)
                {
                    try
                    {
                        channel.cd(directory);
                    }
                    catch(SftpException e)
                    {
                        // swallowed exception
    
                        System.out.println("The directory (" + directory + ") seems to be not exist. We will try to create it.");
    
                        try
                        {
                            channel.mkdir(directory);
                            channel.cd(directory);
                            System.out.println("The directory (" + directory + ") is created successfully!");
                        }
                        catch(SftpException e1)
                        {
                            System.err.println("The directory (" + directory + ") is failed to be created!");
                            e1.printStackTrace();
                            return;
                        }
    
                    }
                }
            }
    
            channel.put(new ByteArrayInputStream(fileBytes), directoryPath + "/" + fileName, overwrite ? ChannelSftp.OVERWRITE : ChannelSftp.RESUME);
        }
    
        public synchronized void disconnect()
        {
            if(session == null || channel == null)
            {
                System.err.println("No open session!");
                return;
            }
    
            channel.exit();
            channel.disconnect();
            session.disconnect();
    
            channel = null;
            session = null;
        }
    }
    

    AppEntryPoint.java:

    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.SftpException;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public final class AppEntryPoint
    {
        private static final String HOST = "192.168.1.1";
        private static final int PORT = 22;
        private static final String USERNAME = "root";
        private static final String PASSWORD = "root";
    
        public static void main(String[] args) throws IOException
        {
            ScpUploader scpUploader = ScpUploader.newInstance();
    
            try
            {
                scpUploader.connect(HOST, PORT, USERNAME, PASSWORD);
            }
            catch(JSchException e)
            {
                System.err.println("Failed to connect the server!");
                e.printStackTrace();
                return;
            }
    
            System.out.println("Successfully connected to the server!");
    
            byte[] fileBytes = Files.readAllBytes(Paths.get("C:/file.zip"));
    
            try
            {
                scpUploader.uploadFile("/test/files", "file.zip", fileBytes, true); // if overwrite == false, it won't throw exception if the file exists
                System.out.println("Successfully uploaded the file!");
            }
            catch(SftpException e)
            {
                System.err.println("Failed to upload the file!");
                e.printStackTrace();
            }
    
            scpUploader.disconnect();
        }
    }
    

提交回复
热议问题