Linux ssh命令詳解


       SSH(遠程連接工具)連接原理:ssh服務是一個守護進程(demon),系統后台監聽客戶端的連接,ssh服務端的進程名為sshd,負責實時監聽客戶端的請求(IP 22端口),包括公共秘鑰等交換等信息。

ssh服務端由2部分組成: openssh(提供ssh服務)    openssl(提供加密的程序)

ssh的客戶端可以用 XSHELL,Securecrt, Mobaxterm等工具進行連接

SSH的工作機制 

      服務器啟動的時候自己產生一個密鑰(768bit公鑰),本地的ssh客戶端發送連接請求到ssh服務器,服務器檢查連接點客戶端發送的數據和IP地址,確認合法后發送密鑰(768bits)給客戶端,此時客戶端將本地私鑰(256bit)和服務器的公鑰(768bit)結合成密鑰對key(1024bit),發回給服務器端,建立連接通過key-pair數據傳輸。       

SSH的加密技術

加密技術:傳輸過程,數據加密。            
1.SSH1沒有對客戶端的秘鑰進行校驗,很容易被植入惡意代碼
2.SSH2增加了一個確認聯機正確性的Diffe_Hellman機制,每次數據的傳輸,Server都會檢查數據來源的正確性,避免黑客入侵。                   
  SSH2支持RSA和DSA密鑰   
        DSA:digital signature Algorithm  數字簽名
        RSA:既可以數字簽名又可以加密      

SSH知識小結           

   1.SSH是安全的加密協議,用於遠程連接Linux服務器               
   2.SSH的默認端口是22,安全協議版本是SSH2               
   3.SSH服務器端主要包含2個服務功能SSH連接和SFTP服務器               
   4.SSH客戶端包含ssh連接命令和遠程拷貝scp命令等 

如何防止SSH登錄入侵            

    1.密鑰登錄,更改端口               
    2.牤牛陣法               
    3.監聽本地內網IP(ListenAddress 192.168.25.*)

SSH功能大全   

 1.登錄                    
        ssh -p22 omd@192.168.25.137                
    2.直接執行命令  -->最好全路徑                    
        ssh root@192.168.25.137 ls -ltr /backup/data                        
            ==>ssh root@192.168.25.137 /bin/ls -ltr /backup/data                
    3.查看已知主機                     
         cat /root/.ssh/known_hosts 
    4.ssh遠程執行sudo命令
        ssh -t omd@192.168.25.137 sudo rsync hosts /etc/

    5.scp                
              1.功能   -->遠程文件的安全(加密)拷貝                    
                  scp -P22 -r -p /home/omd/h.txt omd@192.168.25.137:/home/omd/                
              2.scp知識小結                    
                  scp是加密遠程拷貝,cp為本地拷貝                    
                  可以推送過去,也可以拉過來                    
                  每次都是全量拷貝(效率不高,適合第一次),增量拷貝用rsync

    6.ssh自帶的sftp功能                
              1.Window和Linux的傳輸工具                    
                   wincp   filezip                    
                sftp  -->基於ssh的安全加密傳輸                    
                samba    
              2.sftp客戶端連接                    
                 sftp -oPort=22 root@192.168.25.137                    
                 put /etc/hosts /tmp                    
                 get /etc/hosts /home/omd    
             3.sftp小結:                    
                 1.linux下使用命令: sftp -oPort=22 root@x.x.x.x                    
                 2.put加客戶端本地路徑上傳                   
                 3.get下載服務器端內容到本地                    
                 4.遠程連接默認連接用戶的家目錄

 

ssh常見命令參數

usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-e escape_char] [-F configfile]
           [-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]

關於后台ssh服務的相關

# 查詢openssl軟件
	rpm -qa openssh openssl
# 查詢sshd進程
	ps -ef | grep ssh
        --> /usr/sbin/sshd
