ganymed-ssh 执行脚本

问题: 发现 java 调用ganymed-ssh 执行某些shell 不成功,某些成功。

如下面通过SECURECRT 登录主机执行命令能启动JBOSS,但是用代码却不行。

java 代码如下

package com.tac.tool;

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 = "10.59.9.83";
		String username = "xxxx";
		String password = "xxxxxxxxx";

		try
		{
			/* Create a connection instance */

			Connection conn = new Connection(hostname);

			/* 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");
    	//    sess.execCommand("env");
			
			sess.execCommand("nohup /wls/jbossserver/jboss-as-7.1.1.Final/bin/standalone.sh >/dev/null 2>&1 &");

			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);
		}
	}
}


原因:调试发现两种登录方式的 环境变量不一样

分别在主机上执行 env 命令和在代码里执行

sess.execCommand("env");

解决方案:

  1. Define all your settings in the file ~/.bashrc

  2. Make sure that the file ~/.bash_profile only contains the line source ~/.bashrc.

  3. Before executing Session.execCommand(), do NOT aquire any type of pseudo terminal in the session. Be prepared to consume stdout and stderr data.

这是官网faq 给出的方案,实行后确实可以。

你可能感兴趣的:(ganymed-ssh 执行脚本)