Java SSH

不使用终端也能调用环境变量中的指令

类库的GitHub,https://github.com/hudson/ganymed-ssh-2
后续需要改造下代码,看看能不能更加的精简

依赖

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

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>

代码

package wiki.mysite.ssh2;

import java.io.*;
import java.nio.charset.Charset;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.io.IOUtils;

public class RemoteShellExecutor {

    private Connection conn;
    /** 远程机器IP */
    private String ip;
    /** 用户名 */
    private String osUsername;
    /** 密码 */
    private String password;
    private String charset = Charset.defaultCharset().toString();

    private static final int TIME_OUT = 1000 * 5 * 60;

    public RemoteShellExecutor(String ip, String usr, String pasword) {
        this.ip = ip;
        this.osUsername = usr;
        this.password = pasword;
    }


    /**
     * 登录
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(osUsername, password);
    }

    /**
     * 执行脚本
     *
     * @param cmds
     * @return
     * @throws Exception
     */
    public int exec(String cmds) throws Exception {
        InputStream stdOut = null;
        InputStream stdErr = null;
        String outStr = "";
        String outErr = "";
        int ret = -1;
        try {
            if (login()) {
                // Open a new {@link Session} on this connection
                Session session = conn.openSession();
                // Execute a command on the remote machine.
                session.execCommand(cmds);
                stdOut = new StreamGobbler(session.getStdout());
                outStr = processStream(stdOut, charset);

                stdErr = new StreamGobbler(session.getStderr());
                outErr = processStream(stdErr, charset);

                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

//                System.out.println("outStr=" + outStr);
                System.out.println(outStr);
//                System.out.println("outErr=" + outErr);
                System.out.println(outErr);

                ret = session.getExitStatus();
            } else {
                throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
            IOUtils.closeQuietly(stdOut);
            IOUtils.closeQuietly(stdErr);
        }
        return ret;
    }

    private String processStream(InputStream in, String charset) throws Exception {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }

    public static void main(String args[]) throws Exception {
        RemoteShellExecutor executor = new RemoteShellExecutor("192.168.0.107", "root", "123456");
        // 执行myTest.sh 参数为java Know dummy
        System.out.println(executor.exec("sh t1.sh"));
        
    }
}

t1.sh

echo 'hi'
source ~/.bash_profile
ll
java -version

思路就是把你要执行的shell,放到一个文件中,然后在这个文件的开头执行source ~/.bash_profile,这样环境变量就生效了,然后你可以达到调用命令的目的了

效果图

参考:
java 远程执行Shell命令-通过ganymed-ssh2连接
https://www.jianshu.com/p/513c72dfee1b

原文地址:https://www.cnblogs.com/renguanyu/p/15225633.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


背景:我已经有一个ssh公钥和私钥了,绑定的是公司的码云但是绑定github是不允许的所以我需要在生成一个公钥和私钥第一步执行下面的命令, 至于如果生成ssh公钥点击这里ssh-keygen-trsa-C'your_email@example.com'-f~/.ssh/id_rsa_github然后一路回车 这里注意id_srs_g
在服务器程序的部署运维过程中,我们经常需要将文件从一个服务器拷贝到另一个服务器中。可以使用ftp,可以使用samba服务,这里我们介绍scp命令进行文件的拷贝和传输。scp是securecopy的缩写,scp是linux系统下基于ssh登陆进行安全的远程文件拷贝命令。scp是加
#!/bin/bash#创建一个以.sc结尾的文件,把要操作的主机按顺序填写进去,多个IP另起一行顶格填写例如:#192.168.0.1#192.168.0.2#确保当前操作脚本的主机,已经可以免密到被操作主机,如未完成请自行解决。do_command(){hosts=`sed-n'/^[^#]/p'*.sc`forhost
打开终端安装openssh-server软件包:sudoaptupdatesudoaptinstallopenssh-server安装完成后,SSH服务默认自动启动,你可以通过以下命令校验服务运行状态:sudosystemctlstatusssh如果防火墙开启,则需要让防火墙允许ssh通过sudoufwallowssh注意事项VMware虚拟
环境centos7.9,.NET5一、Jenkins搭建1)下载Jenkins的war包在\home目录建一个jenkins目录放jenkins的包#进入\home目录cd\home#创建jenkins目录mkdirjenkins在jenkins目录下载war包#进入jenkin目录cd\home\jenkins#下载jenkins的war包wgethttp://mirrors.jenkin
dropbear下载地址:https://matt.ucc.asn.au/dropbeareleases/dropbear-2020.81.tar.bz2软件版本号说明opensuse 15.3 ssh8 dropbear2020.81     安装编译器和依赖:zypperinstallzlib-develgcc配置安装目录:./configure--prefix=/
1.前言前面基本上已经都讲完了MHA的原理部分,这小结主要是动手实操一下MHA2.前提准备1.首先下载MHA软件包(1)#下载mha软件mha官网:https://code.google.com/archive/p/mysql-master-ha/github下载地址:https://github.com/yoshinorim/mha4mysql-manager
前期准备确定服务器可以上网apt源配置完毕安装ssh使用apt安装openssh服务。sudoapt-getinstallopenssh-server启动sshroot@cka01:~#sudo/etc/init.d/sshstart#确定22端口存在并存活root@cka01:~#ss-tnl|grep22LISTEN01280.0.0
1.首先你需要在github上或者gitlab上建立了自己的账户,项目组已经将你加入了group。2.打开gitbash,输入命令ls-al~/.ssh如果显示如下图:则表示生成过key,可以去执行第4个步骤。否则的话执行第三个步骤生成key  3.这个时候输入命令ssh-keygen-trsa-C"min~~~~"  这
简述Linux如何远程拷贝,限速和断点续传scp命令 –远程拷贝文件scp拷贝本地文件filename到远程机器192.168.188.188服务器的/datamp目录下scp-P61204-l40000filenameusername@192.168.188.188:/datamp/ -PportSpecifiestheporttoconnecttoontherem
最近两天发现push代码到GitHub上时,发现必须得用SSH或者Token的方式。直接上干货1.SSH方式 1.1在桌面上GitBashHere 1.2检查是否已存在SSH   如果已存在,则直接进入.ssh目录1.3不存在,则创建一个SSHkey(如果不需要设置输入密码,一直回车就好)$ssh-keygen
安装命令yuminstallopenssh-clientsLinuxscp命令用于Linux之间复制文件和目录。scp是securecopy的缩写,scp是linux系统下基于ssh登陆进行安全的远程文件拷贝命令。scp是加密的,rcp 是不加密的,scp是rcp的加强版。语法scp[-1246BCpqrv][-ccipher][-F
1.环境介绍1.本地为windows2.远程为linux2.本地安装ssh环境我这里下载了git,所以在环境变量里把/git/usr/bin加进去就可以了3.本地vscode安装远程开发插件Remote-development是一个集成插件,安装它就可以了4.生成ssh秘钥对,并将公钥放入远程机#本地机生成秘钥对$s
文章链接故障表现在使用jumperver登录AWSec2实例的时候发现ssh配合秘钥登录的时候无法登录,具体报错如下:ssh-i/path/xx.pemuser@10.0.11.190Permissiondenied(publickey,gssapi-keyex,gssapi-with-mic).问题排查过程在发现无法登录的第一时间等了AWS平台查
1.给root用户设置密码sudopasswdroot2.修改sshd配置文件sudonano/etc/ssh/sshd_config修改PermitRootLoginyes把PermitRootLoginwithout-password或者PermitRootLoginprohibit-password改为PermitRootLoginyes,注意PermitRootLoginwithout-password可能被注
手上有一台12.4的ios机器,通过SecureCrt可以ssh上去,但是每次连接的时候都会报“KeyboardInteractive”错误,skip即可,但是通过ssh客户端连接,却无法正常连接,错误提示如下:@127.0.0.1:Permissiondenied(publickey,password,keyboard-interactive) 开始以为是KeyboardInteract
1、创建私有CA并进行证书申请。1.创建CA所需要文件#生成证书索引数据库文件touch/etc/pki/CA/index.txt#指定第一个颁发证书的序列号echo01>/etc/pki/CA/serial2、生成CA私钥cd/etc/pki/CA/(umask066;opensslgenrsa-outprivate/cakey.pem2048)3、生成CA自签名证书op
克隆两台虚拟机加master三台组成一个集群 所克隆的虚拟机需要修改主机名,ip 永久修改主机名 hostnamectlset-hostnamenode1或node2 ip 方式1: 通过可视化界面直接修改 方式2: vim/etc/sysconfigetwork-scripts/ifcfg-ens33 然后重启网络:servicenetworkrestart
SSH配置文件中加密算法没有指定,默认支持所有加密算法,包括arcfour,arcfour128,arcfour256等弱加密算法。但是目前RC4是不安全算法若数据库安全性要求比较高,这个漏洞还是必须要修复的,下面记录下OracleRAC修复过程,此修复过程不影响现有系统。如有不当欢迎斧正。1、root权限用户才能
问题:通过XShell等客户端使用ssh方式通过root用户连接Ubuntu虚拟机时,出现SSH服务器拒绝了密码,请再试一次。解决:安装ssh,开启root用户登录权限。1安装ssh-serverroot@ubuntu:/etc/apt#apt-getinstallopenssh-server安装ssh-server2安装ssh-clientroot@ubuntu:/etc/apt#ap