# 查看ssh端口
	netstat -lntup | grep ssh   
	ss | grep ssh                (效果同上,同下,好用)
	netstat -a | grep ssh(記住這個)
	netstat -lnt | grep 22    ==>  查看22端口有沒有開/ssh服務有沒有開啟
    技巧: netstat -lnt | grep ssh | wc -l -->只要大於2個就是ssh服務就是好的
# 查看ssh的秘鑰目錄
    ll /root/.ssh/known_hosts  # 當前用戶家目錄的.ssh目錄下
# ssh的配置文件
	cat /etc/ssh/sshd_config 	
# ssh服務的關閉
	service sshd stop
# ssh服務的開啟:
	service sshd start
# ssh服務的重啟
	service sshd reload    [停止進程后重啟] ==> 推薦
	service sshd restart   [干掉進程后重啟] ==> 不推薦
# ssh遠程登錄
	ssh 192.168.1.100      # 默認利用當前宿主用戶的用戶名登錄
	ssh omd@192.168.1.100  # 利用遠程機的用戶登錄
	ssh omd@192.168.1.100  -o stricthostkeychecking=no # 首次登陸免輸yes登錄
	ssh omd@192.168.1.100 "ls /home/omd"  # 當前服務器A遠程登錄服務器B后執行某個命令
	ssh omd@192.168.1.100 -t "sh /home/omd/ftl.sh"  # 當前服務器A遠程登錄服務器B后執行某個腳本

 

image

ssh免密設置

1、進入用戶的家目錄

[root@localhost ~]# cd /root/.ssh/             【root用戶就在root目錄下的.ssh目錄】
[root@localhost ~]# cd /home/omd/.ssh/   【普通用戶就是在家目錄下的.ssh目錄】

image

2、根據DSA算法生成私鑰和公鑰【默認建立在當前用戶的家目錄】

 [root@localhost .ssh]# ssh-keygen -t dsa     # 一路回車即可
                 id_dsa         -->私鑰(鑰匙) 
                 id_dsa.pub     -->公鑰(鎖)

image

3.拷貝公鑰給目標服務器

[root@localhost .ssh]# ssh-copy-id -i id_dsa.pub omd@192.168.25.110              【 使用ssh登錄的默認端口22】
[root@localhost .ssh]# ssh-copy-id -i id_dsa.pub –p 666 omd@192.168.25.120   【使用ssh登錄設置的端口666】

4. 查看目標服務器生成的文件

[omd@localhost .ssh]$ ll /home/omd/.ssh/authorized_keys

image

5. 免密碼登錄目標服務器

ssh omd@192.168.25.110  

6. 總結一下鑰匙和鎖的關系

1.多個鑰匙開一把鎖
      把id_dsa.pub 復制給各個服務器

2.一個鑰匙開duobasuo
      把id_dsa 傳給各個服務器
      把id_dsa 傳給自己  

ssh排查問題

1.判斷物理鏈路是否通  ping 192.168.25.130     線路 | 防火牆 | 是否同一個網的
            ping   本身是icmp協議
2.判斷服務是否正常
telnet 192.168.25.130 22
3.Linux防火牆
 service iptables status ==>  /etc/init.d/iptables status  
4.打開ssh的調測進行觀察
ssh -vvv omd@192.168.1.100

SSH批量分發與管理方案小結


1.利用root做ssh key驗證

優點:簡單,易用
    缺點:安全性能差,無法禁止root遠程連接


2.利用普通用戶omd                -->推薦


    思路:把要分發的文件拷貝到服務器用戶的家目錄,然后利用sudo提權拷貝分發的文件和對應目錄
    優點:安全
    缺點:復雜,配置麻煩
    1.sudo提權
        echo 'omd     All=(All)      NOPASSWD:/usr/bin/rsync' >> /etc/sudoers
        visudo -c
        grep omd /etc/sudoers
    2.ssh分發到服務器的家目錄
        ssh -p22 -r /etc/hosts omd@192.168.25.137:~
    3.ssh使用sudo復制到目標服務器的/etc
        ssh -t omd@192.168.25.137 sudo rsync hosts /etc/

