我有一个独立的应用程序,应使用ssh连接到Windows服务器并从该Windows服务器上的本地计算机运行批处理脚本。
已采取的步骤:
我面临的问题是,一旦脚本在远程服务器上,我将无法执行。
尝试使用sftpchannel.setCommand()方法进行各种组合以执行文件。
到目前为止,我只是在代码中尝试打印路径变量,但我的最终目标是运行批处理文件脚本。
传递给executeFileforWindows(String localpath,String targetPath)的参数还有:
localPath = D:\ scripts \ script.bat 目标路径= /cygdrive/d/scripts/script.bat
public List<String> executeFileforWindows(String localpath, String targetPath) {
List<String> result = new ArrayList<String>();
try {
JSch jsch = new JSch();
Session session = jsch.getSession(USERNAME, HOST, PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put(localpath, targetPath);
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.setCommand("cmd.exe /c \"echo %PATH%\"");
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
BufferedReader errreadr = new BufferedReader(new InputStreamReader(err));
String line;
String errline;
List<String> errres = new ArrayList<>();
while ((line = reader.readLine()) != null) {
result.add(line);
}
while ((errline = errreadr.readLine()) != null) {
errres.add(errline);
}
System.out.println("error stream>>" + errres);
System.out.println("success stream>>" + result);
int exitStatus = channelExec.getExitStatus();
channelExec.disconnect();
session.disconnect();
if (exitStatus < 0) {
System.out.println("Done, but exit status not set!");
} else if (exitStatus > 0) {
System.out.println("Done, but with error!" + exitStatus);
} else {
System.out.println("Done!");
}
} catch (Exception e) {
System.err.println("Error: " + e);
}
return result;
}
实际结果:
error stream>>[]
success stream>>[]
Done, but with error!255
两个流都返回空,但它应该打印路径变量。