Unable to execute my command after SSH in remote server
I have written a 开发者_如何学编程code that does SSH in servers and runs a Java file with arguments.
The problem I am facing is that the code successfully does SSH in but it does not run the command after that. Strangely If I run the command from the server alone it works. Any suggestions on this please? Following is the code:
public void getSSH(String code, String newCode, JspWriter out){
try{
File f = new File("/usr/site/html/Output.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(f));
String Servers[] = {"root@web233.xyz.com","root@web234.xyz.com","root@web235.xyz.com","root@web153.xyz.com"};
for(int i =0;i<Servers.length && i<1 ;i++){
Process p = Runtime.getRuntime().exec("/usr/site/swapimages.sh "+Servers[i]+" '/root/testRemote.sh "+ code+" "+ newCode+"'");
out.println("/usr/site/swapimages.sh "+Servers[i]+" '/root/testRemote.sh "+ code+" "+ newCode+"'"+"<br>");
Utils.waitFor(10000);
}
}
}
I have also been recommended JSch but haven't looked into it yet.
The reason it isn't working is that the quotes in this version don't have the same effect as they do on the command line. When you call SSH from bash, you put the remote command in quotes so that it is all interpreted as a single argument. Bash does the separation of the arguments for you. With exec
, Java is splitting up the arguments for you. The documentation for exec
describes how it separates. It uses a StringTokenizer
, which is fairly dumb and seperates the line based on spaces (ignoring the quotes). This means that the array of arguments passed into the command is something like:
{ "/usr/site/swapimages.sh", "root@something", "'/root/testRemote.sh",
code, newCodeContents + "'" }
It could be even more strings if code
or newCode
have spaces in them. Notice that your command is multiple elements in the array and will therefore be treated as multiple arguments by ssh. In addition, ssh
will actually try to execute a command that is in a directory that is named '
. What you want to pass in, though, is:
{ "/usr/site/swapimages.sh", "root@something",
"/root/testRemote.sh " + codeContents + " " + newCodeContents }
Notice that there are no quotes and the whole command is the third element in the array.
So, you just need to manually create the string array and use the other form of exec
that takes a string array and that should fix the problem.
精彩评论