java ssh 远程执行_Ganymed SSH-2 java实现远程连接服务器并执行命令的方法(Windows和Linux)...

java实现连接远程服务器并执行命令的基本原理

一、所需jar包

需要借助Ganymed SSH的jar包:  ganymed-ssh2-build210.jar

二、实现原理

Ganymed SSH-2 java在整个访问过程中担当SSH的客户端,由于Linux系统自带SSH服务,所以可以直接访问Linux系统并执行相关命令,而 Windows系统则需要首先安装SSH服务。

三、Win下SSH服务的安装配置

当远程服务器为Windows系统时, 需要在远程服务器中安装Windows版的SSH服务,比如:freesshd。

1.安装完freesshd后,首选在[Users]下添加用来远程连接的win系统用户,此处采用密码认证的方式,允许使用shell:

a37d4b1ed2ed8d351df53299bcd75cd6.png

2.然后再在【Authentication】下设置允许密码认证方式:

c6fbafa24f6e43a3c579eecc32cfa738.png

3.到[Server status]下查看SSH服务器状态,确保启动即可。最后点击【确定】即可。

a319f002f7fe49684f58970a77c8bbad.png

四、java代码实现远程连接服务器并执行命令

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package test;

import java.io.IOException;

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

/*

@author: Liu Yuanyuan

purpose: test connecting remote computer and execute linux command

*/

public class TestRemoteConnect

{

public static void main(String[] args)

{

String hostname = "192.168.100.50";

int port = 22;//22 usually the default port

String username = "root";

String password = "highgo";

//指明连接主机的IP地址

Connection conn = new Connection(hostname,port);

Session ssh = null;

try

{

//连接到主机

conn.connect();

//使用用户名和密码校验

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

if (!isconn)

{

System.out.println("用户名称或者是密码不正确");

}

else

{

System.out.println("已经连接OK");

//以下是linux的示例

//将本地conf/server_start.sh传输到远程主机的/opt/pg944/目录下

SCPClient clt = conn.createSCPClient();

clt.put("conf/server_start.sh", "/opt/pg944/");

//执行命令

ssh = conn.openSession();

ssh.execCommand("sh /root/hello.sh");

//ssh.execCommand("perl /root/hello.pl");

//只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常.

//使用多个命令用分号隔开

//ssh.execCommand("cd /root; sh hello.sh");

/* 执行windows系统命令的示例

Session sess = conn.openSession();

sess.execCommand("ipconfig");

*/

//将Terminal屏幕上的文字全部打印出来

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

}

}

}

catch (IOException e)

{

System.out.println(e.getMessage());

e.printStackTrace();

}

finally

{

//连接的Session和Connection对象都需要关闭

if(ssh!=null)

{

ssh.close();

}

if(conn!=null)

{

conn.close();

}

}

}

}

五、其他的实现方式:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值