sftp安装和常用命令(linux)

# sftp安装

1. 查看openssh版本

ssh -V
openssh版本必须大于4.8p1

2. 创建sftp组

groupadd sftp

3. 创建sftp用户

useradd -g sftp -s /sbin/nologin -M sftp
passwd sftp
输入密码

4. 建立目录

mkdir -p /data/sftp/mysftp
usermod -d /data/sftp/mysftp sftp

5. 修改sshd_config

vim /etc/ssh/sshd_config
注释掉

# Subsystem sftp /usr/libexec/openssh/sftp-server

在最后面添加

Subsystem sftp internal-sftp
Match Group sftp
ChrootDirectory /data/sftp/mysftp
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no

6. 设置Chroot目录权限

chown root:sftp /data/sftp/mysftp
chmod 755 /data/sftp/mysftp

以上完成后,就可以登陆查看了。

7. 设置可以写入的目录

mkdir /data/sftp/mysftp/upload
chown sftp:sftp /data/sftp/mysftp/upload
chmod 755 /data/sftp/mysftp/upload
关闭selinux:
vim /etc/selinux/config
将文件中的SELINUX=enforcing 修改为 SELINUX=disabled ,然后保存。
执行:
setenforce 0
service sshd restart
或
systemctl restart sshd.service

8.测试验证

[root@i-scvedmvo ~]# touch 1.txt
[root@i-scvedmvo ~]# sftp sftp@127.0.0.1
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
sftp@127.0.0.1's password:
Connected to 127.0.0.1.
sftp> ls
upload
sftp> cd upload/
sftp> ls
sftp> put 1.txt
Uploading 1.txt to /upload/1.txt
1.txt                                                           100%    0     0.0KB/s   00:00
sftp> ls
1.txt

如果过于以下报错

[root@i-scvedmvo ~]# sftp sftp@127.0.0.1
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
Permission denied (publickey).
Couldn't read packet: Connection reset by peer

需要修改/etc/ssh/sshd_config文件中PasswordAuthentication为yes

PasswordAuthentication yes

sftp常用命令

1、基本用法

  • 登陆

    [root@i-scvedmvo ~]# sftp sftp@127.0.0.1
    Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
    sftp@127.0.0.1's password:
    Connected to 127.0.0.1.
  • help

    sftp> help
    Available commands:
    bye                                Quit sftp
    cd path                            Change remote directory to 'path'
    chgrp grp path                     Change group of file 'path' to 'grp'
    chmod mode path                    Change permissions of file 'path' to 'mode'
    chown own path                     Change owner of file 'path' to 'own'
    df [-hi] [path]                    Display statistics for current directory or
                                   filesystem containing 'path'
    exit                               Quit sftp
    get [-afPpRr] remote [local]       Download file
    reget [-fPpRr] remote [local]      Resume download file
    reput [-fPpRr] [local] remote      Resume upload file
    help                               Display this help text
    lcd path                           Change local directory to 'path'
    lls [ls-options [path]]            Display local directory listing
    lmkdir path                        Create local directory
    ln [-s] oldpath newpath            Link remote file (-s for symlink)
    lpwd                               Print local working directory
    ls [-1afhlnrSt] [path]             Display remote directory listing
    lumask umask                       Set local umask to 'umask'
    mkdir path                         Create remote directory
    progress                           Toggle display of progress meter
    put [-afPpRr] local [remote]       Upload file
    pwd                                Display remote working directory
    quit                               Quit sftp
    rename oldpath newpath             Rename remote file
    rm path                            Delete remote file
    rmdir path                         Remove remote directory
    symlink oldpath newpath            Symlink remote file
    version                            Show SFTP version
    !command                           Execute 'command' in local shell
    !                                  Escape to local shell
    ?                                  Synonym for help
  • 退出sftp

    bye
    exit
    quit
  • 更改远程服务器工作目录

    cd
  • 清屏

    clea
  • 从远程服务器上下载文件到本机

    get
  • 切换本地当前工作目录

    lcd
  • 列出本地当前目录的内容

    lls    list contents of a localdirectory
  • 打印当前工作目录

    lpwd
  • 列出远程服务器目录内容

    ls
  • 在远程服务器上创建一个目录

    mkdir
  • 搬移或重命名一个的远程服务器文件

    mv
  • 将本机的文件上传到远程服务器

    put
  • 打印远程服务器工作路径

    pwd
  • 搬移或重命名一个的远程服务器文件

    rename
  • 删除一个文件

    rm
  • 在远程服务器上删除一个目录删除一个目录

    rmdir

    2、常用的为上传下载

  • 1)get

从远程服务器上下载一个文件存放到本地,如下:

先通过lcd切换到本地那个目录下,然后通过get file

