http://txy821.iteye.com/blog/1405230

http://my.oschina.net/hetiangui/blog/137426

上篇文章我编写了利用JSch实现SFTP的文件上传和下载 http://my.oschina.net/hetiangui/blog/137357,在本篇文章中,我将描述如何利用JSch实现执行远程SSH2主机的SHELL命令,不说了,直接上代码和详细的代码说明:

view source print?
01 /**
02  * 利用JSch包实现远程主机SHELL命令执行
03  * @param ip 主机IP
04  * @param user 主机登陆用户名
05  * @param psw  主机登陆密码
06  * @param port 主机ssh2登陆端口,如果取默认值,传-1
07  * @param privateKey 密钥文件路径
08  * @param passphrase 密钥的密码
09  */
10 public static void sshShell(String ip, String user, String psw
11         ,int port ,String privateKey ,String passphrase) throws Exception{
12     Session session = null;
13     Channel channel = null;
14  
15       
16     JSch jsch = new JSch();
17  
18     //设置密钥和密码
19     if (privateKey != null && !"".equals(privateKey)) {
20         if (passphrase != null && "".equals(passphrase)) {
21             //设置带口令的密钥
22             jsch.addIdentity(privateKey, passphrase);
23         } else {
24             //设置不带口令的密钥
25             jsch.addIdentity(privateKey);
26         }
27     }
28       
29     if(port <=0){
30         //连接服务器,采用默认端口
31         session = jsch.getSession(user, ip);
32     }else{
33         //采用指定的端口连接服务器
34         session = jsch.getSession(user, ip ,port);
35     }
36  
37     //如果服务器连接不上,则抛出异常
38     if (session == null) {
39         throw new Exception("session is null");
40     }
41       
42     //设置登陆主机的密码
43     session.setPassword(psw);//设置密码   
44     //设置第一次登陆的时候提示,可选值:(ask | yes | no)
45     session.setConfig("StrictHostKeyChecking", "no");
46     //设置登陆超时时间   
47     session.connect(30000);
48           
49     try {
50         //创建sftp通信通道
51         channel = (Channel) session.openChannel("shell");
52         channel.connect(1000);
53  
54         //获取输入流和输出流
55         InputStream instream = channel.getInputStream();
56         OutputStream outstream = channel.getOutputStream();
57           
58         //发送需要执行的SHELL命令,需要用\n结尾,表示回车
59         String shellCommand = "ls \n";
60         outstream.write(shellCommand.getBytes());
61         outstream.flush();
62  
63  
64         //获取命令执行的结果
65         if (instream.available() > 0) {
66             byte[] data = new byte[instream.available()];
67             int nLen = instream.read(data);
68               
69             if (nLen < 0) {
70                 throw new Exception("network error.");
71             }
72               
73             //转换输出结果并打印出来
74             String temp = new String(data, 0, nLen,"iso8859-1");
75             System.out.println(temp);
76         }
77         outstream.close();
78         instream.close();
79     } catch (Exception e) {
80         e.printStackTrace();
81     } finally {
82         session.disconnect();
83         channel.disconnect();
84     }
85 }

利用JSch实现执行远程SSH2主机的SHELL命令,见我的博文:http://my.oschina.net/hetiangui/blog/137426

==========================

java程序通过密钥方式使用JSch API访问SSH(转帖)

  • 博客分类:
  • SFTP
sshjsch 
java程序通过密钥方式使用JSch API访问SSH(转帖)
2011-05-09 20:44 297人阅读 评论(0) 收藏 举报
java程序通过密钥方式使用JSch API访问SSH
2010-05-20 14:51
上面已经验证了通过密钥方式访问SSH Server是可行的,并且给自己搭建了一个测试环境,下面就开始我最终的目的:java程序通过密钥访问。

1、工程引入jsch-0.1.42.jar,可以到http://www.jcraft.com/jsch/官方下载。

2、在官方的example中,有一个demo,类UserAuthPubKey,是使用密钥访问的,参考了下,我对其进行了修改,改为自动连接并使用SFTP协议显示当前路径,代码如下:

package Test.sftp;

import com.jcraft.jsch.*;

