Java使用SSH远程访问Windows并执行命令
2019-12-10 09:07 在奋斗的菜鸟 阅读(2530) 评论(0) 编辑 收藏 举报
转载于:http://blog.csdn.net/carolzhang8406/article/details/6760430 https://blog.csdn.net/angel_xiaa/article/details/52355513 有关freeSSHd的用法写的很清楚
windows由于没有默认的ssh server,因此在允许ssh之前需要先安装ssh server。
下载freeSSHd
http://www.freesshd.com/?ctt=download
安装
直接执行freeSSHd.exe就可以进行安装了(用户一定要有管理员权限),安装过程中freeSSHd会问你
Private keys should be created. Should I do it now?
这是问你是否需要现在创建私钥,回答是
Do you want to run FreeSSHd as a system service?
这是问你是否希望把freeSSHd作为系统服务启动,回答是之后就安装完成了。
安装完成之后,双击freesshd图标(桌面或开始菜单),不会直接打开配置界面,而是需要在任务栏的“显示隐藏图标”(正三角图标)处右键freessh图标,选择setting。
配置用户名和密码:(java代码中连接的用户名和密码)
检查freesshd server status状态。切换至“server status”标签页,查看“SSH server is running”是否打钩,如果没有,点击下方连接检查,如果报错“the specified address is already in use”,则是由于安装时询问“Do you want to run FreeSSHd as a system service?”选择了“是”导致的,只需要在services.msc中将该服务停掉,再在配置界面启动,显示为打钩状态即可。或者在任务管理器-服务,停掉FreeSSHDService在点击启动服务
Java代码如下:
SSHWindows.java:
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SSHWindows {
private static final Logger log = LoggerFactory.getLogger(SSHWindows.class);
public static String SERVERIP = "192.168.27.209";
public static String SERVERUSERNAME = "admin";
public static String SERVERPWD = "12345678";
public static void execWinShell(String script){
try{
//建立连接
Connection conn= new Connection(SERVERIP);
log.info("set up connections");
conn.connect();
//利用用户名和密码进行授权
boolean isAuthenticated = conn.authenticateWithPassword(SERVERUSERNAME, SERVERPWD);
if(isAuthenticated ==false)
{
throw new IOException("Authorication failed");
}
//打开会话
Session sess = conn.openSession();
//执行命令
sess.execCommand(script);
log.info("The execute command output is:{}", script);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout,"gbk"));
while(true)
{
String line = br.readLine();
if(line==null) break;
log.info(line);
}
log.info("Exit code "+sess.getExitStatus());
sess.close();
conn.close();
log.info("Connection closed");
}catch(IOException e)
{
log.info("can not access the remote machine");
}
}
}
以上代码依赖于ssh2的jar包,pom.xml里配置依赖包
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>