今天碰到个问题,在windows想下载linux服务器上的文件,看下有什么代码实现,当然可以利用工具比如SecureCRT,网上搜索找到答案

1. java使用jsch包实现远程访问

2.Jsch官网

详细的可以看下上面这两个链接,下面直接贴代码和结果

配置类:

package com.idc.remote;

public class SshConfiguration {
	private String host;
	private String username;
	private String password;
	private int port;
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	
}
主类
package com.idc.remote;

import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
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;

public class SshUtil {
	private ChannelSftp channelSftp;
	private ChannelExec channelExec;
	private Session session=null;
	private int timeout=60000;
	
	public SshUtil(SshConfiguration conf) throws JSchException{
		System.out.println("try connect to  "+conf.getHost()+",username: "+conf.getUsername()+",password: "+conf.getPassword()+",port: "+conf.getPort());
		JSch jSch=new JSch(); //创建JSch对象
		session=jSch.getSession(conf.getUsername(), conf.getHost(), conf.getPort());//根据用户名,主机ip和端口获取一个Session对象
		session.setPassword(conf.getPassword()); //设置密码
		Properties config=new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);//为Session对象设置properties
		session.setTimeout(timeout);//设置超时
		session.connect();//通过Session建立连接		
	}
	public void download(String src,String dst) throws JSchException, SftpException{
		//src linux服务器文件地址,dst 本地存放地址
		channelSftp=(ChannelSftp) session.openChannel("sftp");
		channelSftp.connect();
		channelSftp.get(src, dst);
		channelSftp.quit();
	}
	public void close(){
		session.disconnect();
	}
	public static void main(String[] args){
		SshConfiguration configuration=new SshConfiguration();
		configuration.setHost("192.168.1.109");
		configuration.setUsername("root");
		configuration.setPassword("123456789");
		configuration.setPort(22);
		try{
			SshUtil sshUtil=new SshUtil(configuration);
			sshUtil.download("/home/bigdata/0119EC5A1EF19C8BB1D5F30ED05D0A6D.apk","0119EC5A1EF19C8BB1D5F30ED05D0A6D.apk");
			sshUtil.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
例子中获取 /home/bigdata目录下的0119EC5A1EF19C8BB1D5F30ED05D0A6D.apk文件,并保存在当前目录下,结果如图:



Logo

更多推荐