欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java执行SSH/SCP之JSch

程序员文章站 2022-05-14 22:46:29
...
JSch (Java Secure Channel)是纯Java的SSH2实现。可以把它集成到你的Java应用中来连接sshd服务器,执行指令(port forward, file transfer, terminal emulation)。Ant、Eclipse-CVSSSH2、NetBeans等工具都在使用它。如果你的服务部署在linux服务器中,有时你需要执行一些系统命令,这时候需要用到Runtime.getRuntime().exec("java -version"); 但是这样会让你的服务器内存瞬间增长很多。JSch基于JavaTM Cryptography Extension(JCE)通过Socket来实现通信,可以大大减少内存的暴涨。

http://www.jcraft.com/

版本:jsch-0.1.51.jar

SSH例子:
public void ssh() throws Exception {
	JSch jsch = new JSch();

	// connect session
	Session session = jsch.getSession(USER_ID, HOST_NAME, 22);
	session.setPassword(PASSWORD);
	session.setConfig("StrictHostKeyChecking", "no");
	session.connect();

	// exec command remotely
	String command = "ls -l";
	ChannelExec channel = (ChannelExec) session.openChannel("exec");
	channel.setCommand(command);
	channel.connect();

	// get stdout
	InputStream in = channel.getInputStream();
	byte[] tmp = new byte[1024];
	while (true) {
		while (in.available() > 0) {
			int i = in.read(tmp, 0, 1024);
			if (i < 0)
				break;
			System.out.print(new String(tmp, 0, i));
		}
		if (channel.isClosed()) {
			System.out.println("exit-status: " + channel.getExitStatus());
			break;
		}
		try {
			Thread.sleep(1000);
		} catch (Exception ee) {
		}
	}
	channel.disconnect();
	session.disconnect();
}


SFTP例子:
public void sftp() throws Exception {
	JSch jsch = new JSch();
	
	// connect session
	Session session = jsch.getSession(USER_ID, HOST_NAME, 22);
	session.setPassword(PASSWORD);
	session.setConfig("StrictHostKeyChecking", "no");
	session.connect();

	// sftp remotely
	ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
	channel.connect();

	// ls
	Vector list = channel.ls(".");
	System.out.println("---- ls");
	for (int i = 0; i < list.size(); i++) {
		System.out.println(list.get(i));
	}

	// lstat
	try {
		SftpATTRS stat = channel.lstat("index.html");
		System.out.println("---- lstat");
		System.out.println(stat);
		System.out.println(stat.getSize());
	} catch (SftpException ex) {
		ex.printStackTrace();
	}

	// get
	channel.get("./index.html", "./index.html.dst");
	// put
	channel.put(new FileInputStream("c:/test.txt"), "test_new.txt");

	channel.disconnect();
	session.disconnect();
}


其他的工具还有:
Ganymed SSH-2:https://code.google.com/p/ganymed-ssh-2/
sshj :https://github.com/shikhar/sshj
Apache SSHD:http://mina.apache.org/sshd-project/