1. 程式人生 > >Java通過SSH連線Linux伺服器

Java通過SSH連線Linux伺服器

Java通過SSH連線Linux伺服器

Window系統連線Linux伺服器一般情況下需要使用Xshell去連線,但是如果只是執行一個簡單並且重複的命令時,使用Xshell就顯得大材小用了,並且操作會比較繁瑣。如果能夠使用簡單的java命令去實現就會方便很多。

Jsch(http://www.jcraft.com/jsch/examples/)恰好能夠滿足我們的要求,使用簡單的java命令去連線Linux伺服器並執行shell指令。

示例如下:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class T {
	public static void main(String[] args) throws Exception {
		JSch jsch = new JSch(); // 建立JSch物件
		String userName = "";// 使用者名稱
		String password = "";// 密碼
		String host = "";// 伺服器地址
		int port = 0;// 埠號
		String cmd = "";// 要執行的命令
		Session session = jsch.getSession(userName, host, port); // 根據使用者名稱,主機ip,埠獲取一個Session物件
		session.setPassword(password); // 設定密碼
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config); // 為Session物件設定properties
		int timeout = 60000000;
		session.setTimeout(timeout); // 設定timeout時間
		session.connect(); // 通過Session建立連結
		ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
		channelExec.setCommand(cmd);
		channelExec.setInputStream(null);
		channelExec.setErrStream(System.err);
		channelExec.connect();
		InputStream in = channelExec.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
		String buf = null;
		StringBuffer sb = new StringBuffer();
		while ((buf = reader.readLine()) != null) {
			sb.append(buf);
			System.out.println(buf);// 列印控制檯輸出
		}
		reader.close();
		channelExec.disconnect();
		if (null != session) {
			session.disconnect();
		}
	}
}