I am trying to transfer my folder using scp using a pem file
My whole program is executing fine but files in not showing on server. Anyone can tell me where I am doing mistake
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class jschclass {
public static void main(String[] args) {
String SFTPHOST = "xx.xxx.xx.xxx";
int SFTPPORT = 22;
String SFTPUSER = "myusername";
// String SFTPPASS = "password";
String SFTPWORKINGDIR = "/var/www/html/projects/demoo_reports/";
String Pemfilepath=System.getProperty("user.dir")+File.separator+"src"+File.separator+"lib"+File.separator+"airtel.pem";
String targetFolder = System.getProperty("user.dir")+File.separator+"test-output";
//String Pemfilepath="./src/lib/airtel.pem";
//String targetFolder = "./test-output";
File folder = new File("./test-output");
System.out.println("folder=" + folder);
if (folder.listFiles() != null) {
List<File> listOfFiles = Arrays.asList(folder.listFiles());
for (File file : listOfFiles) {
// System.out.println("File name: " + file.getName());
// System.out.println("Full path: " + file.getAbsolutePath());
System.out.println("Target path: " + targetFolder + file.getName());
System.out.println();
}
}
/////////////////////
final JSch jsch = new JSch();
try {
jsch.addIdentity(Pemfilepath);
System.out.println("identity added ");
Session session = jsch.getSession(SFTPUSER,SFTPHOST,22 );
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Connected");
////////////
SimpleDateFormat dateFormatForFoldername = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
Date currentDate = new Date();
String folderDateFormat = dateFormatForFoldername.format(currentDate);
String command = "scp -i "+Pemfilepath+" -r "+targetFolder+" "+"user@xx.xxx.xx.xxx:/var/www/html/projects/demo_reports/"+folderDateFormat+"/";
System.out.println(command);
Channel channel = session.openChannel("exec");
//channel.setCommand(command);
//channel.setErrStream(System.err);
channel.connect();
System.out.println("Files is up");
channel.disconnect();
session.disconnect();
System.out.println("Disconnected");
////////////
} catch (JSchException e) {
e.printStackTrace();
}
}
}
In an another approch I have used sh exector directly from my local without connecting to the server first
"echo "+pass+" | "+"sudo -S
Worked for me
My full code seems like below :-
String pass = "\"Yourpassword\"";
out.println("echo "+pass+" | "+"sudo -S scp -i "+Pemfilepath+" -r "+targetFolder+" "+"user@xx.xxx.xx.xxx:/var/www/html/projects/demoproject");
Hope it will help you :)