`
aimer311
  • 浏览: 94749 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

使用jsch实现文件上传

    博客分类:
  • java
阅读更多

仅提供代码作为参考,

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.jcraft.jsch.Channel;
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 com.shonetown.common.util.log.EventLog;

/**
 * In order for SSH2 tunneling to function correctly one must ensure that the
 * following line is uncommented in /etc/ssh/sshd_config :
 * --------------------------CUT-------------------------------
 * # Change to yes to enable tunnelled clear text passwords
 * PasswordAuthentication yes
 * --------------------------CUT-------------------------------
 * Otherwise the initiation of the tunnel will fail with
 * "SSH Initialization failed, try again?
 * com.jcraft.jsch.JSchException: Auth fail"
 * @author aimer.xu
 *
 */
public class SftpHelper extends Thread {
	private static EventLog log = new EventLog(SftpHelper.class);
	
	private String host;
	private String username;
	private String password;
	private String location;
	private int port;
	private String knowHosts;
	
	private String osName;
	
	private List<String> filenames = new ArrayList<String>();
	
	public SftpHelper(String host, String username, String password, int port) {
		this(host, username, password, port, "");
	}
	
	public SftpHelper(String host, String username, String password, int port, String location) {
		this.host = host;
		this.username = username;
		this.password = password;
		this.port = port;
		osName = System.getProperty("os.name");
		if (osName.toUpperCase().indexOf("WINDOWS") > -1) {
            this.knowHosts = "c:\\known_hosts";
            if(location == null || location.length() == 0){
    			this.location = "c:\\";
    		}
        } else {
        	this.knowHosts = "/root/.ssh/known_hosts";
        	if(location == null || location.length() == 0){
    			this.location = "/";
    		}
        }
		this.location = location;
	}
	
	public void addFilename(String filename){
		filenames.add(filename);
	}
	
	public void setFilenames(List<String> filenames){
		this.filenames = filenames;
	}

	public void run(){
		upload();
	}
	
	/**
	 * 要上传的文件必须包含完整的路径
	 * 
	 */
	public boolean upload(){
		if(filenames.size() == 0)
			return false;
		Session session;
		Channel channel;
		JSch jsch = new JSch();
		try {
			jsch.setKnownHosts(knowHosts);
			session = jsch.getSession(username, host, port);
			session.setPassword(password);
			session.connect();
			channel = session.openChannel("sftp");
			channel.connect();
			ChannelSftp c = (ChannelSftp)channel;
			c.cd(location);
			
			InputStream in = null;
			OutputStream out = null;
			for(int i=0; i<filenames.size(); i++){
				String filename = filenames.get(i);
				if(filename == null || "".equals(filename)){
					log.Debug("", "当前没有要上传的文件!");
					continue;
				}
				int idx= filename.lastIndexOf(File.separator);
				String uploadname = filename.substring(idx==-1?0:idx+1);
				out = c.put(uploadname);
				log.Debug("", "sleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeep "+5000+"ms!");
				sleep(5000);
				
				in = new FileInputStream(filename);
				
//				String suffix = filename.substring(filename.lastIndexOf(".")+1);
//				if("gz".equals(suffix)){
//					in = new GZIPInputStream(in);
//				}
				byte [] b = new byte[1024];
				int n;
				while ((n = in.read(b)) != -1) {
					out.write(b);
				}
			}
			out.flush();
			out.close();
			in.close();
			c.disconnect();
			session.disconnect();
			sleep(500);
			return true;
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (SftpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch(InterruptedException e){
			e.printStackTrace();
		}
		return false;
	}
	
	public static void main(String[] args){
		String username = "root";
		String host = "*.*.*.*";
		int port = 22;
		String password = "******";
		String path = "/home/data/download/";
		SftpHelper helper = new SftpHelper(host, username,password, port,path);
		helper.addFilename("c:\\bcp.sql");
		helper.addFilename("c:\\a.sql");
//		helper.upload("c:\\bcp.sql");
		helper.start();
		
	}
}

 请注意类的注释部分,known_hosts文件的内容如下:

202.7.3.190 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEA6tHmMBQwcSieFneaObnDyzthMSn1FyWFp/TCMV4rt+ZEtOZo49GK0kdM3tYy1IQD8hZz016JG5uOIbrBN+O0BtzY89y3uIwo0hsYQtP/LKAR5BU+pT3R20ltVbcEGzrSpKiSClObD9MbiOt0899Du9bG89/BiMvxUxj/Rhg33l0=

 

 写道
附:产生此文件的简单方法:可以在Linux中用ssh命令登录一次,这样便在/root/.ssh(假如使用root用户登录到Linux)目录下生成known_hosts文件。

 这片文章也许对你更有帮助:http://www.blogjava.net/fastzch/archive/2008/07/08/213477.html

0
0
分享到:
评论
2 楼 MrCrapBag 2013-02-06  
/**
* In order for SSH2 tunneling to function correctly one must ensure that the
* following line is uncommented in /etc/ssh/sshd_config :
* --------------------------CUT-------------------------------
* # Change to yes to enable tunnelled clear text passwords
* PasswordAuthentication yes
* --------------------------CUT-------------------------------
* Otherwise the initiation of the tunnel will fail with
* "SSH Initialization failed, try again?
* com.jcraft.jsch.JSchException: Auth fail"
* @author aimer.xu
*
*/

这个类的说明很重要...

如果连接的时候报了com.jcraft.jsch.JSchException: Auth fail" 这样的错误,把/etc/ssh/sshd_config中的PasswordAuthentication 配置改成yes即可,即允许使用密码进行认证
1 楼 jn_nian 2012-03-22  
无法做到要上传的文件包含完整的路径,在各个浏览器里都不一样

相关推荐

Global site tag (gtag.js) - Google Analytics