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

java(jsp)执行ssh命令 在远程执行shell命令 博客分类: javaLinux javajspssh远程shell 

程序员文章站 2024-03-09 17:30:59
...

以下两种方法可以指定 主机地址,用户名,密码,端口号(port) 

本机是windows,也可以连接的远程linux执行shell命令

如远程重启另一台weblogic

1.查看进程号

2.kill -9 进程号

3.启动weblogic

 

可能会存在open files的问题(如果过堡垒机的也要设置好)

linux修改最大文件链接数open files
http://happyqing.iteye.com/blog/1953563

 

第一种 Ganymed SSH-2 for Java

据说Ganymed比jsch强大,能写出一些高级的东西

下载地址

http://www.ganymed.ethz.ch/ssh2/

ganymed-ssh2-build210.zip 包中有样例

 

样例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Basic
{
	public static void main(String[] args)
	{
		String hostname = "127.0.0.1";
		String username = "joe";
		String password = "joespass";

		try
		{
			/* Create a connection instance */

			Connection conn = new Connection(hostname, 22);

			/* Now connect */

			conn.connect();

			/* Authenticate.
			 * If you get an IOException saying something like
			 * "Authentication method password not supported by the server at this stage."
			 * then please check the FAQ.
			 */

			boolean isAuthenticated = conn.authenticateWithPassword(username, password);

			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");

			/* Create a session */

			Session sess = conn.openSession();

			sess.execCommand("uname -a && date && uptime && who");

			System.out.println("Here is some information about the remote host:");

			/* 
			 * This basic example does not handle stderr, which is sometimes dangerous
			 * (please read the FAQ).
			 */

			InputStream stdout = new StreamGobbler(sess.getStdout());

			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

			while (true)
			{
				String line = br.readLine();
				if (line == null)
					break;
				System.out.println(line);
			}

			/* Show exit status, if available (otherwise "null") */

			System.out.println("ExitCode: " + sess.getExitStatus());

			/* Close this session */

			sess.close();

			/* Close the connection */

			conn.close();

		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
	}
}

 Connection conn = new Connection(hostname, 22);
在第二个参数可设置端口(port)

用Ganymed,不用设置什么加密算法,似乎也不用保存主机秘钥。

 

第二种 jsch

下载地址

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

com.jcraft.jsch 所需jar包

jsch-0.1.53.zip

jsch-0.1.53.jar

 

样例

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

 

网摘样例

package com.codeconch.ssh;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

/**
 * SSH工具类
 * @author 赵聪慧
 * 2013-4-7
 */
public class SSHHelper {
  
  /**
   * 远程 执行命令并返回结果调用过程 是同步的(执行完才会返回)
   * @param host	主机名
   * @param user	用户名
   * @param psw	密码
   * @param port	端口
   * @param command	命令
   * @return
   */
  public static String exec(String host,String user,String psw,int port,String command){
    String result="";
    Session session =null;
    ChannelExec openChannel =null;
    try {
      JSch jsch=new JSch();
      session = jsch.getSession(user, host, port);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.setPassword(psw);
      session.connect();
      openChannel = (ChannelExec) session.openChannel("exec");
      openChannel.setCommand(command);
      int exitStatus = openChannel.getExitStatus();
      System.out.println(exitStatus);
      openChannel.connect();  
            InputStream in = openChannel.getInputStream();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
            String buf = null;
            while ((buf = reader.readLine()) != null) {
            	result+= new String(buf.getBytes("gbk"),"UTF-8")+"    <br>\r\n";  
            }  
    } catch (JSchException | IOException e) {
      result+=e.getMessage();
    }finally{
      if(openChannel!=null&&!openChannel.isClosed()){
        openChannel.disconnect();
      }
      if(session!=null&&session.isConnected()){
        session.disconnect();
      }
    }
    return result;
  }
  
  
  
  public static void main(String args[]){
    String exec = exec("192.168.1.254", "root", "123456", 22, "sleep 20;ls;");
    System.out.println(exec);	
  }
}

 

看起来挺简单的,

貌似是在redhat6.7及以后有加密算法的问题,需要在目标机做配置,

Algorithm negotiation fail
com.jcraft.jsch.JSchException: Algorithm negotiation fail 
at com.jcraft.jsch.Session.receive_kexinit(Session.java:520) 
at com.jcraft.jsch.Session.connect(Session.java:286) 
at com.jcraft.jsch.Session.connect(Session.java:150) 

 使用Ganymed SSH-2 for Java则不存在此问题