找回密碼
 註冊
搜索
查看: 1338|回復: 0

[教學] java使用ssh連接Linux並執行命令

[複製鏈接]
發表於 2019-2-20 23:45:21 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
需依賴jcraft的jar包。可自行下載或者通過maven下載。

maven pom.xml配置:

  1. <dependency>
  2.         <groupId>com.jcraft</groupId>
  3.            <artifactId>jsch</artifactId>
  4.            <version>0.1.53</version>
  5.     </dependency>
複製代碼


java代碼如下:
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import org.apache.commons.io.IOUtils;

  4. import com.jcraft.jsch.ChannelExec;
  5. import com.jcraft.jsch.JSch;
  6. import com.jcraft.jsch.JSchException;
  7. import com.jcraft.jsch.Session;

  8. public class SSHLinux {

  9.         public static void main(String[] args) throws IOException, JSchException {
  10.                 // TODO Auto-generated method stub
  11.                 String host = "172.19.28.253";
  12.                 int port = 22;
  13.                 String user = "root";
  14.                 String password = "123456";
  15.                 String command = "whatweb --output-xml http://216.139.147.75:443/";
  16.                 String res = exeCommand(host,port,user,password,command);

  17.                 System.out.println(res);
  18.                
  19.         }
  20.         
  21.         
  22. public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
  23.         
  24.         JSch jsch = new JSch();
  25.         Session session = jsch.getSession(user, host, port);
  26.         session.setConfig("StrictHostKeyChecking", "no");
  27.     //    java.util.Properties config = new java.util.Properties();
  28.      //   config.put("StrictHostKeyChecking", "no");
  29.         
  30.         session.setPassword(password);
  31.         session.connect();
  32.         
  33.         ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
  34.         InputStream in = channelExec.getInputStream();
  35.         channelExec.setCommand(command);
  36.         channelExec.setErrStream(System.err);
  37.         channelExec.connect();
  38.         String out = IOUtils.toString(in, "UTF-8");
  39.         
  40.         channelExec.disconnect();
  41.         session.disconnect();
  42.         
  43.         return out;
  44.     }

  45. }
複製代碼


文章出處
 
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-5-1 21:53 , Processed in 0.024823 second(s), 21 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表