我正在尝试运行一个程序,该程序使用 Unix 中的 jcraft 库从窗口处理文件。建立 channel 后我发现它总是尝试在主目录中运行程序,但我需要在单独的目录中运行。请看看我到目前为止尝试了什么,让我知道我缺少什么。
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
但是通过腻子我能够运行该程序。只是为了让您知道 process.ksh 不在输入目录中,但能够从任何地方带参数运行。 ((ChannelExec)channel).setcommand("ls") 打印出主目录中的所有文件。我相信我正在建立一个到主目录的 channel ,我只是不知道如何在所需位置使用 jcraft 运行 bash 程序。请让我知道我缺少什么或者是否有可能实现它。
提前致谢。 努尔
最佳答案
“sftp” channel 不是用来执行 shell 命令,而是只执行 sftp 命令。
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();
关于java - 如何使用 java 在 unix 中从 Windows 运行 bash 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35047043/