java执行shell命令返回127 :No such file or directory

场景:需要在指定的远端机器执行某些shell命令

 

过程:
java中执行以下代码:

Process process = Runtime.getRuntime().exec(realCommond);
realCommond中的值为:
ssh -p 22 -q admin@192.168.110.10 "sh xxx.sh "

返回以下结果:

bash:  sh xxx.sh: No such file or directory

而且执行的返回值 

process.waitFor() = 127

realCommond的值复制到终端执行却没问题。

 

原因猜想:

java运行时环境和用户登录运行环境差异导致的。

 

解决方法一(未成功):

使用登陆的用户环境,在执行前添加 /etc/profile,并且在执行的 shell命令前加上  source /etc/profile;

如:

ssh -p 22 -q admin@192.168.110.10 "source /etc/profile; sh xxx.sh "

解决方法二(成功):

新建一个sh文件,把ssh的工作交给它,自己只需传入相关参数就行。

这样也能使用当前用户环境而不是Java环境。

新建一个ssh.sh 文件:

#!/bin/sh
echo "in ssh.sh  you will execute: ssh -p $2 -q $1 '$3 $4 $5 $6 $7 $8 $9'" 
ssh -p $2 -q $1 "$3 $4 $5 $6 $7 $8 $9" 
echo "========done ssh === "

然后Java中的realCommond的值只需改为:

sh ssh.sh  admin@192.168.110.10 22 sh xxx.sh

 


版权声明:本文为m0_37691745原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。