部署openssh服务器

时间:2023-03-09 17:02:26
部署openssh服务器
1、安装服务器端软件包
先查看是否已经安装openSSH服务器软件包
# rpm -qa|grep openssh
openssh-askpass-.3p1-.el6_6..x86_64
openssh-server-.3p1-.el6_6..x86_64 #服务器端软件包
openssh-clients-.3p1-.el6_6..x86_64 #客户端软件包
openssh-.3p1-.el6_6..x86_64 #包含服务器端和客户端的核心文件
如果没有安装,挂载光盘,
#mkdir /mnt/local                                  #创建一个目录,用于挂载光盘文件
# mount /dev/cdrom /mnt/local/
mount: block device /dev/sr0 is write-protected, mounting read-only
# cd /mnt/local/Packages/ #DVD镜像文件的盛放目录
进入光盘目录,找到并执行执行下列命令:
# rpm -ivh openssh-.3p1-.el6.x86_64.rpm
# rpm -ivh openssh-server-.3p1-.el6.x86_64.rpm
# rpm -ivh openssh-clients-.3p1-.el6.x86_64.rpm
# rpm -ivh openssh-askpass-.3p1-.el6.x86_64.rpm 按序安装
# ssh -v                    #版本信息
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips Feb
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-e escape_char] [-F configfile]
[-I pkcs11] [-i identity_file]
[-L [bind_address:]port:host:hostport]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
[-R [bind_address:]port:host:hostport] [-S ctl_path]
[-W host:port] [-w local_tun[:remote_tun]]
[user@]hostname [command]
2、服务器端配置文件详解
# cat /etc/ssh/sshd_config
一般默认不需要修改就能连接,每一行都是"关键词   值"的格式。
 #Port                                         #服务器监听的端口号
#AddressFamily any
#ListenAddress 0.0.0.0 #设置OpenSSH服务器绑定的IP
#ListenAddress :: # Disable legacy (protocol version ) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol
Protocol # HostKey for protocol version
#HostKey /etc/ssh/ssh_host_key #设置包含计算机私有主机秘钥的文件
# HostKeys for protocol version
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key # Lifetime and size of ephemeral version server key
#KeyRegenerationInterval 1h
#ServerKeyBits #设置服务器秘钥的位数,最小值512,默认1024 # Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO #设置记录ssh日志消息的级别 # Authentication: #LoginGraceTime 2m #设置如果用户不能成功登录,在切断连接之前服务器需要等待的时间
#PermitRootLogin yes #设置root用户是否能够使用ssh登录
#StrictModes yes
#MaxAuthTries
#MaxSessions #指定允许每个网络连接打开的最大会话数,默认10 #RSAAuthentication yes #设置是否允许只有RSA安全验证
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no #设置是否允许用rhosts或/etc/hosts.equiv加上RSA进行安全验证
# similar for protocol version
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes #设置RhostsRSA验证和Hostbased验证的时候是否使用.rhosts和.shosts文件 # To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes #设置是否允许口令验证
#PermitEmptyPasswords no #设置是否允许用户口令为空字符串的账号登陆,默认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 no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange 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'.
#UsePAM no
UsePAM yes # 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 #AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes #设置是否允许X11转发
#X11DisplayOffset
#X11UseLocalhost yes
#PrintMotd yes #设置sshd是否在用户登陆的时候显示/etc/motd文件的信息
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval
#ClientAliveCountMax #设置允许超时的次数(指定从客户端断开连接之前,在没有接到响应时能够发送客户端活跃消息的次数)
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups :: #指定SSH守护进程并未经身份验证连接的最大数量,默认值是10
#PermitTunnel no
#ChrootDirectory none # no default banner path
#Banner none # 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
# ForceCommand cvs server AllowGroups #设置允许连接的组群
AllowUsers #设置允许连接的用户
DenyGroup #设置拒绝连接的组群
DenyUsers #设置拒绝连接的用户(默认没有这个项,需要手动添加,若模式写成User@Host,则User和Host将同时被检查,限制特定用户在特定主机上连接SSH服务器,例Tom@192.168.10.10,表示拒绝用户Tom在192.168.10.10的主机上连接openSSH服务器
2、服务器配置实例
某公司内部部署OpenSSH服务器,为公司网络内的客户端计算机提供远程SSH登陆服务,具体参数:
服务器IP:192.168.0.2
监听端口:22
不允许空口令用户登陆
禁止test用户登陆
修改sshd_config文件参数如下;
13Port
ListenAddress 192.168.0.2
Protocol
SyslogFacility AUTHPRIV
#PermitEmptyPasswords no
PasswordAuthentication yes
DenyUsers test
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials yes
UsePAM yes
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
X11Forwarding yes #设置是否允许X11转发
Subsystem sftp /usr/libexec/openssh/sftp-server
  3、控制SSH服务                                           
