我在使用java代码执行sh文件时遇到错误。从终端开始,它运行正常
sudo:没有tty存在且没有指定askpass程序
我的代码: -
package com.test;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
public class TestScript {
int iExitValue;
String sCommandString;
public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}
}
public static void main(String args[]){
TestScript testScript = new TestScript();
testScript.runScript("sh /home/FTP-SCP-Project/shellscript.sh");
}
}
sh文件: -
sudo scp -i /home/FTP-SCP-Project/src/lib/demo.pem -r /home/FTP-SCP-Project/test-output3 user@xx.xxx.xx.xxx:/var/www/html/projects/demo_reports/reporttest112
我已经尝试了所有其他java代码,但他们给出了错误,而我给了他们所有权限,如chmod 777或755或600
String Pemfilepath="/home/shubham/Experiment_zone/FTP-SCP-Project/src/lib/cuelogic.pem";
String targetFolder = "/home/shubham/Experiment_zone/FTP-SCP-Project/test-output3";
String[] command = { "sudo scp -i "+Pemfilepath+" -r "+targetFolder+" "+"ubuntu@54.152.13.148:/var/www/html/projects/kumo_reports/reporttest1"};
// String command = "ls";
System.out.println(command[0]);
Process process = Runtime.getRuntime().exec(new String[] { "sudo ", "scp ", "-i " ,Pemfilepath," ", "-r"," ",targetFolder," ","user@xx.xxx.xx.xxx:/var/www/html/projects/demo_reports/reporttest1" });
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
但是他们也给出了如下错误: -
线程“main”中的异常java.io.IOException:无法运行程序 “sudo”:error = 2,没有这样的文件或目录 java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)at java.lang.Runtime.exec(Runtime.java:617)at java.lang.Runtime.exec(Runtime.java:485)at com.test.shelllocallaunch.main(shelllocallaunch.java:14)引起: java.io.IOException:error = 2,没有这样的文件或目录 java.lang.UNIXProcess.forkAndExec(Native Method)at java.lang.UNIXProcess。(UNIXProcess.java:187)at java.lang.ProcessImpl.start(ProcessImpl.java:130)at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)...还有3个
我观察到如果命令很小,就像ls一切都很好,但我的上面的命令没有执行,而它从终端正常工作。 如果我遗漏任何内容,请帮忙
答案 0 :(得分:0)
"echo "+pass+" | "+"sudo -S
为我工作
我的完整代码如下所示: -
String pass = "\"Yourpassword\"";
out.println("echo "+pass+" | "+"sudo -S scp -i "+Pemfilepath+" -r "+targetFolder+" "+"user@xx.xxx.xx.xxx:/var/www/html/projects/demoproject");
希望它会对你有所帮助:)。