由于公司需要,在网上找了一下支持SFTP的包,发现俩个不错的,一个是 Secure FTP Factory ,一个是 J2SSH Maverick ,但都是收费的,现在简单介绍一下 J2SSH Maverick 怎样简单使用。代码如下:/* HEADER */import com.maverick.ssh.*;import com.maverick.ssh2.*;import java.io.*;
import com.sshtools.net.*;import com.sshtools.sftp.*;
/** * This example demonstrates the connection process connecting to an SSH2 server * and usage of the SFTP client. */public class MySftpConnect { public static void main(String[] args) { MySftpConnect c = new MySftpConnect(); c.createSftpClient("192.168.0.108", "szb", "szbpatternx86", 22);--参数依次为主机名,用户名,密码,端口号。 }
public void createSftpClient(String hostname, String username, String password, int port) { try { System.out.println("Connecting to " + hostname);
// Create an SshConnector instance SshConnector con = SshConnector.getInstance();
// Connect to the host SocketTransport t = new SocketTransport(hostname, port); t.setTcpNoDelay(true); SshClient ssh = con.connect(t, username); Ssh2Client ssh2 = (Ssh2Client) ssh;
// Authenticate the user using password authentication com.maverick.ssh.PasswordAuthentication pwd = new com.maverick.ssh.PasswordAuthentication(); do { pwd.setPassword(password); } while (ssh2.authenticate(pwd) != SshAuthentication.COMPLETE && ssh.isConnected()); // Start a session and do basic IO if (ssh.isAuthenticated()) { SftpClient sftp = new SftpClient(ssh2); // test create file. this.createTestFile(sftp); } } catch (Throwable th) { th.printStackTrace(); } }
//测试IO操作 public void createTestFile(SftpClient sftp) throws Exception {
File textFile = new File(System.getProperty("user.home"), "shining.txt"); FileOutputStream tout = new FileOutputStream(textFile);
// Create a file with \r\n as EOL for (int i = 0; i < 100; i++) { tout.write("All work and no play makes Jack a dull boy中文\r\n" .getBytes()); } tout.close();
// Perform some text mode operations指定文件存储为txt类型 sftp.setTransferMode(SftpClient.MODE_TEXT);
// Tell the client which EOL the remote client is using - note // that this will be ignored with version 4 of the protocol sftp.setRemoteEOL(SftpClient.EOL_LF); //将文件上传到服务器 sftp.put(textFile.getAbsolutePath()); }}写的不太详细,请参考:http://3sp.com/kb/idx/0/014/article/Getting_started_with_J2SSH_Maverick.html