linux配置应用服务器通过证书免密码登录SFTP测试站点

Posted 白-胖-子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux配置应用服务器通过证书免密码登录SFTP测试站点相关的知识,希望对你有一定的参考价值。

SFTP和vsftp是完全两回事。

  • sftp是sshd服务附带的文件传输协议。
  • vsftp是vsftpd服务,是正儿八经的传统意义上的FTP

sftp配置文件

  • sftp没有自己的配置文件,因为是sshd附赠的,所以和ssh公用22端口以及sshd的配置文件
    cat /etc/ssh/sshd_config

sftp服务器配置

  • 其实每台能ssh上去的服务器都可以看作是sftp服务器
  • 但为了限制sftp的访问目录,俗话叫禁锢,需要在配置文件中做点设置
  1. 修改配置文件添加禁锢sftp用户的配置信息,在配置文件的最下边
# 上边还有挺老些就不涉及到了
# 最主要的是Subsystem sftp /usr/libexec/openssh/sftp-server 
# 这行要注释掉原来的,添加新的
# override default of no subsystems
#Subsystem	sftp	/usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	PermitTTY no
#	ForceCommand cvs server
Subsystem sftp internal-sftp -l INFO -f AUTH
Match Group sftpuser
   ChrootDirectory /app/sftpsite
   X11Forwarding no
   AllowTcpForwarding no
   ForceCommand internal-sftp -l INFO -f AUTH
  1. 创建sftp上传下载用户和目录
[root@C8-196 ~]# id sftp
id: ‘sftp’: no such user
[root@C8-196 ~]# mkdir -pv /app/sftpsite/
[root@C8-196 ~]# useradd -d /app/sftp sftpuser
[root@C8-196 ~]# chown root:sftpuser /app/sftp
sftp/     sftpsite/ 
[root@C8-196 ~]# chown root:sftpuser /app/sftpsite/
[root@C8-196 ~]# ll -d /app/sftpsite/
drwxr-xr-x 2 root sftpuser 6 Feb 25 23:13 /app/sftpsite/
[root@C8-196 ~]# id sftpuser
uid=1001(sftpuser) gid=1001(sftpuser) groups=1001(sftpuser)
  • 为了做免密,就要给sftpuser用户密码
    passwd sftpuser
  1. 重启sshd服务
    systemctl restart sshd.service

sftp客户端设置

  • 登录客户端切到sftp上传的普通用户
[root@C8-197 ~]# id fbqadm
uid=1002(fbqadm) gid=1002(fbqadm) groups=1002(fbqadm)
[root@C8-197 ~]# su - fbqadm
  • 先尝试使用新建的sftpuser连接服务器端的ssh,果然不可以,哈哈哈!这就对了
[fbqadm@C8-197 ~]$ ssh sftpuser@10.0.0.196
The authenticity of host '10.0.0.196 (10.0.0.196)' can't be established.
ECDSA key fingerprint is SHA256:aywhAJk1lgttDV9vmoQsM8rtnBJiPXgCCGbt5B1oAlk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.196' (ECDSA) to the list of known hosts.
sftpuser@10.0.0.196's password: 
Permission denied, please try again.
sftpuser@10.0.0.196's password: 
This service allows sftp connections only.##看这里,只允许sftp连接
Connection to 10.0.0.196 closed.
  • 生成自己的密钥对
