Код: Выделить всё
private static Session getSession() {
if (session == null || !session.isConnected()) {
session = connect(hostname, username, password);
}
return session;
}
private static Channel getChannel() {
if (channel == null || !channel.isConnected()) {
try {
channel = (ChannelShell) getSession().openChannel("shell");
channel.connect();
} catch (Exception e) {
System.out.println("Error while opening channel: " + e);
}
}
return channel;
}
private static Session connect(String hostname, String username, String password) {
JSch jSch = new JSch();
try {
session = jSch.getSession(username, hostname, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
System.out.println("Connecting SSH to " + hostname + " - Please wait for few seconds... ");
session.connect();
System.out.println("Connected!");
} catch (Exception e) {
System.out.println("An error occurred while connecting to " + hostname + ": " + e);
}
return session;
}
static void executeCommands(List commands) {
try {
Channel channel = getChannel();
System.out.println("Sending commands...");
sendCommands(channel, commands);
readChannelOutput(channel);
System.out.println("Finished sending commands!");
} catch (Exception e) {
System.out.println("An error ocurred during executeCommands: " + e);
}
}
private static void sendCommands(Channel channel, List commands) {
try {
PrintStream out = new PrintStream(channel.getOutputStream());
out.println("#!/bin/bash");
for (String command : commands) {
out.println(command);
}
out.println("exit");
out.flush();
} catch (Exception e) {
System.out.println("Error while sending commands: " + e);
}
}
private static void readChannelOutput(Channel channel) {
byte[] buffer = new byte[1024];
try {
InputStream in = channel.getInputStream();
String line = "";
while (true) {
while (in.available() > 0) {
int i = in.read(buffer, 0, 1024);
if (i < 0) {
break;
}
line = new String(buffer, 0, i);
System.out.println(line);
}
if (line.contains("logout")) {
break;
}
if (channel.isClosed()) {
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
} catch (Exception e) {
System.out.println("Error while reading channel output: " + e);
}
}
Я ожидаю получить вывод удаленно выполненной команды. Например, если я выполняю ls -l, он должен вывести список всех подкаталогов/файлов этого компьютера.
Обновление 1
Добавление вывода, который я получаю для приведенного выше кода, с помощью одной простой команды ls -l -
Код: Выделить всё
Connecting SSH to 17x.xx.xx.xx - Please wait for few seconds...
Connected!
Sending commands...
]0;c:\windows\system32\cmd.exeMicrosoft Windows [Version 10.0.17763.3770]
(c) 2018 Microsoft Corporation. All rights reserved.
abc\administrator@xyz28 C:\Users\Administrator>#!/bin/bashls -lexit
]0;Administrator: c:\windows\system32\cmd.exe
Обновление 2
Здесь мое основное требование — программно подключиться по SSH от клиента на базе Unix к серверу Windows, выполнить некоторые команды PowerShell и прочитать соответствующие выходные данные с какой-либо библиотекой или без нее. .
Подробнее здесь: https://stackoverflow.com/questions/787 ... using-jsch