1. 程式人生 > >linux-openssh

linux-openssh

openssh

OpenSSH 是一組用於安全地訪問遠程計算機的連接工具。 它可以作為 rlogin、 rsh rcp 以及 telnet 的直接替代品使用。 更進一步, 其他任何 TCP/IP 連接都可以通過 SSH 安全地進行隧道/轉發。 OpenSSH 對所有的傳輸進行加密, 從而有效地阻止了竊聽、 連接劫持, 以及其他網絡級的攻擊。OpenSSH 由 OpenBSD project 維護。

登錄過程和使用 rlogin 或 telnet 建立的會話非常類似。 在連接時, SSH 會利用一個密鑰指紋系統來驗證服務器的真實性。 只有在第一次連接時, 用戶會被要求輸入 yes。 之後的連接將會驗證預先保存下來的密鑰指紋。 如果保存的指紋與登錄時接收到的不符, 則將會給出警告。 指紋保存在 ~/.ssh/known_hosts 中, 對於 SSH v2 指紋, 則是 ~/.ssh/known_hosts2。

默認情況下, 較新版本的 OpenSSH 只接受 SSH v2 連接。 如果能用版本 2 則客戶程序會自動使用, 否則它會返回使用版本 1 的模式。 此外, 也可以通過命令行參數 -1 或 -2 來相應地強制使用版本 1 或 2。 保持客戶端的版本 1 能力是為了考慮較早版本的兼容性。


 openssh: 
  C/S
   S: sshd
   C: ssh
    putty
    xshell
    securecrt
    sshshellclient


openssh的客戶端組件:
ssh: 配置/etc/ssh/ssh_config
ssh [username@]host [COMMAND]

ssh -l username host [COMMAND]
-p PORT

[[email protected] ~]# cat /etc/ssh/ssh_config
# $OpenBSD: ssh_config,v 0.25 2009/02/17 01:28:32 djm Exp $

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

# 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 0
#   StrictHostKeyChecking ask   # 詢問當前用戶是否接受主機密鑰
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   Port 22   #默認端口號
#   Protocol 2,1
#   Cipher 3des   #加密算法3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,[email protected]
/* */,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


基於密鑰的ssh登陸

[[email protected] ~]# ssh-keygen -t rsa  #生存密鑰:公鑰和私鑰
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:
f7:08:86:07:d6:65:79:23:6e:86:cd:96:75:38:07:80 [email protected]
The key‘s randomart image is:
+--[ RSA 2048]----+
|         .+o.o   |
|       .Eoo * o  |
|      o .= = =   |
|     . o. O      |
|      . S+.      |
|       o o o     |
|          . .    |
|                 |
|                 |
+-----------------+
[[email protected] ~]# ls .ssh/
id_rsa  id_rsa.pub
[[email protected] ~]# rm .ssh/* 
rm: remove regular file `.ssh/id_rsa‘? 
rm: remove regular file `.ssh/id_rsa.pub‘? 
[[email protected] ~]# ssh-keygen -t rsa -P ‘‘ -f ‘/home/root/.ssh/id_rsa‘          #-P 指定密碼,-f 指定保存目錄
Generating public/private rsa key pair.
open /home/root/.ssh/id_rsa failed: No such file or directory.
Saving the key failed: /home/root/.ssh/id_rsa.
[[email protected] ~]# ls .ssh/
id_rsa  id_rsa.pub
[[email protected] ~]# 
[[email protected] ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]              # ssh-copy-id將公鑰上傳至目的主機
The authenticity of host ‘192.168.1.29 (192.168.1.29)‘ can‘t be established.
RSA key fingerprint is 65:62:07:a9:06:32:39:e1:af:21:8d:5b:cf:53:27:e2.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.1.29‘ (RSA) to the list of known hosts.
reverse mapping checking getaddrinfo for bogon [192.168.1.29] failed - POSSIBLE BREAK-IN ATTEMPT!
[email protected] password: 
Now try logging into the machine, with "ssh [email protected]", and check in:

  .ssh/authorized_keys   

to make sure we haven‘t added extra keys that you weren‘t expecting.

