java远程调用shell脚本,提示命令找不到command not found异常,但是使用同一个用户登录服务器后在sh执行同一个脚本,并没有该提示。经过百度好像是因为环境变量未加载。需要在远程调用脚本的命令前面加上 ". ~/.bash_profile && source /etc/profile" 一段话。
例如以前脚本调用命令"sh /xxx/xx.sh"
修改后为". ~/.bash_profile && source /etc/profile && sh /xxx/xx.sh"
这里注意,前面的“.”不要忘记。
java远程调用工具类:
public static List<String> jschExecCommand(String ip, String username, String password, String cmd){
JSch jSch = new JSch();
Session session = null;
BufferedReader br = null;
InputStream errStream = null;
ChannelExec exec = null;
try{
session = jSch.getSession(username,ip);
session.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking","no");
session.setConfig(properties);
session.connect(10000);
logger.info("-----远程链接成功 ip={}",ip);
exec = (ChannelExec)session.openChannel("exec");
exec.setCommand(cmd);
exec.connect();
br = new BufferedReader(new InputStreamReader(exec.getInputStread()));
logger.info("-----命令执行日志如下:");
List<String> r = new ArrayList<>();
String line = "";
while((line = br.readLine()) != null){
r.add(line);
logger.info(line);
}
//打印错误日志,这里使用InputStream直接打印,转换为字符流会出现阻塞问题
errStream = exec.getErrStream();
StringBuffer sb = new StringBuffer();
byte[] buf = new byte[2048];
while(errStream.read(buf) != -1){
sb.append(buf);
}
logger.info("-----命令执行错误日志如下:{}",sb);
return r;
}catch(Exception e){
e.printStackTrace();
}finally{
if(errStream != null){
try{
errStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(br != null){
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(exec != null){
exec.disconnect();
}
if(session != null){
session.disconnect();
}
}
return null;
}
该远程调用shell工具类使用JSch实现,其他实现方式类似。
JSch的maven依赖:
<dependency><groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.50</version>
</dependency>