Remote execute command in Java example

  sonic0002        2014-12-12 03:20:19       46,569        11          English  简体中文  繁体中文  ภาษาไทย  Tiếng Việt 

經常需要登入遠端系統並執行一些命令或程式以取得輸出,許多軟體可以達到此目的,例如 putty 和 gitshell。這些軟體通常提供對遠端系統的安全存取。但是,您是否曾經想過,如果您需要同時在許多不同的系統上執行命令並將所有這些結果返回到單一位置,該怎麼辦?尤其在大數據時代,許多任務可能在不同的分散式系統上執行,而您希望有一個單一位置來累積結果。

在這篇文章中,我們將介紹一個可以幫助實現此目標的 Java 函式庫 -- JSch。它是一個純 Java 實現的 SSH2。JSch 允許您連接到 sshd 伺服器並使用端口轉發、X11 轉發、檔案傳輸等,您可以將其功能整合到您自己的 Java 程式中。

使用它的好處是您可以以程式方式連接到移除伺服器並在那裡執行一些命令,而無需實際登入。以下是如何在遠端 Linux 伺服器上執行ls -la 的範例。

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

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


public class JSchTest {
	public static void main(String[] args){
		try{
			String command = "ls -la";
			String host = "host_ip";
			String user = "username";
			String password = "password";
			
			JSch jsch = new JSch();
			Session session = jsch.getSession(user, host, 22);
			Properties config = new Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);;
			session.setPassword(password);
			session.connect();
			
			Channel channel = session.openChannel("exec");
			((ChannelExec)channel).setCommand(command);
			channel.setInputStream(null);
			((ChannelExec)channel).setErrStream(System.err);
			
			InputStream input = channel.getInputStream();
			channel.connect();
			
			System.out.println("Channel Connected to machine " + host + " server with command: " + command ); 
			
			try{
				InputStreamReader inputReader = new InputStreamReader(input);
				BufferedReader bufferedReader = new BufferedReader(inputReader);
				String line = null;
				
				while((line = bufferedReader.readLine()) != null){
					System.out.println(line);
				}
				bufferedReader.close();
				inputReader.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
			
			channel.disconnect();
			session.disconnect();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}

執行程式後,輸出為:

Channel Connected to machine hostname server with command: ls -la
total 1367872
drwxr-xr-x 33 peter users      4096 Dec 11 16:49 .
drwxr-xr-x  6 root  root       4096 Mar 21  2014 ..
-rw-------  1 peter users     15607 Dec 11 19:01 .bash_history
-rw-r--r--  1 peter users      1177 Mar 21  2014 .bashrc
drwxr-xr-x  2 peter users      4096 Sep 12 09:47 bin
drwxrwxrwx  2 peter users      4096 Sep  3 14:10 cfg

這相當方便。如果您想在兩個遠端系統上執行相同的命令,您只需要建立一個新的 Session 和 Channel 並執行相同的操作。

JSch 可以幫助執行更多操作,包括端口轉發、檔案傳輸等。

JSCH  EXAMPLE  DISTRIBUTED SYSTEM  SSH2 

       

  RELATED


  11 COMMENTS


Anonymous [Reply]@ 2017-08-06 23:10:19

Hey Sonic,

Great article. That is what i was looking for. Thanks

But i am getting a "com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect" error.

Any insights here?

Ke Pi [Reply]@ 2017-08-07 09:03:53

Apparently the error you are seeing is that remote end refuses the connection. Maybe the port is not accessible. Please make sure that you can telnet to the remote host at port 22.

Anonymous [Reply]@ 2018-05-14 04:30:51

Hi Sonic,

on a Windows server how can I connect? I can't use 22 port.

Thanks,

Sara

Ke Pi [Reply]@ 2018-05-14 10:00:39

What do you mean by you cannot use port 22? The port you should use depends on what port the SSHd service is listening at the other end. 

Venni [Reply]@ 2018-08-14 09:04:21

How can we execute multiple commands ?

Ke Pi [Reply]@ 2018-08-14 10:58:26

Can try to delimit the command with semicolon

Anonymous [Reply]@ 2019-12-09 04:01:37

After sending a command I get a prompt where I need to provide an user input. How can I do this?

Ke Pi [Reply]@ 2019-12-10 09:08:27

Ideally it should not prompt as you already put username. Out of curiosity, what prompt do you see? In your Java output?

Anonymous [Reply]@ 2019-12-10 10:05:50

It’s like an incident number where i need to give user input

Ke Pi [Reply]@ 2019-12-11 08:14:21

Maybe it's related to interactive mode of ssh? https://unix.stackexchange.com/questions/349425/ssh-command-and-non-interactive-non-login-shell

Prasun [Reply]@ 2020-06-07 02:56:40

i'm new to java.. just trying to creating ssh connection and execute the shell script which has pretty long output in console. How can we have handle such scenario. I see script code is getting hanged and not display the console output.



  RANDOM FUN

When codes are not saved