我正在使用ssh
库通过jsch
执行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.");
}
当使用上述代码在目录中找不到文件时,我仍然无法收到错误消息。
答案 0 :(得分:2)
这是对我的一点猜测,但是......
您似乎将通道对象的错误流设置为应用程序的System.err - 除非您已将应用程序的System.err重新配置为指向其他位置,这将是控制台。
setErrStream采用什么参数?如果它是一个OutputStream,你可以让它写入ByteArrayOutputStream,然后从中构建一个字符串吗?
答案 1 :(得分:0)
我已经能够使用FileOutputStream
FileOutputStream fos = null;
File file = new File("errors.txt");
try
{
fos = new FileOutputStream(file);
}
catch(IOException ioe)
{
System.err.println("redirection not possible: "+ioe);
System.exit(-1);
}
PrintStream ps = new PrintStream(fos);
((ChannelExec)channel).setErrStream(ps);