我正在尝试创建一个java程序,它将在我的macbook上为我设置SSH连接。它提示我输入用户名,然后输入IP地址,然后它应该用" ssh username @ ip"。
以下是我的代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class SSH {
public static void main(String[] args) throws Exception {
boolean rep = true;
String username = (null);
String IPAdress = (null);
while (rep) {
Scanner scanner = new Scanner(System.in);
System.out.print("Username: ");
username = scanner.next();
System.out.print("\nIP Adress: ");
IPAdress = scanner.next();
System.out.println("\n\nIs this correct?\nUsername: " + username + "\nIP Adress: " + IPAdress + "\nY/N");
char responce = scanner.next().charAt(0);
if (responce == 'Y' || responce == 'y') {
rep = false;
scanner.close();
} else if (responce == 'N' || responce == 'n') {
} else {
Error displayErrorMessage = new Error();
displayErrorMessage.displayError();
}
}
String SSHStartup = username + "@" + IPAdress;
System.out.println("Running command: ssh " + SSHStartup);
String[] command = { "/bin/bash, -c , ssh " + SSHStartup };
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
StringBuffer output = new StringBuffer();
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
}
}
我知道,它凌乱,现在缩进了,但它没有执行命令,而是给了我这个:
Exception in thread "main" java.io.IOException: Cannot run program "/bin/bash, -c , ssh root@(ip here)": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:485)
at SSH.main(SSH.java:32)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 3 more
为了这篇文章的目的,我已经删除了IP地址,但是当我编译并运行它时,我尝试了实际的那个,它给了我同样的错误。
帮助?
答案 0 :(得分:9)
String[] command = { "/bin/bash, -c , ssh " + SSHStartup };
Process p = Runtime.getRuntime().exec(command);
您的command
数组包含单个值,即字符串&#34; / bin / bash,-c,ssh ...&#34;。 Java正在尝试并且无法执行具有该名称的文件。
您可能打算构造一个包含命令及其参数的command
作为字符串序列,而不是单个字符串:
String[] command = { "/bin/bash", "-c", "ssh " + SSHStartup };