java远程执行linux命令

 

如何实现JAVA远程操控linux服务器,代码如下:

 

package hb.linux;

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 TestCtrCommond {

	public static void main(String[] args) {
		
		String hostname = "129.17.17.20";
		String username = "weblogic";
		String password = "weblogic";
		//指明连接主机的IP地址
		Connection conn = new Connection(hostname);
		Session ssh = null;
		try {
			//连接到主机
			conn.connect();
			//使用用户名和密码校验
			boolean isconn = conn.authenticateWithPassword(username, password);
			if(!isconn){
				System.out.println("用户名称或者是密码不正确");
			}else{
				System.out.println("已经连接OK");
				ssh = conn.openSession();
				//使用多个命令用分号隔开
//				ssh.execCommand("pwd;cd /tmp;mkdir hb;ls;ps -ef|grep weblogic");
				ssh.execCommand("cd /app/weblogic/Oracle/Middleware/user_projects/domains/base_domain;./startWebLogic.sh &");
				//只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常
//				ssh.execCommand("mkdir hb");
				//将屏幕上的文字全部打印出来
				InputStream  is = new StreamGobbler(ssh.getStdout());
				BufferedReader brs = new BufferedReader(new InputStreamReader(is));
				while(true){
					String line = brs.readLine();
					if(line==null){
						break;
					}
					System.out.println(line);
				}
				
			}
			//连接的Session和Connection对象都需要关闭
			ssh.close();
			conn.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

 

附件中有远程连接的SSH使用的jar包,还有相关的demo

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值