[英]execute multiple command with jsch session and channelexec
我努力让它工作,但最终让脚本在远程 unix 服务器上执行命令(执行 sh 脚本)。 我正在尝试执行第二个命令并在创建新频道或使用相同频道时不断收到错误消息。
try {
((ChannelExec) channel).setCommand(command);
PrintStream out= new PrintStream(channel.getOutputStream());
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader scriptReader= new BufferedReader(new InputStreamReader(in));
scriptOutput = scriptReader.readLine();
sb = new StringBuilder();
while ((scriptOutput = scriptReader.readLine())!= null) {
sb.append(scriptOutput + "\n");
这是频道执行的第一个片段,效果很好。 现在,在使用上述输入流后立即调用下一个方法片段:
try {
StringBuilder sb = new StringBuilder();
command = new_command;
((ChannelExec) channel).setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader scriptReader= new BufferedReader(new InputStreamReader(in));
scriptOutput = scriptReader.readLine();
//StringBuilder sb = new StringBuilder();
for(int c=0; c < consumerList.size(); c++){
....
现在返回以下错误:
com.jcraft.jsch.JSchException: channel is not opened.
现在,如果我使用相同的会话创建一个新频道,我会从返回的流中得到一个空响应。 我确实在远程 shell 中测试了命令,它工作正常:
int counter = 0;
Channel channelII = session.openChannel("exec");
try {
StringBuilder sb = new StringBuilder();
command = new_command;
((ChannelExec) channelII).setCommand(command);
InputStream in = channelII.getInputStream();
channelII.connect();
BufferedReader scriptReader= new BufferedReader(
new InputStreamReader(in));
scriptOutput = scriptReader.readLine();
第二个命令如下,我希望能够为不同的消费者群体重复执行它:
/usr/kafka/bin/kafka-consumer-groups.sh --bootstrap-server
192.xxx.xx.xxx:9092 --describe -group consumergroup1
编辑:
第二个命令的响应:
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET
LAG CONSUMER-ID HOST
CLIENT-ID
output.influxDB 1 94919 2781796
2686877 - -
-
output.influxDB 0 94919 2781798
2686879 - -
-
output.influxDB 2 94918 2781795
2686877 - -
-
感谢 Nicholas 和 Martin 的回复。 我弄清楚出了什么问题并想发布一个答案,因为我确实意识到这样的小事情确实会出现在我们那里的“愚蠢”程序员身上,他们提出了会招致反对票的荒谬问题。 第二个命令的输出在第一行返回一个警告/错误响应,不包括以下内容,我没有看到,阅读下一行是空的。 我知道这很愚蠢,并且应该在发布之前弄清楚这一点,因为这就是本网站的重点:发布超出其他人知识范围的问题。 但既然我天生就应该知道这一点:
无论如何确保包括以下行:
((ChannelExec)channelII).setErrStream(System.err);
并且还使用循环读取流,而不仅仅是通过读取第一行进行测试。
while ((scriptOutput = scriptReader.readLine())!= null) {
sb.append(scriptOutput + "\n");
}
我希望这至少可以成为一些人的教训,如果不是解决方案的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.