Jsch shell模式下的代码示例:
参考:http://stackoverflow.com/questions/6770206/what-is-the-difference-between-the-shell-channel-and-the-exec-channel-in-jsc
Shell.java
import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class Shell {
public static void main(String[] arg) {
Channel channel = null;
Session session = null;
try {
String dir = Shell.class.getClassLoader().getResource(".").getFile();
JSch jsch = new JSch();
// System.out.println(dir);
// System.exit(0);
jsch.setKnownHosts(dir + ".ssh/known_hosts");
// jsch.setKnownHosts("/home/foo/.ssh/known_hosts");
String host = null, host1 = null;
Integer port = 22;
if (arg.length > 0) {
host = arg[0];
} else {
host = JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name") + "@localhost");
}
String user = host.substring(0, host.indexOf('@'));
String p = null;
if (host.indexOf(':') != -1) {
host1 = host.substring(host.indexOf('@') + 1, host.indexOf(':'));
p = host.substring(host.indexOf(':') + 1);
try {
port = Integer.parseInt(p);
} catch (Exception e) {
e.printStackTrace();
port = 22;
}
} else {
host1 = host.substring(host.indexOf('@') + 1);
}
session = jsch.getSession(user, host1, port);
String passwd = JOptionPane.showInputDialog("Enter password");
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);
// It must not be recommended, but if you want to skip host-key
// check,
// invoke following,
// session.setConfig("StrictHostKeyChecking", "no");
// session.connect();
session.connect(30000); // making a connection with timeout.
channel = session.openChannel("shell");
// Enable agent-forwarding.
// ((ChannelShell)channel).setAgentForwarding(true);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat df1 = new SimpleDateFormat("HH:mm:ss");
Date d1 = new Date();
String command = "sudo /bin/date -s " + df.format(d1) + " && sudo /bin/date -s " + df1.format(d1) + " \n";
byte[] bytes = command.getBytes();
ByteArrayInputStream bInput = new ByteArrayInputStream(bytes);
// channel.setInputStream(System.in);
channel.setInputStream(bInput);
/*
* // a hack for MS-DOS prompt on Windows.
* channel.setInputStream(new FilterInputStream(System.in){ public
* int read(byte[] b, int off, int len)throws IOException{ return
* in.read(b, off, (len>1024?1024:len)); } });
*/
channel.setOutputStream(System.out);
// FileOutputStream foutput = new FileOutputStream(dir +
// "shell.log", true);
// channel.setOutputStream(foutput);
/*
* // Choose the pty-type "vt102".
* ((ChannelShell)channel).setPtyType("vt102");
*/
/*
* // Set environment variable "LANG" as "ja_JP.eucJP".
* ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
*/
channel.connect();
// 如果输出没有结尾,则一直等待下去
do {
Thread.currentThread().sleep(1000);
} while (!channel.isEOF());
} catch (Exception e) {
System.out.println(e);
} finally {
channel.disconnect();
session.disconnect();
}
}
public static abstract class MyUserInfo implements UserInfo, UIKeyboardInteractive {
public String getPassword() {
return null;
}
public boolean promptYesNo(String str) {
return false;
}
public String getPassphrase() {
return null;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptPassword(String message) {
return false;
}
public void showMessage(String message) {
}
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}
}
MyUserInfo.java
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
/**
* 主要功能是用于提示用户输入或确认信息的接口实现。
*
* @author Administrator
*
*/
public abstract class MyUserInfo implements UserInfo, UIKeyboardInteractive {
private String password;
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean promptYesNo(String str) {
return false;
}
public String getPassphrase() {
return this.password;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptPassword(String message) {
return false;
}
public void showMessage(String message) {
}
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}
JschShellTest.java
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();
}
}
在