一、前言
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。
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/