JSch-Javaセキュアチャネル:リモートサーバー操作用のJavaコード



Jsch Java Secure Channel



I.はじめに

JSchは SSH2 純粋なJavaの実装

JSchを使用すると、sshdサーバーに接続して、ポート転送、X11転送、ファイル転送などを使用できます。その機能を独自のJavaプログラムに統合できます。JSch取得 BSDフォーマットライセンス



当初、これらを開発する動機は、純粋なJavaXサーバーを許可することでした。 WiredX ユーザーは安全なXセッションを楽しむことができます。したがって、私たちの努力は主にX11転送用のSSH2プロトコルを実装することです。もちろん、ポートフォワーディング、ファイル転送、端末エミュレーション、その他の機能の追加にも関心があります。

公式ウェブサイトには非常に詳細な手順と例があります。

公式サイト:http://www.jcraft.com/jsch/



-------------------------------------------------- -------------------------------------------------- ------------------------------





次に、デモを実装します

1.ツール:

  • USER:ログイン時の接続されたLinuxホストのユーザー名
  • パスワード:ログインパスワード
  • ホスト:ホストアドレス
  • 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...the desktop has an 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 ps -ef | grep java | awk '{print $2}' | xargs kill -9 nohup java -jar xxxx-0.0.1-SNAPSHOT.jar & ', 'utf-8') //Restart the database //String res = sshUtil.runShell('docken restart JY_mysql ', 'utf-8') //String res = sshUtil.runShell('nohup java -jar forlovehome-0.0.1-SNAPSHOT.jar & ', 'utf-8') // String res = sshUtil.runShell('/usr/apache-tomcat-7.0.47/bin/startup.sh ', 'utf-8') System.out.println(res) sshUtil.close() } }


参照:http://www.importnew.com/22322.html

http://www.jcraft.com/jsch/