[root@vnc Packages]# vim /etc/ssh/
moduli ssh_host_dsa_key ssh_host_key.pub
ssh_config ssh_host_dsa_key.pub ssh_host_rsa_key
sshd_config ssh_host_key ssh_host_rsa_key.pub
ssh_config 客户端配置文件
sshd_config 服务器配置文件
控制sshd服务
# service  sshd  start
# service sshd status
# service sshd stop restart
# service sshd reload 重新加载sshd服务配置
# chkconfig sshd on 开机自启动
# chkconfig --list sshd
四、配置Linux客户端软件
1、安装软件包
光盘或yum安装openssh和openssh-clients软件包
客户端配置文件ssh_config
# Host *                                                                只对匹配后面字符串的计算机有效,* 表示所有计算机
# ForwardAgent no
# ForwardX11 no
# RhostsRSAAuthentication no
# RSAAuthentication yes
# PasswordAuthentication yes
# HostbasedAuthentication no
# GSSAPIAuthentication no
# GSSAPIDelegateCredentials no
# GSSAPIKeyExchange no
# GSSAPITrustDNS no
# BatchMode no
# CheckHostIP yes
# AddressFamily any
# ConnectTimeout
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/identity
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# Port
# Protocol ,
# Cipher 3des
# Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
# MACs hmac-md5,hmac-sha1,umac-@openssh.com,hmac-ripemd160
# EscapeChar ~
# Tunnel no
# TunnelDevice any:any
# PermitLocalCommand no
# VisualHostKey no
Host *
GSSAPIAuthentication yes
# If this option is set to yes then remote X11 clients will have full access
# to the original X11 display. As virtually no X11 client supports the untrusted
# mode correctly we set this to yes.
ForwardX11Trusted yes
# Send locale-related environment variables
SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
SendEnv XMODIFIERS
2、ssh远程登录程序
ssh  [选项]   [用户]@主机[命令]
注意:设置好防火墙和SELinux,如果客户端无法连接,很多情况是这里出的问题
登录时不指定用户名,在本地服务器上的登陆名就会被传递给远程主机;
$ ssh 192.168.175.134
若希望指定不同用户名,用下面的命令:
例:2.1、以用户vn登陆到IP为192.168.175.138的用户
# ssh vn@192.168.175.138 
例:登陆并查看目录信息
# ssh root@192.168.175.138 ls -ahl /home
3、scp安全远程文件复制程序
命令的语法:
scp  [选项]  [[用户@主机1:]]文件1   [[用户@主机2:]文件2

例子1:用vn账户将本地/home目录下的update.sh文件传到192.168.175.138主机;/root目录下,同时更名为u.sh
[vn@vn /]$ whoami
vn 当前用户名
[vn@vn /]$ scp /home/update.sh root@192.168.175.138:/root/u.sh
例子2:用vn账户把/home及其目录下所有文件和子目录都传送到远程主机/root/test目录下:
[vn@vn /]$ scp -r /home root@192.168.175.138:/root/test
root@192.168.175.138's password: //输入密码
[vn@vn /]$ ssh root@192.168.175.138 ls -ld /root/test/home //这里可以查看传送的文件
root@192.168.175.138's password:
drwxr-xr-x. root root 7月 : /root/test/home
例子3:将远程主机上/root/test/home目录及其子目录传送到本地主机/root目录下
[root@vn vn]# scp -r root@192.168.175.138:/root/test/home /root
root@192.168.175.138's password:
[root@vn vn]# ls -ld /root/home/
drwxr-xr-x. root root 7月 : /root/home/ 
4、sftp安全的文件传输程序
命令语法:
sftp  [选项]主机
sftp  [用户@]主机[:文件]
sftp  [用户@]主机[:dir[/]]
sftp  [选项][用户@]主机
例子:
[root@vn vn]# scp -r root@192.168.175.138:/root/test/home /root
root@192.168.175.138's password:
[root@vn vn]# ls -ld /root/home/
drwxr-xr-x. root root 7月 : /root/home/

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 [-P] remote-path [local-path] Download 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 oldpath newpath Symlink remote file
lpwd Print local working directory
ls [-1aflnrSt] [path] Display remote directory listing
lumask umask Set local umask to 'umask'
mkdir path Create remote directory
progress Toggle display of progress meter
put [-P] local-path [remote-path] 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>
五、Windows客户端
putty或Xshell
六、OpenSSH服务器高级配置:
1、禁止root用户ssh登陆
编辑配置文件:
[root@computer ~]# vim /etc/ssh/sshd_config 
将#PermitRootLogin yes  去掉注释,将yes更改为no
重启ssh服务:
[root@computer ~]# service sshd restart
测试:
[root@vn ~]# ssh root@192.168.175.138
root@192.168.175.138's password:
Permission denied, please try again. //连接被拒绝
2、创建SSH认证秘钥
ssh-keygen命令可以生成、管理和转换SSH认证秘钥,使用SSH v1创建RSA秘钥,使用SSH v2创建RSA或DSA秘钥。-t指定生成类型,默认为SSH v2连接的RSA秘钥。
命令语法:
ssh-kengen [选项]
[root@computer ~]# ssh-keygen help
Too many arguments.
usage: ssh-keygen [options]
Options:
-a trials Number of trials for screening DH-GEX moduli.
-B Show bubblebabble digest of key file.
-b bits Number of bits in the key to create.
-C comment Provide new comment.
-c Change comment in private and public key files.
-D pkcs11 Download public key from pkcs11 token.
-e Convert OpenSSH to RFC key file.
-F hostname Find hostname in known hosts file.
-f filename Filename of the key file.
-G file Generate candidates for DH-GEX moduli.
-g Use generic DNS resource record format.
-H Hash names in known_hosts file.
-h Generate host certificate instead of a user certificate.
-I key_id Key identifier to include in certificate.
-i Convert RFC to OpenSSH key file.
-L Print the contents of a certificate.
-l Show fingerprint of key file.
-M memory Amount of memory (MB) to use for generating DH-GEX moduli.
-N phrase Provide new passphrase.
-O option Specify a certificate option.
-P phrase Provide old passphrase.
-p Change passphrase of private key file.
-q Quiet.
-R hostname Remove host from known_hosts file.
-r hostname Print DNS resource record.
-S start Start point (hex) for generating DH-GEX moduli.
-s ca_key Certify keys with CA key.
-T file Screen candidates for DH-GEX moduli.
-t type Specify type of key to create.
-V from:to Specify certificate validity interval.
-v Verbose.
-W gen Generator to use for generating DH-GEX moduli.
-y Read private key file and print public key.
-Z name,... User/host principal names to include in certificate
-z serial Specify a serial number.

例1、创建RSA秘钥

[root@computer ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): //直接回车,使用默认文件保存秘钥
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): //输入秘钥保护密码
Enter same passphrase again: //再次输入秘钥保护密码
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
:5f:::4a:7a:9d:5a:fb::::c7:::b9 root@computer
The key's randomart image is:
+--[ RSA ]----+
| . .+. |
| o oo . |
| oo + . = |
| .. o = = +|
| S. o + +.|
| . o E |
| * |
| . |
| |
+-----------------+
例2、显示主机的公钥文件的SSHFP指纹资源记录
[root@computer ~]# ssh-keygen -r rhel
rhel IN SSHFP 38b3bd45ce295040ebb21a415f5a4674e36c0389
rhel IN SSHFP 2cf544964ba9cba2c1135f5decc96dd92a897c1d
例3、创建ssh认证秘钥,指定秘钥文件为/root/.ssh/known_hosts
[root@computer ~]# ssh-keygen -f /root/.ssh/known_hosts
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): //输入秘钥保护密码
Enter same passphrase again: //再次输入秘钥保护密码
Your identification has been saved in /root/.ssh/known_hosts.
Your public key has been saved in /root/.ssh/known_hosts.pub.
The key fingerprint is:
f8:b0:c0:8d:bd:1f:d3:c9:ae:e5::5f::ca::b9 root@computer
The key's randomart image is:
+--[ RSA ]----+
| |
| . |
| o |
| . + o . |
| + = E . |
| . = = o . . |
| o + O . . .|
| . B . . . |
| o.o . |
+-----------------+
例4、创建DSA秘钥
[root@computer ~]# ssh-keygen -d
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa): 直接回车,使用默认文件保存秘钥
Enter passphrase (empty for no passphrase): 使用秘钥保护密码
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
b0:fd::1d::f2::b4:a0:cb:ad:be::3c:d2: root@computer
The key's randomart image is:
+--[ DSA ]----+
| .o.. |
| .+.o.o|
| . ...+ o.|
| + ..o . |
| . S .o . |
| oo o |
| E o.B |
| . = . |
| o. |
+-----------------+
七、使用秘钥认证方式连接OpenSSH服务器实例
服务器端:192.168.175.134 (hostname:   vn)
客户端:192.168.175.138 (hostname:  computer)
1、OpenSSH客户端配置
(1)、创建DSA秘钥
[root@computer ~]# ssh-keygen -d
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Passphrases do not match. Try again.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
::0d::::dc:e8:b2:2b:::1d:7d:ba: root@computer
The key's randomart image is:
+--[ DSA ]----+
| .+*. |
| o*.o . |
| .o o o |
| . o+o E |
| . .ooS. o |
| . .o .. |
| o . |
| . . . |
| . |
+-----------------+
查看 /root/.ssh目录下生成的公钥和私钥文件:
[root@computer ~]# ls /root/.ssh/id_dsa*
/root/.ssh/id_dsa /root/.ssh/id_dsa.pub
安装公钥到OpenSSH服务器
[root@computer ~]# ssh-copy-id -i ~/.ssh/id_dsa.pub 192.168.175.134
The authenticity of host '192.168.175.134 (192.168.175.134)' can't be established.
RSA key fingerprint is 5e:0c:e1:cc:::a1:9b::d5:aa:2b:6d:7b:c3:.
Are you sure you want to continue connecting (yes/no)? yes 同意连接
Warning: Permanently added '192.168.175.134' (RSA) to the list of known hosts.
root@192.168.175.134's password: 输入主机192.168.175.134的root用户密码
Now try logging into the machine, with "ssh '192.168.175.134'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
2、OpenSSH服务器配置
(1)、修改配置文件
# vim /etc/ssh/sshd_config
 66 PasswordAuthentication no
