JSch -- Java Secure Channel

 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;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值