>> lcd d:\            #表示切换到本地的d盘下

>> get ./test.sql   #这样就将当前文件下载本地的d盘下
  • 2)put

是将本地的文件上传到远程服务器上,如下:

>> put               #在windows下弹出选择文件的窗口
  • 3)lcd

先通过lcd切换到本地那个目录下

>> lcd c:\            #表示切换到本地的c盘下
  • 4)lls

显示当前目录下的所有文件

  • 5)pwd

显示当前目录

Java通过SFTP连接、上传、下载、删除文件

1.需要导入的jar包:jsch-0.1.54.jar

2.工具类

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

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

public class SFTPUtil {
    private String host;//sftp服务器ip
    private String username;//用户名
    private String password;//密码
    private String privateKey;//密钥文件路径
    private String passphrase;//密钥口令
    private int port = 9022;//默认的sftp端口号9022

    public SFTPUtil(String host,String username,String password,String privateKey, String passphrase, int port) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.privateKey = privateKey;
        this.passphrase = passphrase;
        this.port = port;
    }
    /**
     * 获取连接
     * @return channel
     */
    public ChannelSftp connectSFTP() {
        JSch jsch = new JSch();
        Channel channel = null;
        System.out.println("--------privateKey:"+privateKey);
        try {
            if (privateKey != null && !"".equals(privateKey)) {
                //使用密钥验证方式,密钥可以使有口令的密钥,也可以是没有口令的密钥
                if (passphrase != null && "".equals(passphrase)) {
                    jsch.addIdentity(privateKey, passphrase);
                } else {
                    jsch.addIdentity(privateKey);
                }
            }
            Session session = jsch.getSession(username, host, port);
            if (password != null && !"".equals(password)) {
                session.setPassword(password);
            }

            //Console 里面打印连接的更多相关信息
            com.jcraft.jsch.Logger logger = new SettleLogger();
            JSch.setLogger(logger);

            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");// do not verify host key
            session.setConfig(sshConfig);
            // session.setTimeout(timeout);
            session.setServerAliveInterval(92000);
            session.connect();
            //参数sftp指明要打开的连接是sftp连接
            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            System.out.println("connectSFTP:"+e);
        }
        return (ChannelSftp) channel;
    }

    /**
     * 上传文件
     * 
     * @param directory
     *            上传的目录
     * @param uploadFile
     *            要上传的文件
     * @param sftp
     */
    public void upload(String directory, String uploadFile, ChannelSftp sftp) {
        try {
            System.out.println(directory);
            sftp.cd(directory);
            System.out.println(uploadFile);
            File file = new File(uploadFile);
            System.out.println(directory+","+uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
        } catch (Exception e) {
            System.out.println("upload:"+e);
        }
    }

    /**
     * 下载文件
     * 
     * @param directory
     *            下载目录
     * @param downloadFile
     *            下载的文件
     * @param saveFile
     *            存在本地的路径
     * @param sftp
     */
    public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.get(downloadFile,saveFile);
        } catch (Exception e) {
            System.out.println("download:"+e);
        }
    }

    /**
     * 删除文件
     * 
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            System.out.println("delete:"+e);
        }
    }

    public void disconnected(ChannelSftp sftp){
        if (sftp != null) {
            try {
                sftp.getSession().disconnect();
            } catch (JSchException e) {
                System.out.println("disconnected:"+e);
            }
            sftp.disconnect();
        }
    }
}

//Console 里面打印连接的更多相关信息
class SettleLogger implements com.jcraft.jsch.Logger {
    public boolean isEnabled(int level) {
        return true;
    }

    public void log(int level, String msg) {
        System.out.println(msg);
    }
}

3.调用

String host="sftp连接的ip";
String username = "sftp连接的用户名";
String password = "sftp连接的密码";
String privateKey = "ssh 私钥本地路径";
String passphrase = "";//ssh 私钥口令
int port = 22;//默认端口号是22
String directory = "./";//默认地址
String uploadfilepath = "需要上传的文件的本地路径";

SFTPUtil sftpUtil = new SFTPUtil(host,username,password,privateKey,passphrase,port);
ChannelSftp channelsftp =  sftpUtil.connectSFTP();
if(channelsftp!=null) {
    sftpUtil.upload(directory,uploadfilepath,channelsftp);
    //下载和删除就不写了 反正都是写一下服务器的文件路径 需要操作的文件 最后再写个channelsftp就好了 
    sftpUtil.disconnected(channelsftp);
}

————————————————
引用文章:https://blog.csdn.net/gzxdale/article/details/81140889

------本页内容已结束,喜欢请分享------

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发
冬子先生的头像-运维开发故事

昵称

取消
昵称表情代码图片