Java使用SSH远程访问Windows并执行命令

转载自:Java使用SSH远程访问Windows并执行命令--博主angel_xiaa

这种方法只是一种,还有通过windows的telent,以及其他,不做介绍

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图标(桌面或开始菜单),不会直接打开配置界面,而是需要在任务栏的“显示隐藏图标”处右键freessh图标,选择setting。

添加用户


点击Users,点击add


填写内容之后,保存即可

开启服务
切换到Server status 菜单

开启这两个即可。
在开启SSH server的时候,如果报错提示“ the specified address is already in use
这是因为在安装的时候,“ Do you want to run FreeSSHd as a system service?”选择了“是”导致的,打开系统服务,
停掉FreeSSHService服务即可,然后返回setting面板,开启那两个即可
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;

public class SSHWindows {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 String hostname ="192.168.30.10";
	        String username="administrator";
	        String password="Talent123";
	        try{
	            //建立连接
	            Connection conn= new Connection(hostname);
	       //     System.out.println("set up connections");
	            conn.connect();
	            //利用用户名和密码进行授权
	            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
	            if(isAuthenticated ==false)
	            {
	       //     	System.out.println("--------");
	                throw new IOException("Authorication failed");
	            }
	            //打开会话
	            Session sess = conn.openSession();
	        //    System.out.println("cmd----");
	            //执行命令
	            sess.execCommand("ruby C:\\WhatWeb-master\\whatweb --output-xml http://216.139.147.75:443/");
	       //     System.out.println("The execute command output is:");
	            InputStream stdout = new StreamGobbler(sess.getStdout());
	            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
	            while(true)
	            {
	                String line = br.readLine();
	                if(line==null) break;
	                System.out.println(line);
	            }
	         //   System.out.println("Exit code "+sess.getExitStatus());
	            sess.close();
	            conn.close();
	       //     System.out.println("Connection closed");
	            
	        }catch(IOException e)
	        {
	            System.out.println("can not access the remote machine");
	        }
	    }


}



以上代码依赖于ssh2的jar包。下载地址:http://www.ganymed.ethz.ch/ssh2/




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值