public class TestKeyAcc {
public static void main(String[] arg) {

String keyFile = "./id_rsa";
   String user = "username";
   String host = "127.0.0.1";
   String passphrase = "111111";
   int port = 22;
   try {
    JSch jsch = new JSch();
    jsch.addIdentity(keyFile);

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

// username and passphrase will be given via UserInfo interface.
    UserInfo ui = new MyUserInfo(passphrase);
    session.setUserInfo(ui);
    session.connect();

Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftp = (ChannelSftp) channel;
    System.out.println(sftp.pwd());
   } catch (Exception e) {
    e.printStackTrace();
    System.out.println(e);
   }
}

public static class MyUserInfo implements UserInfo {
   private String passphrase = null;

public MyUserInfo(String passphrase) {
    this.passphrase = passphrase;
   }

public String getPassphrase() {
    return passphrase;
   }

public String getPassword() {
    return null;
   }

public boolean promptPassphrase(String s) {
    return true;
   }

public boolean promptPassword(String s) {
    return true;
   }

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

public void showMessage(String s) {
    System.out.println(s);
   }
}
}
运行后结果显示:

****USAGE WARNING****

This is a private computer system. This computer system, including all
related equipment, networks, and network devices (specifically including
Internet access) are provided only for authorized use. This computer system
may be monitored for all lawful purposes, including to ensure that its use
is authorized, for management of the system, to facilitate protection against
unauthorized access, and to verify security procedures, survivability, and
operational security. Monitoring includes active attacks by authorized entities
to test or verify the security of this system. During monitoring, information
may be examined, recorded, copied and used for authorized purposes. All
information, including personal information, placed or sent over this system
may be monitored.

Use of this computer system, authorized or unauthorized, constitutes consent
to monitoring of this system. Unauthorized use may subject you to criminal
prosecution. Evidence of unauthorized use collected during monitoring may be
used for administrative, criminal, or other adverse action. Use of this system
constitutes consent to monitoring for these purposes.

/cygdrive/d/opensshhome/username

ok,good,问题解决了,如果不是密钥方式,与普通FTP一样的用户名及密码访问又是怎样的呢,那就比较简单了

去掉

jsch.addIdentity(keyFile);

UserInfo ui = new MyUserInfo(passphrase);
    session.setUserInfo(ui);

在Session sshSession = jsch.getSession(userStr, serverIp, port);下增加
          sshSession.setPassword(passwordStr);

如果在生成私钥时没有使用密码,那又是怎样的呢?其实很简单,如果不需要密码访问,你提供了密码也是通过的( new MyUserInfo(passphrase);中密码不null或空),大概过程是,先看是否需要密码,如果不需要,那么就直接过去,所以即便设置了密码也没问题。

在使用该API进行密钥及非密钥访问SFTP时,感觉不是很惬意,试验了许久才通过。

以上文字但愿对后来者有所帮助

==============

http://www.jcraft.com/jsch/examples/

  • Shell.java
    demonstrating how to connect to sshd server and get the shell prompt.
  • Exec.java
    demonstrating the remote exec.
  • ViaHTTP.java
    demonstrating the ssh session via HTTP proxy.
  • ViaSOCKS.java
    demonstrating the ssh session via SOCKS proxy.
  • PortForwardingR.java
    demonstrating the port forwarding like option -R of ssh command.
  • PortForwardingL.java
    demonstrating the port forwarding like option -L of ssh command.
  • StreamForwarding.java
    demonstrating the stream forwarding.
  • UserAuthPubKey.java
    demonstrating the user authentification by public key.
  • Compression.java
    demonstrating the packet compression.
  • ScpTo.java
    demonstrating the file transfer from local to remote.
  • ScpFrom.java
    demonstrating the file transfer from remote to local
  • Sftp.java
    demonstrating the sftp protocol support.
  • KnownHosts.java
    demonstrating the 'known_hosts' file handling.
  • UserAuthKI.java
    demonstrating the keyboard-interactive authentication.
  • KeyGen.java
    demonstrating the DSA keypair generation.
  • ChangePassphrase.java
    demonstrating how to change the passphrase for a private key file instead of creating a new private key.
  • AES.java
    demonstrating how to use "aes128-cbc".
  • Daemon.java
    demonstrating how to provide a network service like inetd by using remote port-forwarding functionality.
  • Logger.java
    demonstrating how to enable logging mechanism and get logging messages.
  • Subsystem.java
    demonstrating how to use the Subsystem channel.
  • Sudo.java
    demonstrating how to sudo on the remote.
  • ScpToNoneCipher.java
    demonstrating how to enable none cipher.
  • X11Forwarding.java
    demonstrating the X11 forwarding.
  • JumpHosts.java
    demonstrating SSH through jump hosts.
  • OpenSSHConfig.java
    demonstrating how OpenSSH's config is supported.