(2)、重启服务
# service sshd restart
停止 sshd: [确定]
正在启动 sshd: [确定]
(3)、查看公钥(
[root@vn ~]# ls /root/.ssh/
authorized_keys known_hosts
[root@vn ~]# cat /root/.ssh/authorized_keys 该文件的内容和OpenSSH客户端上的公钥文件是一致的
ssh-dss AAAAB3NzaC1kc3MAAACBAPuwIw7NDzwNXWaxG5rUsySBzqMlGRTBtAqXWmA2gUsPgJXuf8F0y+cqjCt6EnISp98dPbUR9UkkGOtnl627kDrW1Q/zT6S4Z4d9QT94zEYhXZ8u3OJsxHW8vru1wEdyPG0AmYHrZyBONUdw8vjOn2RX1pIZ3qaHTgwcxWPPNH43AAAAFQDYTPLsiarPPiE1D5dQ0RcmfySwjQAAAIEA3aULtXsmcoB71kgZxj6iRIZpz+t06EfnRaXZbTCY7BlFNF16bY/Fjub/fOD51nZN4q9kaxkDFD6P7z2kMDP47j+9BVHEJFlCixUr8RimYCDPLgE8KIQuyt5ymdZ8TaGUOt1Fz5YsJ1YsSpk09rl0jGjl+vaqVVaihsGmmZdHkskAAACAZnNOLCE+T9mQmR4MNQUNFCDm0uDE8aet1UEHdh1GyQjLy4LfU/u2vRin8w4/2rmq2/zNUHTVXvWed/FG1oQQxSwUfOFhDmyh3mjl7O+fk1qznexC/mPuO3p49dhkkCBECqYGK9ZjrpLojoM7bxvkHT1TU86N7wLJK/n37/VIiXE= root@computer
3、连接OpenSSH服务器
[root@computer ~]# ssh 192.168.175.134
Enter passphrase for key '/root/.ssh/id_dsa': 输入秘钥保护密码
Last login: Fri Jul :: from 192.168.175.1
[root@vn ~]# ifconfig eth1|grep "inet addr" 登陆服务器成功
inet addr:192.168.175.134 Bcast:192.168.175.255 Mask:255.255.255.0