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>
原文:http://www.cnblogs.com/linying/p/4939967.html