У меня в java коде вызываются ssh комманды через Runtime.exec(). Но я не могу полностью вывести результат выполнения команд в реальном времени. К примеру, команда scp ничего не выводит, в том числе прогресс копирования. Для вывода Error и Input потоков я использую Stream Gobbler. Помогите, плз, подкорректировать код, чтобы можно было выводить полный результат выполнения ssh комманд в реальном времени.
public class FilesUpdate {
public static void main(String args[]) throws IOException, SAXException, ParserConfigurationException {
if(runCommand() != true) {
System.out.println("Aborted!");
return;
}
}
private static boolean runCommand(GameSettings gameSettings) {
String projectDir = '/home/user/projects';
String[] commands = new String[100];
commands[0] = "git reset --hard HEAD^ ";
commands[1] = "git checkout test_branch";
commands[2] = "git pull origin test_branch";
commands[3] = "scp -i /home/user/.ssh/id_rsa -P 22 -r user@111.111.111.111:/some/path /some/local/path";
commands[4] = "git add .";
commands[5] = "git commit -m 'Comment'";
commands[6] = "git push origin test_branch";
try {
for(int i=0; i<commands.length; i++) {
if(!commands[i].isEmpty()) {
if( runCommand(commands[i], projectDir) != true ) {
return false;
}
}
}
return true;
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean runCommand(String cmd, String path) throws Exception {
try {
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd,null, new File(path));
InputStream inStream, inErrStream;
OutputStream outStream;
inStream = p.getInputStream();
inErrStream = p.getErrorStream();
outStream = p.getOutputStream();
StreamGobbler input = new StreamGobbler(inStream, "OUTPUT");
input.run();
StreamGobbler error = new StreamGobbler(inErrStream, "ERROR");
error.run();
int exitVal = p.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch(Exception e) {
e.printStackTrace(); // return false;
throw e;
}
System.out.println(" (command done).");
return true;
}
}
class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(InputStream is, String type)
{
this(is, type, null);
}
StreamGobbler(InputStream is, String type, OutputStream redirect)
{
this.is = is;
this.type = type;
this.os = redirect;
}
/** creates readers to handle the text created by the external program
*/
public void run()
{
try
{
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
} }