码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-03-16 00:29:11      阅读:605      评论:0      收藏:0      [点我收藏+]

标签:org   cli   public   catch   lse   ade   inpu   stream   close   

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命令

标签:org   cli   public   catch   lse   ade   inpu   stream   close   

原文地址:https://www.cnblogs.com/SunshineKimi/p/10540276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!