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

转载至:http://blog.csdn.net/carolzhang8406/article/details/6760430

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中将该服务停掉,再在配置界面启动,显示为打钩状态即可。


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/


猜你喜欢

转载自blog.csdn.net/angel_xiaa/article/details/52355513
今日推荐