java后台上传到linux

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();
        }
    }
}

<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.50</version>
</dependency>

posted @ 2015-11-05 16:27  呱哇  阅读(1483)  评论(0编辑  收藏  举报