java jsch exec,JSch Exec输出错误

博主需在远程机器上运行Shell脚本,使用JSch的ChannelExec连接并执行。想了解执行命令时如何知晓是否出错,给出了代码示例。解决方案是参考官方示例,还可通过ChannelExec.getErrStream读取错误流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I need to run shell script at a remote machine. I am using JSch to connect to the remote machine and executing the shell script using ChannelExec.

I need to know how I can get to know, if there was any error while execution of the command.

Following is my code

ChannelExec channel = (ChannelExec) session.openChannel("exec");

BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));

String command = scriptName;

if(parameter != null && !parameter.isEmpty()){

command += " " + parameter;

}

LOGGER.debug("Command To be Executed: " + command);

channel.setCommand(command);

channel.connect();

//capture output

String msg;

StringBuffer output = new StringBuffer();

while ((msg = in.readLine()) != null)

{

//output = output + msg;

output.append(msg);

}

LOGGER.debug("Output Message = " + output.toString());

LOGGER.debug("ERROR STATUS --" + channel.getExitStatus());

channel.disconnect();

session.disconnect();

解决方案

Start with the official example for the "exec" channel, do not re-invent the wheel:

http://www.jcraft.com/jsch/examples/Exec.java.html

To read the error, read also the error stream using the ChannelExec.getErrStream.

你可以使用JSch库来连接SSH服务器并执行exec命令。以下是一个简单的示例代码: ```java import com.jcraft.jsch.*; public class SSHCommandExecutor { public static void main(String[] args) { String host = "your_ssh_host"; String username = "your_ssh_username"; String password = "your_ssh_password"; String command = "your_command_to_execute"; try { JSch jsch = new JSch(); Session session = jsch.getSession(username, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setCommand(command); channelExec.connect(); InputStream in = channelExec.getInputStream(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } System.out.print(new String(tmp, 0, i)); } if (channelExec.isClosed()) { if (in.available() > 0) { continue; } System.out.println("exit-status: " + channelExec.getExitStatus()); break; } Thread.sleep(1000); } channelExec.disconnect(); session.disconnect(); } catch (Exception e) { System.out.println(e); } } } ``` 在这个示例中,我们使用JSch库创建一个连接到SSH服务器的会话,并打开一个exec通道来执行命令。我们通过通道的输入流读取命令的输出,并在控制台上打印出来。最后,我们断开通道和会话连接。 请注意,您需要将“your_ssh_host”、“your_ssh_username”、“your_ssh_password”和“your_command_to_execute”替换为您实际使用的SSH主机、用户名、密码和要执行的命令。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值