1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java 连接远程服务器_java实现连接远程服务器并执行命令的基本原理

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

时间:2019-08-05 06:58:45

相关推荐

java 连接远程服务器_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:

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

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

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

/*

*Tochangethislicenseheader,chooseLicenseHeadersinProjectProperties.

*Tochangethistemplatefile,chooseTools|Templates

*andopenthetemplateintheeditor.

*/

packagetest;

importjava.io.IOException;

importch.ethz.ssh2.Connection;

importch.ethz.ssh2.Session;

importch.ethz.ssh2.StreamGobbler; importjava.io.BufferedReader; importjava.io.InputStream; importjava.io.InputStreamReader; /* @author:LiuYuanyuan purpose:testconnectingremotecomputerandexecutelinuxcommand */ publicclassTestRemoteConnect { publicstaticvoidmain(String[]args) { Stringhostname="192.168.100.50"; intport=22;//22usuallythedefaultport Stringusername="root"; Stringpassword="highgo"; //指明连接主机的IP地址 Connectionconn=newConnection(hostname,port); Sessionssh=null; try { //连接到主机 conn.connect(); //使用用户名和密码校验 booleanisconn=conn.authenticateWithPassword(username,password); if(!isconn) { System.out.println("用户名称或者是密码不正确"); } else { System.out.println("已经连接OK"); //以下是linux的示例 //将本地conf/server_start.sh传输到远程主机的/opt/pg944/目录下 SCPClientclt=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;shhello.sh"); /*执行windows系统命令的示例 Sessionsess=conn.openSession(); sess.execCommand("ipconfig"); */ //将Terminal屏幕上的文字全部打印出来 InputStreamis=newStreamGobbler(ssh.getStdout()); BufferedReaderbrs=newBufferedReader(newInputStreamReader(is)); while(true) { Stringline=brs.readLine(); if(line==null) { break; } System.out.println(line); } } } catch(IOExceptione) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { //连接的Session和Connection对象都需要关闭 if(ssh!=null) { ssh.close(); } if(conn!=null) { conn.close(); } } } }

五、其他的实现方式:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。