ssh2的两种java实现

SSH2的两种java实现,jcraft和Ganymed,终于把困扰我多日的问题解决了,贴上来看看 [点击图片可在新窗口打开]
(看了源码,Ganymed好像就是对craft做了封装.)

/**
* craft method
*/
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class SSHTest {
public static final UserInfo defaultUserInfo = new UserInfo() {
  public String getPassphrase() {
   return null;
  }

  public String getPassword() {
   return null;
  }
  public boolean promptPassword(String arg0) {
   return false;
  }

  public boolean promptPassphrase(String arg0) {
   return false;
  }

  public boolean promptYesNo(String arg0) {
   return true;
  }

  public void showMessage(String arg0) {
  }
};

public static void main(String[] args) throws Exception {
  String hostname = "192.168.0.0";
  String username = "root";
  String password = "pass";
  String remoteFile = "/home/sun";
  String localFile = "C:\\001.txt";

  JSch jsch = new JSch();

  Session session = jsch.getSession(username, hostname, 22);
  session.setPassword(password);
  session.setUserInfo(defaultUserInfo);
  session.connect();
 
  Channel channel = session.openChannel("sftp");
  channel.connect();
  ChannelSftp c = (ChannelSftp) channel;
  c.put(localFile, remoteFile);
  session.disconnect();
}
}



/**
* Ganymed method
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Basic
{
public static void main(String[] args)
{
  String hostname = "192.168.0.0";
  String username = "root";
  String password = "pass";

  try
  {
   Connection conn = new Connection(hostname);

   conn.connect();

   boolean isAuthenticated = conn.authenticateWithPassword(username, password);

   if (isAuthenticated == false)
    throw new IOException("Authentication failed.");

   Session sess = conn.openSession();

   sess.execCommand("cd /home/sun && mkdir test");

   InputStream stdout = new StreamGobbler(sess.getStdout());

   BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

   while (true)
   {
    String line = br.readLine();
    if (line == null)
     break;
    System.out.println(line);
   }

   System.out.println("ExitCode: " + sess.getExitStatus());

   sess.close();

   conn.close();

  }
  catch (IOException e)
  {
   e.printStackTrace(System.err);
   System.exit(2);
  }
}
}

你可能感兴趣的:(java实现)