JSch:純JAVA實現遠程執行SSH2主機的SHELL命令

jopen 11年前發布 | 70K 次閱讀 JSch 網絡工具包

我將描述如何利用JSch實現執行遠程SSH2主機的SHELL命令,不說了,直接上代碼和詳細的代碼說明:

/**

  • 利用JSch包實現遠程主機SHELL命令執行
  • @param ip 主機IP
  • @param user 主機登陸用戶名
  • @param psw 主機登陸密碼
  • @param port 主機ssh2登陸端口,如果取默認值,傳-1
  • @param privateKey 密鑰文件路徑
  • @param passphrase 密鑰的密碼 */ public static void sshShell(String ip, String user, String psw
     ,int port ,String privateKey ,String passphrase) throws Exception{
    
    Session session = null; Channel channel = null;
JSch jsch = new JSch();

//設置密鑰和密碼
if (privateKey != null && !"".equals(privateKey)) {
       if (passphrase != null && "".equals(passphrase)) {
        //設置帶口令的密鑰
           jsch.addIdentity(privateKey, passphrase);
       } else {
        //設置不帶口令的密鑰
           jsch.addIdentity(privateKey);
       }
   }

if(port <=0){
    //連接服務器,采用默認端口
    session = jsch.getSession(user, ip);
}else{
    //采用指定的端口連接服務器
    session = jsch.getSession(user, ip ,port);
}

//如果服務器連接不上,則拋出異常
if (session == null) {
    throw new Exception("session is null");
}

//設置登陸主機的密碼
session.setPassword(psw);//設置密碼   
//設置第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//設置登陸超時時間   
session.connect(30000);

try {
    //創建sftp通信通道
    channel = (Channel) session.openChannel("shell");
    channel.connect(1000);

    //獲取輸入流和輸出流
    InputStream instream = channel.getInputStream();
    OutputStream outstream = channel.getOutputStream();

    //發送需要執行的SHELL命令,需要用\n結尾,表示回車
    String shellCommand = "ls \n";
    outstream.write(shellCommand.getBytes());
    outstream.flush();


    //獲取命令執行的結果
    if (instream.available() > 0) {
        byte[] data = new byte[instream.available()];
        int nLen = instream.read(data);

        if (nLen < 0) {
            throw new Exception("network error.");
        }

        //轉換輸出結果并打印出來
        String temp = new String(data, 0, nLen,"iso8859-1");
        System.out.println(temp);
    }
    outstream.close();
    instream.close();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    session.disconnect();
    channel.disconnect();
}

}</pre>來自:http://my.oschina.net/hetiangui/blog/137426

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!