前言:

  最近需要做一个功能,编写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;
}
}
 

 

    

  

posted on 2019-06-11 16:25  帅过驴的袋鼠  阅读(3953)  评论(0编辑  收藏  举报