如何使用java从unix中的windows运行bash程序

如何使用java从unix中的windows运行bash程序

问题描述:

我正在尝试运行一个程序,该程序使用 Unix 中的 jcraft 库处理来自窗口的文件.我在建立频道后发现它总是尝试在主目录中运行程序,但我需要在单独的目录中运行.请看看我到目前为止尝试过的内容,并让我知道我缺少什么.

I am trying to run a program which process a file from window using jcraft library in Unix. what i found after establishing the channel it always try to run the program in home directory but i need to run in a separate directory.please have a look what i tried so far and let me know what i am missing.

String strRemoteDir = "/home/process/input"channel = session.openChannel("sftp");

String strRemoteDir = "/home/process/input" channel = session.openChannel("sftp");

    channel.connect();
    System.out.println("sftp channel opened and connected.");
    channelSftp = (ChannelSftp) channel;
    // Printing Home Directory in Unix Server
    System.out.println(channelSftp.getHome());
    channelSftp.cd(strRemoteDir);
   System.out.println(channelSftp.pwd());

  // for uploading a file where i need to run the program
    File f = new File(fileName);
    channelSftp.put(new FileInputStream(f), f.getName());
    System.out.println("File transfered successfully to host.");
    fileTransfer = true;

    channel=session.openChannel("exec");
    InputStream in=channel.getInputStream();
    // it is printing the desired directory where i want to go
    System.out.println(channelSftp.pwd());
    ((ChannelExec)channel).setCommand("sh process.ksh "a.txt");
    channel.setInputStream(null);
    ((ChannelExec)channel).setErrStream(System.err);
     channel.connect();

输出:未找到 process.ksh

output : process.ksh not found

但是通过腻子我能够运行该程序.只是为了让您知道 process.ksh 不在输入目录中,但可以从任何带有参数的地方运行.((ChannelExec)channel).setcommand("ls")打印出主目录中的所有文件.我相信我正在建立一个到主目录的通道,我只是不知道如何在所需的位置使用 jcraft 运行 bash 程序.请告诉我我缺少什么或者是否有可能实现.

But through putty i was able to run the program. just to let you know process.ksh is not in the input directory, but has the capability to run from anywhere with arguments. ((ChannelExec)channel).setcommand("ls") prints out all the files from home directory. i believe i am establishing a channel to home directory, i just don't know how to run bash program using jcraft in a desired location.Please let me know what i am missing or is it possible to make it happen.

提前致谢.努尔

"sftp" 通道不是用来执行 shell 命令的,而是用来执行 sftp 命令的.

"sftp" channel are not made to execute shell command but sftp command only.

    Channel channel = session.openChannel("shell");
    cmdSend = channel.getOutputStream();
    InputStream cmdRcv = channel.getInputStream();
    // Start a Thread reading and displaying cmdRcv

    channel.connect(3000);
    Thread.sleep(1000);

    cmdSend.write("cd /to/the/right/dir\n".getBytes());
    cmdSend.flush();
    cmdSend.write("sh process.ksh \"a.txt\"\n".getBytes());
    cmdSend.flush();