轉載至: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/
注意: 該服務端需安裝在數據庫所在服務器