`
conkeyn
  • 浏览: 1505599 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Jsch使用

    博客分类:
  • Java
 
阅读更多

 

 

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

	}

}

 

 

分享到:
评论

相关推荐

    java使用JSCH进行连接远程服务器Demo

    是使用java使用JSCH进行连接远程服务器的Demo,让更多刚刚接触的同学进行学习。

    jsch-0.1.54-API文档-中文版.zip

    赠送jar包:jsch-0.1.54.jar; 赠送原API文档:jsch-0.1.54-javadoc.jar; 赠送源代码:jsch-0.1.54-sources.jar; 赠送Maven依赖信息文件:jsch-0.1.54.pom; 包含翻译后的API文档:jsch-0.1.54-javadoc-API文档-...

    jsch_jsch jsch_jsch jsch_jsch

    jsch_jschjsch_jschjsch_jschjsch_jschjsch_jschjsch_jschjsch_jschjsch_jsch

    JSCH免费下载啦

    Jsch jar包 下载 SFTP 欢迎是大家下载 jsch-0.1.51.jar

    jsch实现sftp文件上传、下载 ,jsch jar

    jsch实现sftp文件上传、下载文件,提供jsch jar

    jsch文件名中文乱码解决办法

    *jsch的源文件 *jsch的依赖包 *用jsch源文件及依赖包构建的项目,便于修改其源码* 修改源码后重新导出的jar包 *我写的一段小程序,实现的主要功能是同步sftp上的文件夹(sftp->本地) *我写的一个小程序,用于将字符...

    jsch-0.1.55_jsch_JSCH0.1._55_服务器_jsch0.1.55_

    JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器

    详解Java使用Jsch与sftp服务器实现ssh免密登录

    主要介绍了详解Java使用Jsch与sftp服务器实现ssh免密登录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    jsch-0.1.53 使用sftp协议上传下载文件名中文乱码解决办法

    jsch-0.1.53 不支持修改编码格式,sftp.setFilenameEncoding("GBK");这样修改是不起作用的,所以必须修改源码。此处是修改源码后重新导出的jar包。

    jsch的jar包最新版

    它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。同时该开发包也提供 J2ME 下的版本

    jsch jar包

    包括jsch-0.1.51.jar jsch-0.1.52.jar jsch-0.1.53.jar三个版本的包

    jsch-0.1.42

    jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42jsch-0.1.42

    jsch API文档

    jsch_APIchm.rar

    jsch依赖包.zip

    java使用Jsch组件链接资源上传下载文件 java使用Jsch组件链接资源上传下载文件 依赖jar包jsch-0.1.55.jar

    jsch-0.1.53.jar

    jsch-0.1.53 jsch-0.1.53 jsch-0.1.53 jsch-0.1.53 jsch-0.1.53 jsch-0.1.53

    jsch实现远程传输

    jsch,jsch工具类,jsch实现远程sftp,jsch实现过程 通过JSch实现sftp传输文件

    jsch连接linux例子

    这里是我使用jsch连接linux并且执行相关命令的案例,希望对你有所帮助。

    jsch API CHM格式

    JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。 从之前发布其他chm文件下载用户的反映看,有不少朋友反映下载后...

    使用jsch中的ChannelSftp上传文件和文件夹[参考].pdf

    使用jsch中的ChannelSftp上传文件和文件夹[参考].pdf

    jsch-0.1.54.zip

    包含了源码与示例。 jar包单独下载,链接: https://sourceforge.net/projects/jsch/?source=typ_redirect

Global site tag (gtag.js) - Google Analytics