java通过ssh远程调用服务器

1.在大数据时代,服务器使用的频率难免上升,工作中难免会出现频繁使用的时候,有些场景不方便切换到服务器去操作,比如调用一个服务器的命令,但是要在程序里执行,当然不能手动去执行啦,所以java调用ssh就尤为重要。

首先,添加maven依赖
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>1.8.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>

上一段demo

 

package quartz;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

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

/**
 * @Author: Monkey
 * @Date: Created in 14:15  2016/4/16.
 * @Description: Test SSH
 */
public class TestSSH {

    /**
     * Run SSH command.
     * @param host
     * @param username
     * @param password
     * @param cmd
     * @return exit status
     * @throws IOException
     */
    public static int runSSH(String host, String username, String password,
                             String cmd) throws IOException {
        System.out.println("running SSH cmd [" + cmd + "]");

        Connection conn = getOpenedConnection(host, username, password);
        Session sess = conn.openSession();
        sess.execCommand(cmd);

        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

        while (true) {
            String line = br.readLine();
            if (line == null){
                break;
            }
            System.out.println(line);
        }

        sess.close();
        conn.close();
        return sess.getExitStatus().intValue();
    }
    /**
     * return a opened Connection
     * @param host
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    private static Connection getOpenedConnection(String host, String username,
                                                  String password) throws IOException {

        System.out.println("connecting to " + host + " with user " + username
                + " and pwd " + password);
        //添加SSH连接端口,默认22
        Connection conn = new Connection(host, 22);
        conn.connect(); // make sure the connection is opened
        boolean isAuthenticated = conn.authenticateWithPassword(username,
                password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        return conn;
    }

    public static void main(String[] args) throws Exception{
        String cmd = "mkdir -p /home/1.txt";
        runSSH("10.0.43.106", "root", "monkey", cmd);
    }


}

当然,服务器要开放22端口才行,正常情况下都是开启了的。然后就看到了对应的文件已经生成了。

要在Java调用远程服务器的Shell脚本,可以使用Java的Runtime类的exec()方法。这个方法可以让你在Java程序中执行命令。具体步骤如下: 1. 首先,确保你已经在本地和远程服务器上安装了Java环境和SSH服务。 2. 在Java程序中,使用Runtime.getRuntime().exec()方法来执行远程服务器上的Shell命令。你需要提供SSH连接的用户名、密码和远程服务器的IP地址。 3. 在exec()方法中,可以使用ssh命令来连接远程服务器,并执行相应的Shell脚本。例如,你可以使用以下命令: ``` Runtime.getRuntime().exec("ssh username@remote_server_ip 'sh /path/to/remote_script.sh'"); ``` 这个命令将使用ssh连接远程服务器,然后执行远程服务器上的Shell脚本。 需要注意的是,你需要替换命令中的"username"为你的SSH用户名,"remote_server_ip"为远程服务器的IP地址,以及"/path/to/remote_script.sh"为远程服务器上Shell脚本的路径。 此外,你还可以使用SSH密钥对来进行认证,以增加安全性。详细的使用方法可以参考引用和引用所提供的链接。 希望这个回答可以帮到你。如果你还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java代码 调用远程服务器中的Shell脚本。](https://blog.csdn.net/u010797364/article/details/109256790)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值