zoukankan      html  css  js  c++  java
  • Java利用 ganymedssh2build.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;
    }

    }

     

      

  • 相关阅读:
    day3 数据类型
    子查询
    mysql综合练习题
    day5 练习
    月末总结
    Iconfont-阿里巴巴矢量图标库
    vue简介
    Redis简介和数据结构
    浏览器初始化css
    vue脚手架搭建项目初始化
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/10540276.html
Copyright © 2011-2022 走看看