3.拓展方案2,不用sudo,而是設置suid對固定命令提權

 優點:相當安全
       缺點:復雜,安全性較差,任何人都可以處理帶有suid權限的命令
       1.which rsync
       2.chmod 4755 /usr/bin/rsync       

ssh章節小結             

    1.ssh遠程的加密連接協議,相關軟件openssh,openssl               
    2.默認端口22               
    3.ssh版本協議               
    4.服務器ssh連接,ftp連接,sshd守護進程,開機啟動               
    5.ssh客戶端重要命令:ssh(用戶登錄&&遠程命令),scp,sftp,               
    6.安全驗證方式:口令,密鑰  學習原理               
    7.ssh服務優化:改端口,改監聽,no root,no empty,no DNS,
    8.ssh密鑰對,公鑰在服務器端,私鑰在客戶端

修改ssh服務的啟動文件sshd的幾個點

    1-1修改 /etc/ssh/sshd_config
GSSAPIAuthentication yes 解決一台服務器管理多個ssh服務 UseDNS no 加快響應速度因為在內網環境下 PermitRootLogin no 不運行root用戶直接登錄 Port 11544 更改訪問端口號 ListenAddress 192.168.25.130 只監聽內網的IP Match User anoncvs 當前環境允許登錄的用戶 PermitRootLogin no 是否允許root用戶登錄,一般不允許開 1-2重啟服務 service sshd restart 寫入命令進內存 service sshd reload(優先) reload是一個平滑的訪問,不影響用戶使用 1-3查看連接端口 netstat -an | grep EST

SSH跳過HostKeyChecking,不用輸入yes

SSH跳過輸入ssh跳過RSA key fingerprint輸入yes/no

在配置大量的節點之間需要ssh連通的時候,如果自動復制很多節點,都需要輸入yes,兩兩節點之間都要互通一次,這樣會造成很大的麻煩

解決1;修改配置文件/etc/ssh/ssh_config

找  到  # StrictHostKeyChecking ask  
修改為:StrictHostKeyChecking no  

解決2: 添加參數 –o  【o=option】

ssh root@192.168.25.133 -o "StrictHostKeyChecking no"

scp -o "StrictHostKeyChecking no" newfile.txt root@192.168.25.133:/root

ssh帶密碼登錄之sshpass的安裝

【下載地址】https://sourceforge.net/projects/sshpass/files/latest/download

上傳文件到服務器

CentOS下安裝:

[root@localhost ~]# tar xf sshpass-1.06.tar.gz 
[root@localhost ~]# cd sshpass-1.06
[root@localhost sshpass-1.06]# ./configure 
[root@localhost sshpass-1.06]# make && make install

檢查是否安裝成功:

[root@localhost sshpass-1.06]# which sshpass
/usr/local/bin/sshpass

遠程登錄主機:

 sshpass -p FTL600@HH ssh omd@192.168.25.110 -o "StrictHostKeyChecking no"

注意:如果是第一次登錄,需要輸入手動yes,此時sshpass並不會給提示,所以登錄異常

Ubuntu下安裝方法一[推薦]:簡單

omd@omd-virtual-machine:~/sshpass-1.06$ sudo apt install sshpass  

安裝成功:

omd@omd-virtual-machine:~/sshpass-1.06$ which sshpass

Ubuntu下安裝方法二:

omd@omd-virtual-machine:~$ tar xf sshpass-1.06.tar.gz 
omd@omd-virtual-machine:~$ cd sshpass-1.06/
omd @omd-virtual-machine:~/sshpass-1.06$ ./configure 
omd@omd-virtual-machine:~/sshpass-1.06$ sudo make && make install
其同CentOS下安裝

 

附ssh的配置文件

/etc/ssh/sshd_config
[root@localhost .ssh]# 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
#ListenAddress ::

# 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

# 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
#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
# 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
#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
#PidFile /var/run/sshd.pid
#MaxStartups 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM