JSch -- Java Secure Channel

来源:互联网 发布:怎么在淘宝开店铺步骤 编辑:程序博客网 时间:2024/05/19 19:33

 JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。此外,JSch依赖JavaTM Cryptography Extension (JCE)

 

    JSch主页http://www.jcraft.com/jsch/

 

    其实,熟悉ant或多或少会知道。ant的task,sshexec和scp是支持JSch的。通过ant使用的方式特别简单,可以参考

scp:http://ant.apache.org/manual/OptionalTasks/scp.html

sshexec:http://ant.apache.org/manual/OptionalTasks/sshexec.html

 

    由于我需要把JSch整合到自己开发的系统来达到登录、访问远程服务器的需求。我是通过程序的方式来完成的。

 

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.
jsch.JSch;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.UIKeyboardInteractive;
    import com.jcraft.jsch.UserInfo;

 

    try{
      JSch jsch=new JSch();
      String user;//用户名

      String password;//密码

      String host; //主机
      String port;//端口

      Session session=jsch.getSession(user, host, port);

 

      UserInfo ui=new DefaultUserInfo();

      session.setPassword(password)
      session.setUserInfo(ui);
      session.connect();

 

       String command;//登录后执行的命令

      Channel channel=session.openChannel("exec");
      ((ChannelExec)channel).setCommand(command);

      channel.disconnect();
      session.disconnect();

 

    } catch (JSchException e) {

            channel.disconnect();
            session.disconnect();
            e.printStackTrace();
        }

 

  public static class DefaultUserInfo implements UserInfo, UIKeyboardInteractive{

    public String getPassphrase() {   
        return null;
    }

    public String getPassword() {
        return null;
    }

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

    public boolean promptPassword(String message) {
        return false;
    }

    public boolean promptYesNo(String message) {
        return false;
    }

    public void showMessage(String message) {
       
    }

    public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
        return null;
    }
}