java jsch shell_如何在字符串中获取jsch shell命令输出

小编典典

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 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);

}

}

public static void close(){

channel.disconnect();

session.disconnect();

System.out.println("Disconnected channel and session");

}

public static void main(String[] args){

List commands = new ArrayList();

commands.add("ls -l");

executeCommands(commands);

close();

}

}

如果您需要一次发送多个命令并保持通道打开以供以后使用,则此解决方案也很有用。

2020-11-19

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!针对您的问题,我可以给出以下解答: Java JSch 是一个用于远程执行命令和传输文件的 Java 库,通过 JSch,我们可以在 Java 应用程序连接到远程主机,并执行远程主机上的命令。 针对您的问题,如果您在使用 Java JSch 调用 shell 脚本时,脚本执行后立即退出,可能是因为您的 Java 程序没有等待 shell 脚本执行完毕就立即退出了。 为了解决这个问题,您可以在调用 shell 脚本的代码,使用 `ChannelExec.setPty(true)` 方法启用伪终端模式,并使用 `ChannelExec.setCommand(command + ";echo finished")` 方法在 shell 脚本执行完毕后输出一个 "finished" 的标识符。然后您可以使用 `ChannelExec.getInputStream()` 方法获取 shell 脚本的输出流,并等待输出包含 "finished" 标识符,表示 shell 脚本已经执行完毕,然后再关闭连接。 以下是一个示例代码: ``` JSch jsch = new JSch(); Session session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setPty(true); channelExec.setCommand(command + ";echo finished"); channelExec.setInputStream(null); channelExec.setErrStream(System.err); InputStream inputStream = channelExec.getInputStream(); channelExec.connect(); byte[] tmp = new byte[1024]; while (true) { while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channelExec.isClosed()) { if (inputStream.available() > 0) continue; System.out.println("exit-status: " + channelExec.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) {} } channelExec.disconnect(); session.disconnect(); ``` 希望这个解答能够帮到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值