最近在看项目代码,里面有些东西还是很不错的,写下来留个备案以供以后工作了能够重复利用。
shell脚本在生产上用的相当多,不管是shell脚本调java,还是shell脚本调用一些任务什么的都挺常见的,我们经常将之封装成一个工具类,
然后供全局传一些参数什么的调用,此处就不给封装源码了,给个最简单的例子能运行即可。
应该依赖的jar
<dependency>
<groupId>com.boco</groupId>
<artifactId>orion-ssh2</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.boco</groupId>
<artifactId>standard</artifactId>
<version>1.1</version>
</dependency>
要执行的一个十分简单的脚本
![这里写图片描述](https://img-blog.csdn.net/20170731192518987?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveHV4aWUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
然后是执行的代码,代码是main方法调用的,为什么是main方法调用我就不解释了
package shellMonitor;
import java.io.InputStream;
import java.nio.charset.Charset;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
public class ShellMonitorJob {
private static final long TIME_OUT = 0;
public static void main(String[] args) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
String charset = Charset.defaultCharset().toString();
Connection conn = new Connection("此处应有ip");
conn.connect();
boolean authenticateWithPassword = conn.authenticateWithPassword("用户", "密码");
if (authenticateWithPassword) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand("sh /home/ljp/ljp.sh"); // 调用脚本
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
ret = session.getExitStatus();
System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr);
System.out.println("ret=" + ret);
ret = session.getExitStatus();
if (conn != null) {
conn.close();
}
stdOut.close();
stdErr.close();
}
}
private static String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
}
此处么有什么linux缓冲区阻塞问题,输出:
outStr=nihao nihao mohao
outErr=
ret=0