shell(17) : java完成scp功能

maven

<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-common -->
<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-common</artifactId>
    <version>2.7.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-core -->
<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>2.7.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-scp -->
<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-scp</artifactId>
    <version>2.7.0</version>
</dependency>

 

 ScpUtil


import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClient;
import org.apache.sshd.scp.client.ScpClientCreator;

/**
 * @author Miracle Luna
 * @date 2021/7/19
 */
public class ScpUtil {

    public static void scpFile(String localFile, String remoteFile, String host, Integer port,
                               String username, String password) throws Exception {
        long startTime = System.currentTimeMillis();
        // 创建 SSH客户端
        SshClient client = SshClient.setUpDefaultClient();
        // 启动 SSH客户端
        client.start();
        // 通过主机IP、端口和用户名,连接主机,获取Session
        ClientSession session = client.connect(username, host, port).verify().getSession();
        // 给Session添加密码
        session.addPasswordIdentity(password);
        // 校验用户名和密码的有效性
        boolean isSuccess = session.auth().verify().isSuccess();

        // 认证成功
        if (isSuccess) {
            long middleTime = System.currentTimeMillis();
            System.out.println("连接成功,耗时: " + (middleTime - startTime) / 1000.0 + "秒。");
            ScpClientCreator creator = ScpClientCreator.instance();
            // 创建 SCP 客户端
            ScpClient scpClient = creator.createScpClient(session);
            // 添加 ScpClient.Option.Recursive 参数为上传文件夹
            scpClient.upload(localFile, remoteFile);
            // 释放 SCP客户端
            if (scpClient != null) {
                scpClient = null;
            }
            // 关闭 Session
            if (session != null && session.isOpen()) {
                session.close();
            }
            // 关闭 SSH客户端
            if (client != null && client.isOpen()) {
                client.stop();
                client.close();
            }
        } else {
            System.err.println("认证失败");
            return;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("总耗时 : " + (endTime - startTime) / 1000.0 + "秒。");
    }

    public static void main(String[] args) throws Exception {
        scpFile("/home/测试.md", "/root/测试2.md",
                "1.2.3.4", 22, "root", "123");
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java里可以通过Ganymed SSH-2, Expect4j等实现ssh登录,由于Ganymed SSH-2是纯java实现,并且可以实现scp,sftp等,因此我们采用Ganymed SSH-2 1> 下载安装 从http://code.google.com/p/ganymed-ssh-2/ 下载,我们用的是ganymed-ssh2-build251beta1.zip。 在eclipse里新建一个测试工程,并将解压后的ganymed-ssh2-build251beta1.jar拷到工程的lib目录下,然后在工程属性的java build path里添加这个jar的library。 2> ssh 将解压后的examples目录下的Basic.java 拷到工程的src目录,编译运行以后可以在控制台看到输出结果。除了执行一条命令,也可以执行一个shell脚本。 例如将Basic.java中的“uname -a && date && uptime && who” 改为“/home/lss/test.sh”, test.sh的内容如下: #! /bin/sh echo "testing shell"; ls; 在eclipse里运行以后的结果为: Here is some information about the remote host: testing shell 1 test.sh ExitCode: 0 需要注意的是在一个session里只能执行一次命令,因此如果想在server上执行多个命令,要么打开多个session,要么在一个session里去执行一个shell脚本,shell脚本里去执行多个命令。 每次执行完以后,如果正确将返回ExitCode: 0,因此程序里可以通过sess.getExitStatus()来判断命令是否被正确执行。 3> scp 首先在程序里import ch.ethz.ssh2.SCPClient; 然后通过下面的方法来实现: SCPClient scpClient = conn.createSCPClient(); scpClient.put("localFiles", "remoteDirectory"); //从本地复制文件到远程目录 scpClient.get("remoteFiles","localDirectory"); //从远程获取文件 例如: scpClient.put("D:\\localTest.txt", "/home/bill/"); 需要注意的是windows的本地目录要用双斜杠来分隔目录。 scpClient.put("/home/bill/remoteTest.txt", "D:\\"); 4> sftp 首先在程序里import ch.ethz.ssh2.SFTPv3Client; SFTPv3Client sftpClient = new SFTPv3Client(conn); sftpClient.mkdir("newRemoteDir", 0755); //远程新建目录 ,第二个参数是创建的文件夹的读写权限 sftpClient.rmdir("oldRemoteDir"); //远程删除目录 另外还有创建删除文件,读写文件等接口,参见http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/SFTPv3Client.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值