JSch 应用

今天在做一个连接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();
}
}
}

}


最后感觉命令似乎并没有传到服务器端。。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值