Java 如何在jsch中获得输出结果
我试图使用jsch通过SSH获取命令send的输出。我的问题是,我需要将命令的结果转换成字符串,以便以后使用它。例如,如果我发送命令“ls”,我希望文件夹中的文件名为字符串 我该怎么做 这是我的密码:Java 如何在jsch中获得输出结果,java,io,jsch,Java,Io,Jsch,我试图使用jsch通过SSH获取命令send的输出。我的问题是,我需要将命令的结果转换成字符串,以便以后使用它。例如,如果我发送命令“ls”,我希望文件夹中的文件名为字符串 我该怎么做 这是我的密码: import com.jcraft.jsch.*; public class SSHCommand2 { public static void main(String[] args) { String host="host"; String user="user"; S
import com.jcraft.jsch.*;
public class SSHCommand2 {
public static void main(String[] args) {
String host="host";
String user="user";
String password="password";
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("shell");
((ChannelShell) channel).setPty(true);
OutputStream inputstream_for_the_channel = channel.getOutputStream();
PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
channel.setOutputStream(System.out, true);
channel.connect();
commander.println("ls");
if(channel.isClosed()){
//if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
//break;
}
do {
Thread.sleep(1000);
} while(!channel.isEOF());
session.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}
}
这是我读取命令输出的方式 编辑 1) 连接到服务器的方法:
public void connect (final String host){
if(host.isEmpty())
return;
hostname = host;
try{
JSch jsch=new JSch();
String user ="yourUserName";
String host = "yourHost";
Session myLocalSession=jsch.getSession(user, host, 22);
//myLocalSession=jsch.getSession(user, "192.168.1.104", 22);
myLocalSession.setPassword("yourPassword");
myLocalSession.setConfig("StrictHostKeyChecking", "no");
myLocalSession.connect(5000); // making a connection with timeout.
myChannel = myLocalSession.openChannel("shell");
InputStream inStream = myChannel.getInputStream();
OutputStream outStream = myChannel.getOutputStream();
toChannel = new PrintWriter(new OutputStreamWriter(outStream), true);
myChannel.connect();
readerThread(new InputStreamReader(inStream));
Thread.sleep(100);
sendCommand("cd "+path);
}
catch(JSchException e){
String message = e.getMessage();
if(message.contains("UnknownHostException"))
myParser.print(">>>>> Unknow Host. Please verify hostname.");
else if(message.contains("socket is not established"))
myParser.print(">>>>> Can't connect to the server for the moment.");
else if(message.contains("Auth fail"))
myParser.print(">>>>> Please verify login and password");
else if(message.contains("Connection refused"))
myParser.print(">>>>> The server refused the connection");
else
System.out.println("*******Unknown ERROR********");
System.out.println(e.getMessage());
System.out.println(e + "****connect()");
}
catch(IOException e)
{
System.out.println(e);
myParser.print(">>>>> Error when reading data streams from the server");
}
catch(Exception e){
e.printStackTrace();
}
}
2) 方法将命令发送到服务器
public void sendCommand(final String command)
{
if(myLocalSession != null && myLocalSession.isConnected())
{
try {
toChannel.println(command);
} catch(Exception e){
e.printStackTrace();
}
}
}
void readerThread(final InputStreamReader tout)
{
Thread read2 = new Thread(){
@Override
public void run(){
StringBuilder line = new StringBuilder();
char toAppend = ' ';
try {
while(true){
try {
while (tout.ready()) {
toAppend = (char) tout.read();
if(toAppend == '\n')
{
System.out.print(line.toString());
line.setLength(0);
}
else
line.append(toAppend);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("\n\n\n************errorrrrrrr reading character**********\n\n\n");
}
Thread.sleep(1000);
}
}catch (Exception ex) {
System.out.println(ex);
try{
tout.close();
}
catch(Exception e)
{}
}
}
};
read2.start();
}
3) 从服务器读取应答的线程方法
public void sendCommand(final String command)
{
if(myLocalSession != null && myLocalSession.isConnected())
{
try {
toChannel.println(command);
} catch(Exception e){
e.printStackTrace();
}
}
}
void readerThread(final InputStreamReader tout)
{
Thread read2 = new Thread(){
@Override
public void run(){
StringBuilder line = new StringBuilder();
char toAppend = ' ';
try {
while(true){
try {
while (tout.ready()) {
toAppend = (char) tout.read();
if(toAppend == '\n')
{
System.out.print(line.toString());
line.setLength(0);
}
else
line.append(toAppend);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("\n\n\n************errorrrrrrr reading character**********\n\n\n");
}
Thread.sleep(1000);
}
}catch (Exception ex) {
System.out.println(ex);
try{
tout.close();
}
catch(Exception e)
{}
}
}
};
read2.start();
}
您可以将bufferedReader与InputStreamReader一起使用,并逐行读取。我使用一个无限循环,在每次读取失败后暂停一秒钟(服务器上没有任何内容)
假设这三个方法都在SessionB类中。例如:
SessionB testConnexion = new SessionB();
testConnexion.connect();
testConnexion.sendCommand("cd myFolder");
testConnexion.sendCommand("ls");
您应该在控制台中获取文件列表
如果需要,为了能够进行交互(根据输出发送命令),请查看我的帖子。谢谢你的回答,但我真的不知道如何使用它。你能解释一下或者举个例子吗?我编辑了我的答案。我希望它更有帮助。很抱歉耽搁了。我是这个网站的新手,没有反应过来+我没有收到你评论的电子邮件。