gpt4 book ai didi

java - 通过java ssh,将错误存储在变量中

转载 作者:行者123 更新时间:2023-11-30 04:08:09 25 4
gpt4 key购买 nike

我正在使用 jsch 库通过 ssh 执行 rm 命令。命令正在正确发送并执行。但是当在目录中找不到我要删除的文件时,我收到如下错误消息:

No such file or directory

我想将错误消息存储在变量中,然后使用它。

当前执行以下操作时会显示此消息:

((ChannelExec)channel).setErrStream(System.err);  
InputStream in=channel.getInputStream();
channel.connect();

在channel.connect()之后,会显示错误消息。如何将其存储在变量(假设是字符串)中并在完成后打印它?

下面是主类。

        String SSHHOST = "127.0.0.1";
int SSHPPORT = 22;
String SSHPUSER = "user";
String SSHPPASS = "pass";
StringBuilder result = new StringBuilder();
System.out.println("Connecting To Server "+SSHHOST);
JSch jsch = new JSch();
Session session=jsch.getSession(SSHPUSER, SSHHOST, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(SSHPPASS);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("find /home/test/DC* -print -exec rm {} \\;|wc -l");
channel.setInputStream(null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
((ChannelExec)channel).setErrStream(bos) ;
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
String result2 = bos.toString();
System.out.println(result2);
byte[] tmp=new byte[1024];
while(true)
{
while(in.available()>0)
{
int i=in.read(tmp, 0, 1024);
if(i<0)break;
out=new String(tmp, 0, i);
}
if(channel.isClosed())
{
//System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try
{
Thread.sleep(1000);
}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
int status = channel.getExitStatus();
System.out.println(out.trim());
if (channel.getExitStatus() == 0)
{
System.out.println("Perso file purging process completed successfully.");
System.out.println("exit-status: "+channel.getExitStatus());
System.out.println("Number of perso files deleted : "+out);
}
else
{
System.out.println("Perso file purging process completed with errors.");
}

使用上述代码在目录中找不到文件时,仍然无法得到错误消息。

最佳答案

这只是我的猜测,但是......

您似乎将 channel 对象的错误流设置为应用程序的 System.err - 除非您已将应用程序的 System.err 重新配置为指向其他位置,即控制台。

setErrStream 采用什么参数?如果它是一个 OutputStream,您能否将其写入 ByteArrayOutputStream,然后从中构建一个字符串?

关于java - 通过java ssh,将错误存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266418/

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