Search code examples
javasshputtyjsch

How to Execute Putty commands in java to move files between folders(mv command)


I have written a java code that can connects using Jsch, and can Upload and download files between the local machine and server.

But I am not sure how to execute commands like 'mv' to move files between folders withing the server using java. To list the files ls command will be used in putty application, is possible with Jsch or any other library has to be used ?

JSch jsch = null;
Session session = null;
Channel channel = null;
ChannelSftp c = null;
try {
    jsch = new JSch();
    System.out.println("Setting Up SFTP Connection...");
    session = jsch.getSession(username, host, 22);
    session.setPassword(pass);
    System.out.println("SFTP Configration Complete..!");  
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    System.out.println("Attempting to Connect..!"); 
    session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
    session.connect();
    System.out.println("Session Connected."); 
    channel = session.openChannel("sftp");
    channel.connect();
    System.out.println("Channel Connected."); 
    c = (ChannelSftp) channel;
    System.out.println("Connection Established\n");
} catch (Exception e) { 
    e.printStackTrace();    
}

try {
    String tempFolderInLocal = "C:/Users/591705/Desktop/Test";
    String Destiantion = "/hta1/home/pinDap75a/DestinationDemo";
    String ServerTempDestination="/hta1/home/pinDap75a/TempDestinationDemo";
    String DestiantionT = "/hta1/home/pinDap75a/DestinationDemo/Demo.txt";
    String Source = "C:/Users/591705/Documents/Demo.txt";  
    System.out.println("Starting Upload..");
    c.put(Source,Destiantion);
    System.out.println("**Upload Finished**");  
    System.out.println("Starting Downlaod...");
    c.get(DestiantionT, tempFolderInLocal);

    System.out.println("File Transfer Complete! \n");
} 
catch (Exception e) {   e.printStackTrace();    }

c.disconnect();
session.disconnect();

To move the file between ServerDestinationTemp and DestinationT I am able to achieve it


Solution

  • Use a Shell channel

    shchannel = session.openChannel("shell");