日期:2014-05-16 浏览次数:20651 次
?
?
Jsch shell模式下的代码示例:
参考:http://stackoverflow.com/questions/6770206/what-is-the-difference-between-the-shell-channel-and-the-exec-channel-in-jsc
?
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JOptionPane;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
public class JschShellTest {
/**
* @param args
*/
public static void main(String[] args) {
Session session = null;
Channel channel = null;
String host = "127.0.0.1", user = "conkeyn", passwd = "123456";
Integer port = 2222;
JSch jsch = new JSch();
try {
String dir = Shell.class.getClassLoader().getResource(".").getFile();
//把已经连接过的主机保存到known_hosts文件中。
jsch.setKnownHosts(dir + ".ssh/known_hosts");
session = jsch.getSession(user, host, port);
session.setPassword(passwd);
UserInfo ui = new MyUserInfo() {
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
public boolean promptYesNo(String message) {
Object[] options = { "yes", "no" };
int foo = JOptionPane.showOptionDialog(null, message, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
return foo == 0;
}
// If password is not given before the invocation of
// Session#connect(),
// implement also following methods,
// * UserInfo#getPassword(),
// * UserInfo#promptPassword(String message) and
// * UIKeyboardInteractive#promptKeyboardInteractive()
};
session.setUserInfo(ui);
session.connect(30000);
channel = session.openChannel("shell");
//相对channel与sshd端,channel输出流是用于输出命令到sshd。
OutputStream inputstream_for_the_channel = channel.getOutputStream();
PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
channel.setOutputStream(System.out, true);
// 可以使用以下注释的代码替代“channel.setOutputStream(System.out, true);”
//相对channel与sshd端,channel输入流是用于接收sshd输出结果的
// InputStream outputstream_from_the_channel = channel.getInputStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
// String line;
// while ((line = br.readLine()) != null)
// System.out.print(line+"\n");
channel.connect();
commander.println("ls -la");
commander.println("cd ~");
commander.println("ls -la");
commander.println("exit");
commander.close();
//如果输出到结尾,则可以退出等待。
do {
Thread.sleep(1000);
} while (!channel.isEOF());
} catch (Exception e) {
e.printStackTrace();
}
session.disconnect();
}
}
?
在
?