Java利用 ganymed-ssh2-build.jar来上传文件到linux以及下载linux文件以及执行linux shell命令

Posted 入门到放弃

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java利用 ganymed-ssh2-build.jar来上传文件到linux以及下载linux文件以及执行linux shell命令相关的知识,希望对你有一定的参考价值。

package api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.*;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SshTest {
public static void main(String[] args) {
SshTest.exeCmd("df -m","root","123456","192.168.229.128", 22);
}

private static Logger logger = Logger.getLogger(SshTest.class);
public static Connection getConnect(String user,String password ,String ip,int port ) {
Connection conn=new Connection(ip, port);
try {

conn.connect();
conn.authenticateWithPassword(user, password);
logger.error("ssh连接ok");
logger.info("hhhhhhhh");
}catch(Exception e) {
e.printStackTrace();
}
return conn;
}

public static String exeCmd(String cmd,String user,String password ,String ip,int port){
String line=null;
Connection connection=null;
Session session=null;
try {
connection=getConnect(user, password, ip, port);
session=connection.openSession();
session.execCommand(cmd);
InputStream in = new StreamGobbler(session.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(in));
line = brs.readLine();
// logger.info(line);
}catch(Exception e) {
e.printStackTrace();
}finally {
session.close();
connection.close();
}
return line;
}
// downLoadFile from Linux
public static boolean sftpDownload(String remoteFilePath,String localFilePath,String user,String password ,String ip,int port) {
boolean bool=false;
Connection connection=null;
try {
connection=getConnect(user, password, ip, port);
SCPClient scpClient = connection.createSCPClient();
scpClient.put(localFilePath, remoteFilePath);
bool=true;
}catch(IOException ioe) {
ioe.printStackTrace();
bool =false;
}finally {
connection.close();
}
return bool;
}

// uploadFile to Linux
public static boolean uoloadFile(String remoteFilePath,String localFilePath,String user,String password ,String ip,int port) {
boolean bool=false;
Connection connection=null;
try {
connection=getConnect(user, password, ip, port);
SCPClient scpClient = connection.createSCPClient();
scpClient.get(remoteFilePath, localFilePath);
bool=true;
}catch(IOException ioe) {
ioe.printStackTrace();
bool =false;
}finally {
connection.close();
}
return bool;
}

}

 

  

以上是关于Java利用 ganymed-ssh2-build.jar来上传文件到linux以及下载linux文件以及执行linux shell命令的主要内容,如果未能解决你的问题,请参考以下文章

Java连接Linux服务器

使用ganymed工具调用ssh2

使用ganymed-ssh2连接linux报错Cannot negotiate, proposals do not match.

使用JAVA执行shell

使用JAVA执行shell

Java 执行远程主机shell命令代码