java代码远程连接Linux 命令操作 上传文件

 记录一下

package com.ri.web.controller.system;


import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Properties;

/**
 * 测试模拟接口 /api
 */
@RestController
@RequestMapping("/setFile")
@CrossOrigin(origins = "*")
public class FileController {
    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

    private String charset = Charset.defaultCharset().toString();
    private static final int TIME_OUT = 1000 * 5 * 60;
 

    /**
     *    远程linux
     * */
    @PostMapping("/remote")
    @ResponseBody
    public AjaxResult remote(String ip, String username, String password, String cmd)
    {
        try {
            HashMap<String, String> exec = new FileController().exec(ip, username, password, cmd);
            String outStr = exec.get("outStr");
            String outErr = exec.get("outErr");
            if(outErr.length()!=0){
                return AjaxResult.error(outErr);
            }
            else if(outErr.length()==0&&outStr.length()!=0){
                return AjaxResult.success(true,"操作成功",outStr,null);
            }
            else if(outErr.length()==0&&outStr.length()==0){
                return AjaxResult.success(true,"操作成功",null,null);
            }
            else{
                return AjaxResult.error(outErr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  AjaxResult.error("执行有异常!");// 如果有异常
        }
    }
    /**
     *    远程linux上传文件/图片
     *    fileName命名  fileLocalUrl本地文件路径  fileurl将要保存到路径
     * */
    @PostMapping("/remoteUpload")
    @ResponseBody
    public AjaxResult remoteUpload(String ip, String username, String password, String fileName,String fileLocalUrl,String fileurl)
    {
        int port = 22;
        try {
            InputStream is = new FileInputStream(new File(fileLocalUrl));
            JSch jsch = new JSch();
            jsch.getSession(username, ip, port);
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, ip, port);
            LOG.info("创建Session……");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            LOG.info("连接Session……");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            LOG.info("连接Channel……");
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.cd(fileurl);//上传时接文件的服务器的存放目录
//            sftp.cd("yyl0971");
            sftp.put(is, fileName, ChannelSftp.OVERWRITE);//有重名文件覆盖
            sshSession.disconnect();
            is.close();
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 将内容写入到文本文件 string to file
     */
    @PostMapping("/stringToFile")
    @ResponseBody
    public AjaxResult stringToFile(String content,String url){
        //在写入文件时,若没有找到目标文件,则会创建一个
        /**写入txt文件*/
        File writename = new File(url); //绝对路径 
        BufferedWriter out = null;
        try {
            writename.createNewFile(); // 创建新文件
            out = new BufferedWriter(new FileWriter(writename));
            out.write(content);
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 关闭输出
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件输入错误");
        }
        return AjaxResult.success();
    }
    /**
     * 读取文本文件的内容
     */
    @PostMapping("/readFileToString")
    @ResponseBody
    public AjaxResult readFileToString(String url) throws IOException {
        String content = "";
        FileInputStream fin = new FileInputStream(url);
        InputStreamReader reader = new InputStreamReader(fin);
        BufferedReader buffReader = new BufferedReader(reader);
        String strTmp = "";
        while((strTmp = buffReader.readLine())!=null){
            content+=strTmp;
            content+="\r\n";
        }
        System.out.println("返回内容:"+content);
        buffReader.close();
        return AjaxResult.success(true,"操作成功",content,null);
    }



    /**
     *    远程linux
     * */
    @PostMapping("/remote1")
    @ResponseBody
    public AjaxResult remote1(String ip, String username, String password, String cmd)
    {
        try {
            Connection conn = new  Connection(ip, 22);// 创建连接
            conn.connect ();// 启动连接
            // 验证用户密码
            boolean b = conn.authenticateWithPassword(username, password);
            if(!b){
                return  AjaxResult.error("账号或密码错误!");
            }else {
                System.out.println("------------------------已经连接------------------------");
                Session session = conn.openSession();
                session.execCommand ( cmd );//执行命令
                InputStream is = new StreamGobbler(session.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                StringBuffer buffer = new StringBuffer();
                String line;
                while ((line = br.readLine ()) != null) {
                    buffer.append ( line + "\n" );
                }
                String result = buffer.toString ();
                session.close ();
                conn.close ();
                System.out.println("内容:"+result);
                //如果没有异常,返回结果为命令执行结果
                if(result.length()>0){
                    return AjaxResult.success(true,"操作成功",result,null);
                }
                else {
                    return  AjaxResult.error("执行命令错误!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  AjaxResult.error("执行有异常!");// 如果有异常
        }
    }

 
    private String processStream(InputStream in, String charset) throws IOException {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }
    public HashMap<String, String> exec(String ip, String username, String password, String cmds) throws IOException {
        HashMap<String, String> result = new HashMap<String,String>();
        Connection conn = null;
        InputStream is = null;
        InputStream stdErr = null;
        String outStr = "";
        String outErr = "";
        int ret = -1;
        try {
            conn = new Connection(ip);
            conn.connect();
            boolean b = conn.authenticateWithPassword(username, password);
            if (b) {
                Session session = conn.openSession();
                session.execCommand(cmds);
                is = new StreamGobbler(session.getStdout());
                outStr = processStream(is, charset);
                LOG.info("caijl:[INFO] outStr=" + outStr);
                result.put("outStr",outStr);

                stdErr = new StreamGobbler(session.getStderr());
                outErr = processStream(stdErr, charset);
                LOG.info("caijl:[INFO] outErr=" + outErr);
                result.put("outErr",outErr);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                ret = session.getExitStatus();

            } else {
                LOG.error("caijl:[INFO] ssh2 login failure:" + ip);
                throw new IOException("SSH2_ERR");
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (is != null)
                is.close();
            if (stdErr != null)
                stdErr.close();
        }
        return result;
    }


    public static String resolveCode(String path) throws Exception {
        InputStream inputStream = new FileInputStream(path);
        byte[] head = new byte[3];
        inputStream.read(head);
        String code = "gb2312";  //或GBK
        if (head[0] == -1 && head[1] == -2 )
            code = "UTF-16";
        else if (head[0] == -2 && head[1] == -1 )
            code = "Unicode";
        else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
            code = "UTF-8";
        inputStream.close();
        return code;
    }

     
    

}

需要的包:

<dependency>
      <groupId>ch.ethz.ganymed</groupId>
       <artifactId>ganymed-ssh2</artifactId>
       <version>262</version>
</dependency>

<dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.54</version>
</dependency>

<dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
</dependency>

启动项目可能报的错:

 重新下载,clean,install 项目重构,电脑重启。 该尝试的办法都试了, 还是不行的话,可能是jar下载不完整,可以手动下载包,用到项目里,

方法1:看别人是怎么解决的,我用了依旧报错,

右击项目,点Open Module Settings

 点左边的Libraries,看右边Classes下面有没有爆红的,有的话删掉

然后点左边的Modules,看ModuleSDK哪里有没有问题

再不行试试方法2  

方法2:自己瞎琢磨出来的,

在这里搜索需要的包下载

https://mvnrepository.com/

 选版本

点jar包下载

 在项目src文件夹同一级建lib文件夹,把jar包丢进去 在pom.xml里面引用

 

 主要怕自己以后忘记了,记录一下bug 方便,如有不对之处,请各位大神多多指点


版权声明:本文为CSDN博主「谁喝了我的幽兰拿铁」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/yaoyulan21/article/details/120182749

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值