ssh 远程调用

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();
}
}
}

}

相关推荐