java调用sshd windows,java-使用JSch在远程SSH会话上运行telnet命令

我知道了.

在while循环中,line永远不会为null.

为何在调试中起作用仍然是个谜.

我正在发布我的新代码.我希望它对每个想做类似事情的人都有帮助.

package Utility;

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.JSchException;

import com.jcraft.jsch.Session;

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.InputStreamReader;

public class JavaTelnet {

public static void main(String[] arg) {

try {

System.out.println(telnetConnection(YOUR_COMMAND,YOUR_USER,YOUR_PASS,YOUR_HOST));

} catch (Exception e) {

e.printStackTrace();

}

}

public static String telnetConnection(String command, String user, String password, String host) throws JSchException, Exception {

JSch jsch=new JSch();

Session session=jsch.getSession(user, host, 22);

session.setPassword(password);

// It must not be recommended, but if you want to skip host-key check,

session.setConfig("StrictHostKeyChecking", "no");

session.connect(3000);

//session.connect(30000); // making a connection with timeout.

Channel channel=session.openChannel("shell");

channel.connect(3000);

DataInputStream dataIn = new DataInputStream(channel.getInputStream());

BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));

DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());

System.out.println("Starting telnet connection...");

dataOut.writeBytes("telnet localhost 4242

");

// dataOut.writeBytes("enable

");

dataOut.writeBytes(command+"

");

dataOut.writeBytes("exit

"); //exit from telnet

dataOut.writeBytes("exit

"); //exit from shell

dataOut.flush();

String line = reader.readLine();

String result = line +"

";

while (!(line= reader.readLine()).equals("Connection closed by foreign host")){

result += line +"

";

}

dataIn.close();

dataOut.close();

channel.disconnect();

session.disconnect();

return result;

}

}

注:

该外壳是Linux外壳.在Windows中,“退出”命令应该不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值