1. 程式人生 > >Linux初級:ssh服務及基於key驗證方法

Linux初級:ssh服務及基於key驗證方法

ssh

配置檔案:
/etc/ssh/ssh_config 客戶端
/etc/ssh/sshd_config 伺服器端

首次連線,系統自動會把公鑰從被連線考到發起連線主機,來做認證
    /etc/ssh/ssh_host_rsa_key.pub (被連線的主機)
    /root/.ssh/known_hosts (發起連線主機)
如更換機器IP一樣,清空known.hosts檔案即可

1、伺服器端更改預設埠22(我這裡port更改為6666)

[[email protected] ~]#vim /etc/ssh/sshd_config 
#       $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy 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

# 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 6666
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
"/etc/ssh/sshd_config" 139L, 3908C written

更改過後記得
systemctl reload ssdh
ss -ntl可檢視埠是否更改

2、指定埠連結 -p

[[email protected] ~]#ssh 192.168.32.61 -p 6666
[email protected]'s password: 
Last login: Thu Sep 13 21:35:55 2018 from 192.168.32.50
Dadda Up!

3、客戶端更改預設埠22(我這裡更改為6666,與伺服器同樣)

[[email protected] ~]#vim /etc/ssh/ssh_config 
#       $OpenBSD: ssh_config,v 1.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
    Port 6666
#   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 6666
#   Protocol 2,1
#   Cipher 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 "/etc/ssh/ssh_config" 59L, 2049C written

4、指定ip連結連結 -b

[[email protected] ~]#ssh -b 192.168.32.50 192.168.32.61
[email protected]'s password: 
Last login: Thu Sep 13 21:39:27 2018 from 192.168.32.50
Dadda Up!
[[email protected] ~]#

5、除錯模式 -v

[[email protected] ~]#ssh -v 192.168.32.61               
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 192.168.32.61 [192.168.32.61] port 6666.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/identity type -1
debug1: identity file /root/.ssh/identity-cert type -1
debug1: identity file /root/.ssh/id_rsa type -1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<2048<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: checking without port identifier
debug1: Host '192.168.32.61' is known and matches the RSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: found matching key w/out port
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
Cannot determine realm for numeric host address

debug1: Unspecified GSS failure.  Minor code may provide more information
Cannot determine realm for numeric host address

debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/identity
debug1: Trying private key: /root/.ssh/id_rsa
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: Next authentication method: password
[email protected]'s password: 
debug1: Authentication succeeded (password).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: client_input_global_request: rtype [email protected] want_reply 0
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
Last login: Thu Sep 13 21:46:10 2018 from 192.168.32.50
Dadda Up!
[[email protected] ~]#

6、用圖形介面開啟連線主機圖形介面 -x (windows可通過xshell中的xstar連線linux桌面)

[[email protected] ~]#ssh -X 192.168.32.61
[email protected]'s password: 
Last login: Thu Sep 13 22:12:05 2018 from 192.168.32.50
Dadda Up!
[[email protected] ~]#nm-connection-editor

7、強制偽tty分配 -t(通過192.168.32.68跳轉到192.168.32.77)

[[email protected] ~]#ssh -t 192.168.32.68 ssh 192.168.32.77

基於key驗證

1、發起連線主機生成祕鑰

[[email protected] ~]#cd .ssh
[[email protected] .ssh]#ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): dushan_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in dushan_rsa.
Your public key has been saved in dushan_rsa.pub.
The key fingerprint is:
SHA256:GmCdKdxjddHQxc0cfyawAyDh0weuKQIjBuMYaVhWzcs [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|=oo..oo.+.==.o.=.|
|*= . +oB o .oo. =|
|*o  =.X.o . o . +|
|oo . +E= .   . o.|
|  . . + S        |
|   . . o         |
|      .          |
|                 |
|                 |
+----[SHA256]-----+

2、把公鑰拷貝給需要連線的主機(預設生成/root/.ssh/authorized_keys檔案)

[[email protected] .ssh]#ssh-copy-id -i /root/.ssh/dushan_rsa.pub 192.168.32.50
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/dushan.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
[email protected]'s password: 

Number of key(s) added: 1

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

3、直接連線即可

[[email protected] .ssh]#ssh 192.168.32.50

4、設定或更改私鑰口令

[[email protected] .ssh]#ssh-keygen -p
Enter file in which the key is (/root/.ssh/id_rsa): dushan_rsa
Enter old passphrase: 
Enter new passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved with the new passphrase.

5、利用expect把公鑰推送到多臺主機
生成iplist.txt 檔案,把ip都填在裡面

#**************************************************************
#Author:                 Dadda_Du
#QQ:                     316722220     
#Date:                   2018-09-13    
#FileName:               ssh_push_key.sh
#URL:                     https://blog.csdn.net/weixin_40001704
#Description:             The script test
#Copyright(C):            2018 all rights reserved
#**************************************************************
pw="dushan"
rpm -q expect &> /dev/null || yum -y install expect
ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa
while read ip ; do
expect <<EOF
spawn ssh-copy-id i /root/.ssh/id_rsa.pub $ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$pw\n" }
}
expect eof
EOF
done < iplist.txt

