java通过代码登录远程linux服务器并执行linux命令shell脚本

9 篇文章 0 订阅
5 篇文章 0 订阅
package com.snailxr.helper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * SSH工具类
 * @author 王建国
 * 2019-12-29
 */
public class SSHHelper {

    /**
     * 远程 执行命令并返回结果调用过程 是同步的(执行完才会返回)
     * @param host  主机名
     * @param user  用户名
     * @param psw   密码
     * @param port  端口
     * @param command   命令
     * @return
     */
    public static String exec(String host,String user,String psw,int port,String command){
        String result="";
        Session session =null;
        ChannelExec openChannel =null;
        try {
            JSch jsch=new JSch();
            session = jsch.getSession(user, host, port);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setPassword(psw);
            session.connect();
            openChannel = (ChannelExec) session.openChannel("exec");
            openChannel.setCommand(command);
            int exitStatus = openChannel.getExitStatus();
            System.out.println(exitStatus);
            openChannel.connect();  
            InputStream in = openChannel.getInputStream();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
            String buf = null;
            while ((buf = reader.readLine()) != null) {
                result+= new String(buf.getBytes("gbk"),"UTF-8")+"    <br>\r\n";  
            }  
        } catch (Exception e) {
            result+=e.getMessage();
        }finally{
            if(openChannel!=null&&!openChannel.isClosed()){
                openChannel.disconnect();
            }
            if(session!=null&&session.isConnected()){
                session.disconnect();
            }
        }
        return result;
    }



    public static void main(String args[]){
        String exec = exec("127.0.0.1", "root", "root", 3306, "uname -a && date && uptime && who");
        System.out.println(exec);   
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要通过Java 1.8连接Linux服务器执行shell脚本,可以使用Java的SSH库,如JSch。下面是一种可能的实现方式: 首先,你需要在你的Java项目中导入JSch库。你可以在Maven中添加以下依赖项: ```xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> ``` 然后,你需要使用JSch创建一个SSH会话并连接到远程服务器。以下是一个简单的示例代码: ```java import com.jcraft.jsch.*; public class SSHExample { public static void main(String[] args) { String host = "your_host"; int port = 22; String username = "your_username"; String password = "your_password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(username, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand("your_shell_command"); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); // 读取命令输出 byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,你需要将"your_host"替换为远程服务器的IP地址或域名,"your_username"和"your_password"替换为你的用户名和密码。然后,将"your_shell_command"替换为你想要在远程服务器执行的shell命令。 此代码将连接到远程服务器执行shell命令并打印输出流中的结果。你还可以根据需要进行进一步的修改和扩展。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值