使用java代碼鏈接到局域網的windows服務器並執行運行cmd命令行

前言:html

  最近須要作一個功能,編寫java代碼鏈接windows服務器並運行命令。在網上找了幾天,終於鏈接成功。找的過程太痛苦了,記錄一下給有須要的人使用。java

  使用一款叫作freeSSHd的軟件進行鏈接。將freeSSHd安裝到想要鏈接的目標服務器上(至關於java代碼是客戶端,freeSSHd是服務器)。windows

  PS,相關api的使用:http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.htmlapi

準備工做:服務器

  軟件下載地址:http://www.freesshd.com/?ctt=download,下載freeSSHd.exesession

開始安裝freeSSHd:app

  雙擊開始安裝,安裝過程當中會提示兩個選項ssh

    1.Private keys should be created. Should I do it now? this

    這是在詢問如今是否建立私鑰,選是。spa

    2.Do you want to run FreeSSHd as a system service?

    這是在詢問是否開啓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;    }}
相關文章
相關標籤/搜索