前言:
最近需要做一個功能,編寫java代碼連接windows服務器並運行命令。在網上找了幾天,終於連接成功。找的過程太痛苦了,記錄一下給有需要的人使用。
使用一款叫做freeSSHd的軟件進行連接。將freeSSHd安裝到想要連接的目標服務器上(相當於java代碼是客戶端,freeSSHd是服務器)。
PS,相關api的使用:http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.html
准備工作:
軟件下載地址:http://www.freesshd.com/?ctt=download,下載freeSSHd.exe
開始安裝freeSSHd:
雙擊開始安裝,安裝過程中會提示兩個選項
1.Private keys should be created. Should I do it now?
這是在詢問現在是否創建私鑰,選是。
2.Do you want to run FreeSSHd as a system service?
這是在詢問是否開啟freeSSHd服務,選是。
freeSSHd配置:
雙擊桌面上的freeSSHd或者從開始菜單欄傷的freeSSHd並不會打開軟件,這是因為軟件已經啟動並隱藏在右下角處。
在桌面右下角右擊freeSSHdService,選擇settings進行配置。
1.首先配置Server status
找到Server status選項卡,SSH server is running. 默認是紅叉,點擊下方 Click here to start it.啟動服務,紅叉會變成綠勾
如果沒有變成綠勾,並報錯“the specified address is already in use”,這是因為服務在上面已經開啟,需要關閉。win + r 輸入services.msc 找到freeSShd的服務關閉,
關閉之后重啟點擊Click here to start it啟動服務,這時候發現服務已經啟動。
2.配置用戶
找到Users選項卡,點擊add添加一個用戶
第二欄authorization選項選擇 Password stored as SHA1 hash,接着輸入用戶名和密碼。之后確定
3.配置端口
找到SSH選項卡 listen address:監聽的地址 port:監聽的端口 max number of connections:最大連接數
自行配置,端口號默認22盡量不要修改
代碼結構:
第一種連接方式,需要借助Ganymed SSH的jar包
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
代碼如下
package ssh;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SSH_Ganymed {
public static void main(String[] args) {
// 服務器ip
String ipv4Address = "1.1.1.1";
// freeSshd設置的連接端口
int port = 22;
String freeSshdUserName = "username";
String freeSshdUserPassword = "password";
// 在cmd中執行的命令
String command = "java -version";
connectServer(ipv4Address, port, freeSshdUserName, freeSshdUserPassword, command);
}
public static void connectServer(String ipv4Address, int port, String freeSshdUserName, String freeSshdUserpassword, String command) {
Connection conn = new Connection(ipv4Address, port);
Session session = null;
try {
conn.connect();
// login
boolean isLogin = conn.authenticateWithPassword(freeSshdUserName, freeSshdUserpassword);
if (isLogin) {
System.out.println("login success");
} else {
System.out.println("login failed");
}
Session openSession = conn.openSession();
openSession.execCommand(command);
InputStream is = new StreamGobbler(openSession.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
}
}
}
第二種連接方式,需要借助JSch的包
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
代碼如下
package ssh;
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class SSH_JSch {
private static JSch jSch;
private static Session session;
private String freesshdIpFour;
private int freesshdPort;
private String freesshdUsername;
private String freesshdPassword;
private String command;
public SSH_JSch(String freesshdIpFour, int freesshdPort, String freesshdUsername, String freesshdPassword, String command) {
this.freesshdIpFour = freesshdIpFour;
this.freesshdPort = freesshdPort;
this.freesshdUsername = freesshdUsername;
this.freesshdPassword = freesshdPassword;
this.command = command;
}
public String connectServer() {
// 創建JSch對象
jSch = new JSch();
BufferedReader reader = null;
Channel channel = null;
try {
session = jSch.getSession(freesshdUsername, freesshdIpFour, freesshdPort);
session.setPassword(freesshdPassword);
Properties config = new Properties();
session.setTimeout(1500);
session.connect();
if (command != null) {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.connect();
InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in, "GBK"));
String buf;
StringBuffer sb = new StringBuffer();
while ((buf = reader.readLine()) != null) {
sb = sb.append(buf);
}
return sb.toString();
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
session.disconnect();
if (channel != null) {
channel.disconnect();
}
}
return null;
}
}