gpt4 book ai didi

java - 如何在 String 中获取 jsch shell 命令输出

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:03 24 4
gpt4 key购买 nike

我正在使用 JSCH -SSH 库在“shell” channel 中执行命令,但无法找到方法做两件事:-

1) 如何判断命令是否在远程unix box上执行完毕?

2) 如何在 String 中捕获命令输出,而不是在 System.out 控制台上打印它?

下面是我的代码片段,它可以很好地在 system.out 上显示 shell 命令输出

注意:我不想使用“exec” channel ,因为它会为每个命令启动一个新进程,并且不记得导出的“ session ”变量。我必须使用“外壳” channel 。

下面是我的代码片段。感谢您的帮助。感谢您的宝贵时间。

try{

String commandToRun = "ls /tmp/*.log \n";
if(channel.isClosed())
channel=session.openChannel("shell");
byte[] bytes = commandToRun.getBytes();
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
channel.setInputStream(bais);
InputStream ins=channel.getInputStream();
channel.connect();
channel.setOutputStream(System.out);//This prints on console. Need 2 capture in String somehow?

//in-efficient way to allow command to execute completely on remote Unix machine
//DO NOT know a better way, to know when command is executed completely
Thread.sleep(5000L);
}
catch(Exception e){
System.out.println("Exception in executeCommand() --->"+ e.getMessage());
e.printStackTrace();
}

最佳答案

OP 可能不再需要我的解决方案,但任何正在寻找解决方案来满足这两种情况的人 1) 等待命令在远程机器上完成;和 2) 将输出捕获为字符串;你可以试试这个:

public class SshConnectionManager {

private static Session session;
private static ChannelShell channel;
private static String username = "";
private static String password = "";
private static String hostname = "";


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;

}

private static void executeCommands(List<String> 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<String> 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);
}

}

public static void close(){
channel.disconnect();
session.disconnect();
System.out.println("Disconnected channel and session");
}


public static void main(String[] args){
List<String> commands = new ArrayList<String>();
commands.add("ls -l");

executeCommands(commands);
close();
}
}

如果您需要一次发送多个命令并保持 channel 打开以便稍后重用,此解决方案也很有用。

关于java - 如何在 String 中获取 jsch shell 命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com