Skip to main content

Connect to Linux via Java and Execute Scripts or Commands

package run.runnable.XShell;

import ch.ethz.ssh2.*;

import javax.swing.*;
import java.io.*;

public class ConnectLinuxCommand {


private static String DEFAULTCHARTSET = "UTF-8";
private static Connection conn;

/**
*
* @Title: login
* @Description: Remote login to Linux server using username and password
* @return: Boolean
* @throws
*/
public static Boolean login(RemoteConnect remoteConnect) {
boolean flag = false;
try {
conn = new Connection(remoteConnect.getIp());
conn.connect();// Connect
flag = conn.authenticateWithPassword(remoteConnect.getUserName(), remoteConnect.getPassword());// Authenticate
if (flag) {
System.out.println("Authentication successful!");
} else {
System.out.println("Authentication failed!");
conn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}

public static void main(String[] args) {
RemoteConnect remoteConnect = new RemoteConnect("","root","");
Boolean login = login(remoteConnect);
if (login){
System.out.println("Login successful");
}
execute("mkdir /etc/fffffffffff");


}
/**
*
* @Title: loginByKey
* @Description: Remote login to Linux server using key file
* @param remoteConnect
* @param keyFile A file object pointing to a file containing the user's DSA or RSA private key in OpenSSH key format (PEM, cannot lose "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----" tags)
* @param keyfilePass If the key file is encrypted, this parameter is needed for decryption; can be null if not encrypted
* @return Boolean
* @throws
*/
public static Boolean loginByFileKey(RemoteConnect remoteConnect, File keyFile, String keyfilePass) {
boolean flag = false;
// Enter the path where the key is located
// File keyfile = new File("C:\\temp\\private");
try {
conn = new Connection(remoteConnect.getIp());
conn.connect();
// Login authentication
flag = conn.authenticateWithPublicKey(remoteConnect.getUserName(), keyFile, keyfilePass);
if (flag) {
System.out.println("Authentication successful!");
} else {
System.out.println("Authentication failed!");
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}

/**
*
* @Title: loginByCharsKey
* @Description: Remote login to Linux server using key characters
* @param remoteConnect
* @param keys A char[] containing the user's DSA or RSA private key (OpenSSH key format, you cannot lose "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----" tags). The char array can contain newline characters.
* @param keyPass If the key character array is encrypted, this field is needed for decryption; otherwise can be null
* @return Boolean
* @throws
*/
public static Boolean loginByCharsKey(RemoteConnect remoteConnect, char[] keys, String keyPass) {

boolean flag = false;
// Enter the path where the key is located
// File keyfile = new File("C:\\temp\\private");
try {
conn = new Connection(remoteConnect.getIp());
conn.connect();
// Login authentication
flag = conn.authenticateWithPublicKey(remoteConnect.getUserName(), keys, keyPass);
if (flag) {
System.out.println("Authentication successful!");
} else {
System.out.println("Authentication failed!");
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
*
* @Title: execute
* @Description: Remotely execute shell script or command
* @param cmd Script command
* @return: result Result returned after command execution
* @throws
*/
public static String execute(String cmd){
String result = "";
try {
Session session = conn.openSession();// Open a session
session.execCommand(cmd);// Execute command
result = processStdout(session.getStdout(), DEFAULTCHARTSET);
// If standard output is empty, the script execution failed
if (result==null||result.equalsIgnoreCase("")) {
result = processStdout(session.getStderr(), DEFAULTCHARTSET);
}
conn.close();
session.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @Title: executeSuccess
* @Description: Remotely execute shell script or command @param shell Script or command
*
* @return String Result returned after successful command execution; returns empty string (not null) if command fails
* @throws
*/
public static String executeSuccess(String cmd){
String result = "";
try {
Session session = conn.openSession();// Open a session
session.execCommand(cmd);// Execute command
result = processStdout(session.getStdout(), DEFAULTCHARTSET);
conn.close();
session.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
*
* @Title: processStdout
* @Description: Parse the return result of script execution
* @param in Input stream object
* @param charset Encoding
* @return String Returns in plain text format
* @throws
*/
public static String processStdout(InputStream in, String charset){
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line + "\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}

/**
*
* @Title: ConnectLinux
* @Description: Connect to Linux server using username and password
* @return
* @return String
* @throws
*/
public static boolean connectLinux(String ip,String userName,String password,String commandStr) {

System.out.println("ConnectLinuxCommand scpGet===" + "ip:" + ip + " userName:" + userName + " commandStr:"
+ commandStr);

String returnStr = "";
boolean result = true;

RemoteConnect remoteConnect = new RemoteConnect();
remoteConnect.setIp(ip);
remoteConnect.setUserName(userName);
remoteConnect.setPassword(password);
try {
if (login(remoteConnect)) {
returnStr = execute(commandStr);
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}

if (returnStr==null||returnStr.equals("")) {
result = false;
}
return result;
}
/**
*
* @Title: scpGet
* @Description: Get file from another server to local server's specified directory
* @ host ip (other server)
* @ username Username (other server)
* @param password Password (other server)
* @param remoteFile File location (other server)
* @param localDir Local server directory
* @throws IOException
* @return void
* @throws
*/
public static void scpGet(String ip, String userName, String password, String remoteFile, String localDir)
throws IOException {

System.out.println("ConnectLinuxCommand scpGet===" + "ip:" + ip + " userName:" + userName + " remoteFile:"
+ remoteFile + " localDir:" + localDir);
RemoteConnect remoteConnect = new RemoteConnect();
remoteConnect.setIp(ip);
remoteConnect.setUserName(userName);
remoteConnect.setPassword(password);

if (login(remoteConnect)) {
SCPClient client = new SCPClient(conn);
client.get(remoteFile);
conn.close();
}
}
/**
*
* @Title: scpPut
* @Description: Copy file to another computer
* @param password
* @param localFile
* @param remoteDir
* @throws IOException
* @return void
* @throws
*/
public static void scpPut(String ip, String userName, String password, String localFile, String remoteDir)
throws IOException {
System.out.println("ConnectLinuxCommand scpPut===" + "ip:" + ip + " userName:" + userName + " localFile:"
+ localFile + " remoteDir:" + remoteDir);

RemoteConnect remoteConnect = new RemoteConnect();
remoteConnect.setIp(ip);
remoteConnect.setUserName(userName);
remoteConnect.setPassword(password);

if (login(remoteConnect)) {
SCPClient client = new SCPClient(conn);
// SCPOutputStream put = client.put(localFile, remoteDir);
conn.close();
}
}


}