TShopping

 找回密碼
 註冊
搜索
查看: 1087|回復: 0
打印 上一主題 下一主題

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

[複製鏈接]
跳轉到指定樓層
1#
發表於 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, 2024-4-24 13:33 , Processed in 0.049199 second(s), 22 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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