JSch:纯JAVA实现远程执行SSH2主机的SHELL命令相关推荐

  1. java jsch jar_使用JSch从Java在远程计算机上执行命令

    SSH是任何一种every-day工具Linux系统管理工作.这是访问网络上的远程计算机,传输数据和执行远程命令的一种简单而安全的方法.除了交互模式之外,还有许多工具可以使依赖于现有技术的远程任务实现 ...

  2. 【java】java ssh 远程执行命令 并且获取执行的结果

    文章目录 1.概述 1.概述 因为部署到不同的环境,需要远程执行一些命令,然后获取一些信息. 因此写了如下代码 因为包 <dependency><groupId>ch.ethz ...

  3. Docker——容器内部执行宿主机的docker命令

    现在有一个需求是在容器内部使用docker命令,但试了一下报命令不存在 解决办法: 把docker相关的命令和依赖使用-v挂载到容器 docker@box:~$ docker run -it -d \ ...

  4. JAVA Socket远程执行任务

    优化是一个很棘手的问题,最好的策略就是置之不顾,直到你发现需要担心它了 最近一直在复习之前所学过的知识,今天看到之前写过的一段程序,所以在这里写上一篇博客记录一下. 如果我们现在有一个处理数据的任务很 ...

  5. Java SSH远程执行Shell脚本实现

    此程序需要ganymed-ssh2-build210.jar包. 下载地址:http://www.ganymed.ethz.ch/ssh2/ 为了调试方便,可以将\ganymed-ssh2-build ...

  6. sshpass远程执行脚本_终端-Linux命令之非交互SSH密码验证-Sshpass

    Sshpass是使用SSH所谓的"交互式键盘密码身份验证"以非交互方式执行密码身份验证的工具 通俗来说就是 使用ssh密码登录 是需要在连接时手动输入密码的,没办法明文连接,如下图 ...

  7. 远程执行本地查找文件的命令并返回结果

  8. shell脚本不暂停进程,暂停几秒执行下一条shell命令

    需求如下: 跑monkey脚本如果遇到异常结束,则使用logcat输出日志,输出三秒后停止输出 如果使用sleep 命令的话,则会导致logcat在sleep的时候也暂停执行了 解决方法如下,通过wh ...

  9. linux脚本执行暂停,shell脚本不暂停进程,暂停几秒执行下一条shell命令

    需求如下: 跑monkey脚本如果遇到异常结束,则使用logcat输出日志,输出三秒后停止输出 如果使用sleep 命令的话,则会导致logcat在sleep的时候也暂停执行了 解决方法如下,通过wh ...

最新文章

  1. 图像傅里叶变换-不错
  2. java system_深入分析java中的System
  3. 实现带下拉菜单的工具栏按钮
  4. JVM优化系列-常用GC参数总结
  5. 基于JAVA+SpringMVC+Mybatis+MYSQL的甜品店商城
  6. python实现播放音乐_python实现简易云音乐播放器
  7. flink的operator state简单理解
  8. linux是否32位系统文件夹,技术|如何判断Unix系统的一个库文件是32位还是64位的...
  9. python执行shell脚本报错_详解python执行shell脚本创建用户及相关操作
  10. 重新编译Telepresence,谈如何写编译脚本
  11. 最全中文停用词表整理(1893个)
  12. 内网穿透:看这一篇就够了!
  13. 吴恩达深度学习课后作业-目标检测的环境配置
  14. 模拟电子技术知识点总结
  15. jsp内置对象练习题
  16. 解决com.lowagie.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.
  17. 【机器学习】Tensorflow:理解和实现快速风格化图像fast neural style
  18. 吊打何同学?猛肝24小时,用6000元成本打造 AirDesk!
  19. Windbg基础-了解Symbols zz
  20. 2. robot执行的大体流程

热门文章

  1. 2020年第十一届蓝桥杯 - 省赛 - Python大学组 - B.寻找2020
  2. 【CI/CD2】actions,daocloud
  3. 【ARM】Tiny4412裸板编程之协处理器
  4. 【数据库】Ubuntu18.04安装MySQL详解
  5. 【C语言】控制台窗口图形界面编程(五):文本移动
  6. ajax如何给label赋值,如何让AjaxEditableLabel显示TextField?
  7. html请求接口_通用网关接口-FastCGI介绍
  8. 二叉树的中序遍历—leetcode94
  9. mvc4 ajax url参数,MVC4.0中Ajax通过a标签向后台Action传递参数问题?
  10. 4 Git 分支 - 分支开发工作流