标签:throws lin pos exec amp port host logs command
pom.xml 添加jar依赖
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
java类
package com.aliyun.utility.jsch; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import java.io.InputStream; import java.util.Properties; public class JSCHUtil { private static JSCHUtil instance; private JSCHUtil() { } public static JSCHUtil getInstance() { if (instance == null) { instance = new JSCHUtil(); } return instance; } private Session getSession(String host, int port, String ueseName) throws Exception { JSch jsch = new JSch(); Session session = jsch.getSession(ueseName, host, port); return session; } public Session connect(String host, int port, String ueseName, String password) throws Exception { Session session = getSession(host, port, ueseName); session.setPassword(password); Properties config = new Properties(); config.setProperty("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); return session; } public String execCmd(Session session, String command) throws Exception { if (session == null) { throw new RuntimeException("Session is null!"); } ChannelExec exec = (ChannelExec) session.openChannel("exec"); InputStream in = exec.getInputStream(); byte[] b = new byte[1024]; exec.setCommand(command); exec.connect(); StringBuffer buffer = new StringBuffer(); while (in.read(b) > 0) { buffer.append(new String(b)); } exec.disconnect(); return buffer.toString(); } public void clear(Session session) { if ((session != null) && session.isConnected()) { session.disconnect(); session = null; } } public static void main(String[] args) throws Exception { Session session = JSCHUtil.getInstance() .connect("10.9.9.135", 22, "yy", "yy"); String cmd = "cd /" + ";" + "ls -al |grep home"; String result = JSCHUtil.getInstance().execCmd(session, cmd); // ???????;?? System.out.println(result); System.exit(0); } }
标签:throws lin pos exec amp port host logs command
原文地址:http://www.cnblogs.com/lovedaodao/p/7810060.html