ftp与sftp连接实例

1.ftp连接方式

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;


public class Test1 {
	public static FTPClient ftpClient = new FTPClient();
	
	public static boolean connect(String hostname, String username,
            String password) throws IOException {
        ftpClient.connect(hostname);
        ftpClient.setControlEncoding("UTF-8");
        if (ftpClient.login(username, password)) {
        	ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        	System.out.println("FTP连接成功!");
            return true;
        }
        System.out.println("FTP连接失败!");
        disconnect();
        return false;
    }
    
    public static void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
            System.out.println("FTP disconnected..");
        }
    }
	
	public static void main(String[] args) {
		try {
			String hostname = "10.193.22.146";
			String username = "test";
			String password = "test";
			connect(hostname, username, password);
			disconnect();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
2.sftp连接方式

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

public class Test {
	private ChannelSftp sftp;

	/**
	 * @param args
	 * @throws InterruptedException
	 * @throws ParseException
	 * @throws IOException
	 */
	public static void main(String[] args) throws InterruptedException,
			ParseException, Exception {
		
		sftp = connect("10.198.12.87", 22, "admin", "admin");
		sftp.disconnect();
	}

	/**
	 * 连接sftp服务器
	 * 
	 * @param host 主机
	 * @param port 端口
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 */
	public static ChannelSftp connect(String host, int port, String username,
			String password) {
		ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host, port);
			System.out.println("Session created.");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			System.out.println("Session connected.");
			System.out.println("Opening Channel.");
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			System.out.println("Connected to " + host + ".");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sftp;
	}

	public ChannelSftp getSftp() {
		return sftp;
	}

	public void setSftp(ChannelSftp sftp) {
		this.sftp = sftp;
	}

}


备注:

1.ftp连接不安全,一般出于安全性的考虑会关闭ftp端口,连接ftp都是通过sftp方式连接;

2.ftp的上传与下载需要设置文件传输模式为二进制传输模式,如:

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

你可能感兴趣的:(Java)