JAvaバックグラウンドをlinuxにアップロード

2930 ワード

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class Test {
    
    private static Logger logger = LoggerFactory.getLogger(Test.class);
    
    public static void main(String[] args) {
        String fileName = "img.jpg";
        String host = "192.168.1.1";//windos linux   IP   , linux   linux     、    ,         IP
        int port = 22;
        String username = "root";
        String password = "123456";
        try {
            InputStream is = new FileInputStream(new File("D:\\xxx\\test.jpg"));
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            logger.info("  Session……");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            logger.info("  Session……");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            logger.info("  Channel……");
            ChannelSftp sftp = (ChannelSftp) channel;

            sftp.cd("/usr/local/tomcat7/webapps/upload/");//               
            sftp.put(is, fileName, ChannelSftp.OVERWRITE);//       
            sshSession.disconnect();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  com.jcraft   jsch   0.1.50