一、前言
?
前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
?
JSch是SSH2的純Java實現?。
JSch允許您連接到sshd服務器并使用端口轉發,X11轉發,文件傳輸等,您可以將其功能集成到您自己的Java程序中。JSch獲得BSD格式許可證。
?
最初,我們開發這些東西的動機是允許我們的純Java X服務器?WiredX的用戶享受安全的X會話。所以,我們的努力主要是為了實現用于X11轉發的SSH2協議。當然,我們現在也有興趣添加端口轉發,文件傳輸,終端仿真等其他功能。
官網上有很詳細說明和例子:
官網:http://www.jcraft.com/jsch/
----------------------------------------------------------------------------------------------------------------------------------
?
?
二、 實現demo?
1. 工具類:
?
- USER:所連接的Linux主機登錄時的用戶名
- PASSWORD:登錄密碼
- HOST:主機地址
- DEFAULT_SSH_PROT=端口號,默認為22
package util;import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;public class SSHUtil {private Channel channel;private Session session = null;private int timeout = 60000;public SSHUtil(final String ipAddress, final String username, final String password) throws Exception {JSch jsch = new JSch();this.session = jsch.getSession(username, ipAddress, 22);this.session.setPassword(password);this.session.setConfig("StrictHostKeyChecking", "no");this.session.setTimeout(this.timeout);this.session.connect();this.channel = this.session.openChannel("shell");this.channel.connect(1000);}public String runShell(String cmd, String charset) throws Exception {String temp = null;InputStream instream = null;OutputStream outstream = null;try {instream = this.channel.getInputStream();outstream = this.channel.getOutputStream();outstream.write(cmd.getBytes());outstream.flush();TimeUnit.SECONDS.sleep(2);if (instream.available() > 0) {byte[] data = new byte[instream.available()];int nLen = instream.read(data);if (nLen < 0) {throw new Exception("network error...桌面有錯誤");}temp = new String(data, 0, nLen, "UTF-8");}} finally {outstream.close();instream.close();}return temp;}public void close() {this.channel.disconnect();this.session.disconnect();}
}
?
2. 調用:
import util.SSHUtil;public class Test {public static void main(String[] args) throws Exception{SSHUtil sshUtil = new SSHUtil("xx.xx.xx.2", "root", "xxxxxng");String res = sshUtil.runShell("cd xxx\n ps -ef | grep java | awk '{print $2}' | xargs kill -9 \n nohup java -jar xxxx-0.0.1-SNAPSHOT.jar & \n", "utf-8");//重啟數據庫//String res = sshUtil.runShell("docken restart JY_mysql \n", "utf-8");//String res = sshUtil.runShell("nohup java -jar forlovehome-0.0.1-SNAPSHOT.jar & \n", "utf-8");// String res = sshUtil.runShell("/usr/apache-tomcat-7.0.47/bin/startup.sh\n", "utf-8");System.out.println(res);sshUtil.close();}
}
?
?
?
參考:http://www.importnew.com/22322.html
http://www.jcraft.com/jsch/
?