Java实现SSH2工具类以及创建SFTP用户

Java实现SSH2工具类以及创建SFTP用户

SSH2工具类

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


/**
 * @author : liuyang
 * @date : Mar 23 2021
 * @value : SSH2工具类
 */
public class JSchUtils {
    private Session session;

    private String username;
    private String password;
    private String host;
    private int port;

    public JSchUtils(String username, String password, String host ,int port ) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    /**
     *
     * 登录
     *
     */
    public void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);

        // 为session对象设置properties,第一次访问服务器时不用输入yes
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();

    }

    /**
     *
     * 退出
     *
     */
    public void disconnect() {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }


    /**
     *
     * 执行命令(增加sftp用户等命令)
     *
     */
    public String execCmd(String command) throws JSchException, IOException {
        /**
         * 返回信息
         */
        final StringBuilder stringBuilder = new StringBuilder(256);
        BufferedReader reader = null;
        /**
         * 创建连接通道
         */
        Channel channel = null;
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(null);
        /**
         * 连接
         * 运行命令
         */
        channel.connect();
        InputStream in = channel.getInputStream();
        reader = new BufferedReader(new InputStreamReader(in, Charset.forName(String.valueOf(StandardCharsets.UTF_8))));
        String buf;
        while ((buf = reader.readLine()) != null) {
            stringBuilder.append(buf);
            stringBuilder.append(";");
        }
        channel.disconnect();

		/**
		 * 返回指令返回的字符串
		 *
		 */
        return stringBuilder.toString();
    }


}

创建SFTP用户

useradd -d homePath -m -g groupName -s /bin/false username
echo "password"|passwd --stdin username
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值