Использование JSch для выполнения скрипта на powershell
Я хочу выполнить powershell, а затем выполнить некоторые команды в удаленной системе Windows, и я использую JSCH ( http://www.jcraft.com/jsch/). У меня Win32-OpenSSH на компьютере с Windows https://github.com/PowerShell/Win32-OpenSSH
Когда я использую канал "exec", он запускает powershell и закрывает его, поэтому я не могу запускать команды в powershell. С другой стороны, если я запускаю канал "shell", я получаю вывод из командной строки, такой как "Microsoft Windows [Версия 10.0.14393] (c) Microsoft Corporation, 2016 г. Все права защищены". Поэтому я хочу выполнить powershell и получить потоки процесса powershell, чтобы я мог написать свой сценарий в этот поток и также прочитать вывод. При просмотре примеров потоки, которые я получаю, - это потоки SSH-соединения, где запускается сам PowerShell, а не потоки внутри / в PowerShell.
Я использую следующий код для выполнения команд в powershell
private Streams executePowershell(Session session, String command) throws JSchException, IOException {
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(System.err);
//4. Getting response as a stream
channel.connect();
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
System.out.println(out);
Streams streams = new Streams();
streams.setInputStream(in);
streams.setOutputStream(out);
streams.setChannel(channel);
return streams;
}
//command will be powershell to invoke the powershell itself
//command2 will be something such as dir that is the command to execute within powershell
public String executeCommand(String command, String command2) {
String output = null;
try {
Session session = getSession();
Streams streams = null;
streams = executePowershell(session, command);
OutputStream outputStream = streams.getOutputStream();
Util.writeToStream(outputStream, command2);
output = Util.readStream(streams.getInputStream()).toString();
streams.getChannel().disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return output;
}