轉載於: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>