java代码运行sh命令 java执行java代码( 四 )


.......
try{
Session session = new JSch().getSession(user, ip, port);
session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("userauth.gssapi-with-mic", "no");
session.connect();
ChannelExec exec = (ChannelExec) session.openChannel("exec");
exec.setCommand("ifconfig");//这里是你要执行的命令,部分命令不支持 , 具体自己执行下
ByteArrayOutputStream bao = new ByteArrayOutputStream();
exec.setOutputStream(bao);
ByteArrayOutputStream baerr = new ByteArrayOutputStream();
exec.setErrStream(baerr);
exec.connect();
while (!exec.isEOF())
;
String errmsg = new String(baerr.toByteArray(), "utf-8");
if (StringUtils.notNull(errmsg)) {
throw new RuntimeException(errmsg);
} else {
System.out.println(new String(bao.toByteArray(), "utf-8"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭session等操作
}
怎样在java代码中调用执行shell脚本【java代码运行sh命令 java执行java代码】// 用法:Runtime.getRuntime().exec("命令");
String shpath="/test/test.sh";//程序路径
Process process =null;
String command1 = “chmod 777 ” + shpath;
try {
Runtime.getRuntime().exec(command1 ).waitFor();
} catch (IOException e1) {
e1.printStackTrace();
}catch (InterruptedException e) {
e.printStackTrace();
}
String var="201102";/参数
String command2 = “/bin/sh ” + shpath + ” ” + var;
Runtime.getRuntime().exec(command2).waitFor();
关于java代码运行sh命令和java执行java代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读