我正在尝试使用jsch来获取通过SSH发送命令的输出。我的问题是我需要将命令的结果导入String,以便以后使用它。例如,如果我发送命令“ls”,我希望文件夹中的文件名称为字符串。
我该怎么做?
这是我的代码:
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();
}
}
答案 0 :(得分:3)
这就是我读取命令输出的方法
修改强>
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();
}
}
}
3)从服务器读取答案的线程方法
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");
您应该在控制台中获取文件列表。
如果您需要,为了能够互动(根据输出发送命令),请查看我的帖子here。