JSCH执行linux命令
Posted 亲爱的阿道君
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSCH执行linux命令相关的知识,希望对你有一定的参考价值。
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); } }
以上是关于JSCH执行linux命令的主要内容,如果未能解决你的问题,请参考以下文章
使用java中的jsch在linux中通过sudo命令执行shell脚本以启动服务