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

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命令,不说了,直接上代码和详细的代码说明:


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 */
10public 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(转帖)
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/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现连接远程服务器并执行命令,可以使用Java中的SSH协议。SSH(Secure Shell)是一种加密网络协议,可用于安全地连接到远程服务器并执行命令Java中有一些SSH库可以用来实现这个功能,比如JSch和Apache Mina SSHD。下面是一个使用JSch的示例代码: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "remotehost.com"; String user = "username"; String password = "password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand("ls -la"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception e) {} } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 这个代码片段使用JSch创建一个SSH会话,并通过该会话连接到远程主机。然后它打开一个执行通道并设置要执行命令(在这个例子中是“ls -la”)。执行通道连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开连接,并且会话关闭。 需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑使用密钥进行身份验证,而不是密码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值