[[email protected] ~]# ssh [email protected]   #驗證登陸成功
reverse mapping checking getaddrinfo for bogon [192.168.1.29] failed - POSSIBLE BREAK-IN ATTEMPT!
Last login: Sun Jul  2 04:27:29 2017 from 192.168.1.30
[[email protected] ~]# ls .ssh/
authorized_keys
[[email protected] ~]# cat .ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAs4m1xsgo2tQjJ+KRGHgGUUZ2ySYnqt+XRp3AikmuYFRFipX2B3vLTBCyq1XuOCThEws1STRXyZkNcLSVYafmuhshDuL5LM+13hFLbniVzrysuoUWKmaX/bjAY4+FZrt01OpkJjLZesn3TxxfAcigd+26sM5rM9MbFvfm2dZZXyfe7PUC1pTdVz0xVvQPq3L8rCD0dcp130VrD3cTNUJ46MwJ9wiefkHz2ho90NUyWZO7Y42Z19sq0OabNWdwgcLjKMY5cfOFEDFGhjL51VlfdOtaDN/JKkX6o5FKJuNLRIRhrwVGcQQUWmqM/E2J3LojEOXJMxe6q95BH9+V5ra3aQ== [email protected]
[[email protected] ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:A2:54:0A  
          inet addr:192.168.1.29  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fea2:540a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:32835 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9144 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:24448860 (23.3 MiB)  TX bytes:989133 (965.9 KiB)




scp: 利用ssh協議在主機之間實現安全文件傳輸的工具
scp SRC1... DEST


分兩種情形:

    1、源文件在本機,目標為遠程
    # scp /path/to/somefile... [email protected]:/path/to/somewhere
    2、源文件在遠程,本地為目標
    # scp [email protected]:/path/to/somewhere /path/to/somewhere
    
    -r: 復制目錄時使用,遞歸復制
    -p: 保持源文件的元數據信息,包括mode和timestamp,屬主,屬組信息
    -q: 靜默模式
    -P PORT: 指定ssh協議監聽的端口


sftp: 基於ssh的ftp服務
用法:sftp [email protected]

[[email protected] ~]# sftp 192.168.1.29
Connecting to 192.168.1.29...
reverse mapping checking getaddrinfo for bogon [192.168.1.29] failed - POSSIBLE BREAK-IN ATTEMPT!
sftp> ls
Desktop                                            Documents                                          Downloads                                          
Music                                              Pictures                                           Public                                             
Templates                                          Videos                                             anaconda-ks.cfg                                    
apache-tomcat-6.0.53.tar.gz                        bison-3.0                                          bison-3.0.tar.gz                                   
cmake-2.8.8                                        cmake-2.8.8.tar.gz                                 demo                                               
icbc_auto_platform                                 install.log                                        install.log.syslog                                 
jdk-8u131-linux-x64.rpm                            libevent-1.4.13-4.el6.x86_64.rpm                   libevent-devel-1.4.13-4.el6.x86_64.rpm             
libevent-doc-1.4.13-4.el6.noarch.rpm               libevent-headers-1.4.13-4.el6.noarch.rpm           main                                               
mariadb-5.5.44-linux-x86_64.tar.gz                 someTest                                           static                                             
tornado-3.1.0                                      tree-1.7.0.tgz                                     v3.1.0.tar.gz                                      
sftp>

openssh的服務器端:sshd
配置文件:/etc/ssh/sshd_config
服務腳本:/etc/rc.d/init.d/sshd
腳本配置文件:/etc/sysconfig/sshd

[[email protected] ~]# cat /etc/ssh/sshd_config 
# $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm 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:/bin:/usr/bin

# 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 change a
# default value.

#Port 22                       #監聽端口
#AddressFamily any
#ListenAddress 0.0.0.0         #ipv4監聽本地所有地址
#ListenAddress ::              #ipv6本地所有地址

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2                     #ssh版本,默認為sshV2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h    #密鑰生存時間
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m              #登陸超時時間
#PermitRootLogin yes            #是否允許管理員賬號直接登陸
#StrictModes yes                
#MaxAuthTries 6                 #最大嘗試次數
#MaxSessions 10                 #最大會話數

#RSAAuthentication yes                        #是否支持rsa認證
#PubkeyAuthentication yes                     #是否支持pubkey
#AuthorizedKeysFile .ssh/authorized_keys      #公鑰保存目錄 .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
# similar for protocol version 2
#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

# 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                               #GSSAPI認證
#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
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes                                                #DNS域名解析,使用no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server            #是否啟用sftp子系統   

# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand cvs server
[[email protected] ~]#


配置參數:
# man sshd_config


經常需要修改的參數:
Port: 修改默認監聽的端口
ListenAddress


sshd認證方式:
1、基於口令的認證;
2、基於密鑰的認證;
# ssh-keygen -t rsa
默認密鑰為id_rsa, id_rsa.pub


-f /path/to/somefile: 密鑰文件保存位置
-P ‘‘: 指定oldpassword


# ssh-copy-id -i .ssh/id_rsa.pub [email protected]


linux-openssh