[fbqadm@C8-197 ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/fbqadm/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/fbqadm/.ssh/id_rsa.
Your public key has been saved in /home/fbqadm/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Qj30y4BN7Gews6Z3K7vbq3uHZFJPr4T5chQn6znc+AU fbqadm@C8-197
The key's randomart image is:
+---[RSA 3072]----+
|       .o        |
|       *o.       |
|      o.=o.      |
|     .  +++.+ .  |
|      . S*o= *E  |
|       .+ = = .. |
|       o + B =  .|
|      . o.= @ .. |
|       .*X+* o.  |
+----[SHA256]-----+
  • 将密钥对拷贝给服务器
[fbqadm@C8-197 ~]$ ssh-copy-id sftpuser@10.0.0.196
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/fbqadm/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
sftpuser@10.0.0.196's password: 
This service allows sftp connections only.

很显然失败了,哈哈哈哈!!!自己给自己挖了个坑吧!

  • 这时候解决有两种思路:
  1. 第一个是在客户端将自己的pubkey也就是公钥下载到本地,在用其他方式丢到服务器的.ssh目录中的auto那个啥文件里面添加一行,这本来也是ssh-copy-id做的事情
  2. 第二个也就是不嫌麻烦的把服务器端的sshd配置再改过去,取消禁锢。本来我们可以一开始就这么做,但为了演示效果,特意禁锢了一下子,再做ssh-copy-id也是不可以的。
## 服务器端就是把之前添加的内容注释掉再重启sshd服务器就可以了。这里就不贴上来了。
[fbqadm@C8-197 ~]$ ssh-copy-id sftpuser@10.0.0.196
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/fbqadm/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
sftpuser@10.0.0.196's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'sftpuser@10.0.0.196'"
and check to make sure that only the key(s) you wanted were added.

[fbqadm@C8-197 ~]$ ssh 'sftpuser@10.0.0.196'
Last login: Sat Feb 26 22:40:47 2022 from 10.0.0.197
[sftpuser@C8-196 ~]$ who am i
sftpuser pts/1        2022-02-26 22:55 (10.0.0.197)

服务器端改过配置文件后,客户端就可以ssh-copy-id了,做好之后记得把配置文件再改过去,然后重启sshd服务就好了。

  • 现在客户端不能ssh到服务器端,但做到了sftp免密服务器端了
[fbqadm@C8-197 ~]$ ssh 'sftpuser@10.0.0.196'
This service allows sftp connections only.
Connection to 10.0.0.196 closed.## 看看,即使做了免密,也不能ssh
[fbqadm@C8-197 ~]$ sftp 'sftpuser@10.0.0.196'
Connected to sftpuser@10.0.0.196.## sftp可以免密登陆了
sftp> pwd
Remote working directory: /
sftp> mkdir sftptest20220226## 新建文件夹
Couldn't create directory: Permission denied ## 没权限
  • 服务器端如果需要允许客户端进行读以外的写和删操作,需要在服务器端给目录加775权限
[root@C8-196 ~]# ll /app/sftpsite/ -d
drwxr-xr-x 2 root sftpuser 6 Feb 25 23:13 /app/sftpsite/
[root@C8-196 ~]# chmod 775 /app/sftpsite/
[root@C8-196 ~]# ll /app/sftpsite/ -d
drwxrwxr-x 2 root sftpuser 6 Feb 25 23:13 /app/sftpsite/
  • 这用客户端就具有了sftp服务器端写的权限
sftp> mkdir sftptest20220226
Couldn't create directory: Permission denied
sftp> mkdir sftptest20220226
sftp> ls
sftptest20220226 

附sftp命令

sftp> help
Available commands:
bye                                Quit sftp
cd path                            Change remote directory to 'path'
chgrp [-h] grp path                Change group of file 'path' to 'grp'
chmod [-h] mode path               Change permissions of file 'path' to 'mode'
chown [-h] 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

附sshd_config配置文件全部内容

[root@C8-196 ~]# cat /etc/ssh/sshd_config 
#	$OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# This system is following system-wide crypto policy. The changes to
# crypto properties (Ciphers, MACs, ...) will not have any effect here.
# They will be overridden by command-line options passed to the server
# on command line.
# Please, check manual pages for update-crypto-policies(8) and sshd_config(5).

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile	.ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Fedora and may cause several
# problems.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes

# It is recommended to use pam_motd in /etc/pam.d/sshd instead of PrintMotd,
# as it is more configurable and versatile than the built-in version.
PrintMotd no

#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
#Subsystem	sftp	/usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	PermitTTY no
#	ForceCommand cvs server
Subsystem sftp internal-sftp -l INFO -f AUTH
Match Group sftpuser
   ChrootDirectory /app/sftpsite
   X11Forwarding no
   AllowTcpForwarding no
   ForceCommand internal-sftp -l INFO -f AUTH

sftp和vsftp速度测试稍后再发。

以上是关于linux配置应用服务器通过证书免密码登录SFTP测试站点的主要内容,如果未能解决你的问题,请参考以下文章

linux配置应用服务器通过证书免密码登录SFTP测试站点

Linux配置免密登录

Linux 配置ssh 免密码登录

Linux之间配置SSH互信(SSH免密码登录)

Linux之间配置SSH互信(SSH免密码登录)

Linux——配置服务器间的免密登录