如何在java中执行Putty命令在文件夹之间移动文件(mv命令)

时间:2014-12-15 08:39:19

标签: java ssh putty jsch

我编写了一个可以使用Jsch连接的java代码,可以在本地机器和服务器之间上传和下载文件。

但我不确定如何执行像'mv'这样的命令,使用java在服务器之间移动文件。 要列出文件 ls命令将在putty应用程序中使用,是否可以使用Jsch 或者必须使用任何其他库?

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();

要在ServerDestinationTemp和DestinationT之间移动文件,我能够实现它

2 个答案:

答案 0 :(得分:-1)

使用Shell频道

shchannel = session.openChannel("shell");

答案 1 :(得分:-2)

是的,您可以使用以下代码使用java执行shell命令,而无需与shell终端进行交互。

 Runtime runtime = Runtime.getRuntime();
    Process proc = null;
    String retStr = "";
    InputStreamReader insReader = null;
    char[] tmpBuffer = new char[1024];
    int nRet = 0;
    String cmd = "mv abc.txt /home/abct.txt";
    try {
        proc = runtime.exec(cmd);
        insReader = new InputStreamReader(proc.getInputStream());

        while ((nRet = insReader.read(tmpBuffer, 0, 1024)) != -1) {
            retStr += new String(tmpBuffer, 0, nRet);
        }

        insReader.close();
        System.out.println(retStr);
    } catch (Exception e) {
        System.out.println("Bad");
    } finally {
        System.out.println("Done");
        }