Java runtime exec with scp command

This is part of my code for copying files from local to remote computer.

try { Process cpyFileLocal = Runtime.getRuntime().exec("scp " + rFile+"*.csv" + " root@ " + host + ":" + lFile); InputStream stderr = cpyFileLocal.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line = null; System.out.println("<ERROR>"); while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("</ERROR>"); int exitVal = cpyFileLocal.waitFor(); System.out.println("Process exitValue: " + exitVal); System.out.println("...." + cpyFileLocal.exitValue()); System.out.println("SCP COMMAND "+"scp "+rFile+"*.csv" +" root@ "+host+":"+lFile); System.out.println("Sending complete..."); } catch (Exception ex) { ex.printStackTrace(); } 

output...

 <ERROR> /opt/jrms/rmsweb/transfer/cn00/outgoing/*.csv: No such file or directory </ERROR> Process exitValue: 1 ....1 SCP COMMAND scp /opt/jrms/rmsweb/transfer/cn00/outgoing/*.csv root@10.50.1.29 :/opt/jrms/transfer/incoming/ 

but when I run the command in the terminal on the local machine, it works fine and when I run ll , the files there

-rwxr-xr-x 1 freddie freddie 140 Apr 22 22:13 gc00cn00150420092629.csv *

-rwxr-xr-x 1 freddie freddie 105 Apr 22 09:13 gc00cn00150420122656.csv *

Any help please

+6
source share
3 answers

When you run a command using bash with wildcards such as * , bash will expand that command and in your case replace *.csv with a list of files ending in .csv , but this will not happen in your java.

According to this answer, you can do the following:

  • Use the .listFiles () file for a list of files
  • Use file.getName (). contains (string) to filter them if necessary
  • Iterate over an array and execute scp or do it using the whole list

or thanks @James Anderson add sh to scp in your team.

+1
source

If you use java 7 and above, you should use ProcessBuilder instead of Runtime.getRuntime().exec() , and in ProcessBuilder you can specify the execution directory:

  ProcessBuilder pb = new ProcessBuilder("scp", rFile+"*.csv", " root@ " + host + ":" + lFile); Map<String, String> env = pb.environment(); env.put("VAR1", "myValue"); env.remove("OTHERVAR"); env.put("VAR2", env.get("VAR1") + "suffix"); pb.directory("directory where the csv files located"); Process p = pb.start(); 
0
source

According to this , you should try:

 Process cpyFileLocal = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c", "scp " + rFile+"*.csv" + " root@ " + host + ":" + lFile}); 

I tested with /bin/sh and /bin/bash , successfully copied files

0
source

Source: https://habr.com/ru/post/985644/


All Articles