由于公司需要,在網上找了一下支持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