6、在SecureCRT或Xshell實現基於key驗證

在SecureCRT工具—>建立公鑰—>生成Identity.pub檔案
轉化為openssh相容格式(適合SecureCRT,Xshell不需要轉化格式),
並複製到需登入主機上相應檔案authorized_keys中,
注意許可權必須為600,在需登入的ssh主機上執行:
ssh-keygen -i -f Identity.pub >> .ssh/authorized_keys

scp

常用選項:
-C 壓縮資料流
-r 遞迴複製
-p 保持原檔案的屬性資訊
-q 靜默模式
-P PORT 指明remote host的監聽的埠

[[email protected] ~]#scp /etc/fstab 192.168.32.50:/data
[email protected]'s password: 
fstab                                               100%  784     1.1MB/s   00:00

!!!大量重複檔案推薦用rsync,不要使用scp命令

rsync

選項:
-n 模擬複製過程
-v 顯示詳細過程
-r 遞迴複製目錄樹
-p 保留許可權
-t 保留時間戳
-g 保留組資訊
-o 保留所有者資訊
-l 將軟連結檔案本身進行復制(預設)
-L 將軟連結檔案指向的檔案複製
-a 存檔,相當於–rlptgoD,但不保留ACL(-A)和SELinux屬性(-X)

[[email protected] ~]#rsync -av /etc/sysconfig/ 192.168.32.50:/data
拷貝檔案帶/,把目錄下的檔案複製過去
[[email protected] ~]#rsync -av /etc/sysconfig 192.168.32.50:/data
拷貝檔案不帶/,把目錄複製過去

sftp

互動式檔案傳輸工具
用法和傳統的ftp工具相似
利用ssh服務實現安全的檔案上傳和下載
使用ls cd mkdir rmdir pwd get put等指令,可用?或help獲取幫助資訊
sftp [[email protected]]host
sftp> help

pssh

依賴epel源
yum install pssh

pssh是一個python編寫可以在多臺伺服器上執行命令的工具,也可實現檔案複製
選項:
--version:檢視版本
-h:主機檔案列表,內容格式”[[email protected]]host[:port]”
-H:主機字串,內容格式”[[email protected]]host[:port]”
-A:手動輸入密碼模式
-i:每個伺服器內部處理資訊輸出
-l:登入使用的使用者名稱
-p:併發的執行緒數【可選】
-o:輸出的檔案目錄【可選】
-e:錯誤輸入檔案【可選】
-t:TIMEOUT 超時時間設定,0無限制【可選】
-O:SSH的選項
-P:打印出伺服器返回資訊
-v:詳細模式

連線一臺執行命令hostanme
[[email protected] ~]#pssh -H 192.168.32.50 -A -i hostname

連線多臺,利用iplist.txt檔案
[[email protected] ~]#pssh -h iplist.txt -A -i hostname

連線多臺,分別建立dushan使用者(批量執行命令)
[[email protected] ~]#pssh -h iplist.txt -A -i "useradd dushan"

連線多臺,統一修改selinux檔案
[[email protected] ~]#pssh -h iplist.txt -A -i "sed -i 's/SELINUX=disabled/SELINUX=permissive/' /etc/selinux/config"

pscp.pssh

pscp.pssh功能是將本地檔案批量複製到遠端主機
選項
-v 顯示覆制過程
-r 遞迴複製目錄

將本地curl.sh 複製到/app/目錄
pscp.pssh -H 192.168.1.10 /root/test/curl.sh /app/
pscp.pssh -h host.txt /root/test/curl.sh /app/

將本地多個檔案批量複製到/app/目錄
pscp.pssh -H 192.168.1.10 /root/f1.sh /root/f2.sh /app/

將本地目錄批量複製到/app/目錄
pscp.pssh -H 192.168.1.10 -r /root/test/ /app/

pslurp

pslurp功能是將遠端主機的檔案批量複製到本地
選項
-L 指定從遠端主機下載到本機的儲存的目錄,local是下載到本地後的名稱
-r 遞迴複製目錄

批量下載目標伺服器的日誌檔案至/data下,並更名為m
pslurp -h iplist.txt -L /data /var/log/messages m