论坛首页 入门技术论坛

JSch 应用

浏览 4589 次
锁定老帖子 主题:JSch 应用
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-03  
今天在做一个连接linux SSH服务器的一个客户端,要求可以执行自定义的linux命令,发现已经有一个工具可以帮组建立连接JSCH

在运动Shell命令的时候可以在控制台上输入linux命令去执行,但是这个东西要放到web上运用,需要将输入输出转到其他流,所以考虑用管道流来控制,但是具体怎么让传进去的命令执行还是不大清楚,下面是代码:

package com.sun.work;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class PipeStreamTest {

public static void main(String args[]){
try {
new PipeStreamTest().connect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connect() throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession("test", "10.67.7.109", 22);
session.setPassword("SVNAdmin");
Properties prop = new Properties();
prop.setProperty("StrictHostKeyChecking", "no");// StrictHostKeyChecking:
// ask | yes | no
session.setConfig(prop);
session.connect();

Channel channel = session.openChannel("shell");
Sender t1 = new Sender();
Receiver t2 = new Receiver();
PipedInputStream pis1 = t2.getInputStream();
PipedOutputStream pos1 = t1.getOutputStream();
//如果是用控制台,可以这样设置。
// channel.setOutputStream(System.out);
// channel.setInputStream(System.in);
channel.setInputStream(pis1);
channel.setOutputStream(pos1);


try {
pos1.connect(pis1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.start();
t2.start();
channel.connect();
}

class Sender extends Thread {
private PipedOutputStream out = new PipedOutputStream();

public PipedOutputStream getOutputStream() {
return out;
}

public void run() {
String s = "ls -F";
try {
out.write(s.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

class Receiver extends Thread {
private PipedInputStream in = new PipedInputStream();

public PipedInputStream getInputStream() {
return in;
}

public void run() {
byte[] buf = new byte[10240];
try {
while(in.read()!=-1){
int len = in.read(buf);
System.out.println(len);
String s = new String(buf, 0, len);
System.out.println(s);
//in.close();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

}


最后感觉命令似乎并没有传到服务器端。。。。
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics