ssh

檢視連線參數的設定
$ ssh -F ~/.ssh/config -G remote-host-name
user root
hostname 173.82.136.138
port 22
addressfamily any
batchmode no
canonicalizefallbacklocal yes
canonicalizehostname false
challengeresponseauthentication yes
checkhostip yes
compression no
...
複製主機 A 的公鑰檔 id_rsa.pub 至遠端主機上

指令一:從主機 A 上執行

ssh-copy-id user@remote-host-ip 
or
ssh-copy-id -f -i $HOME/.ssh/id_rsa.pub user@remote-host-ip

指令二:從主機 A 上執行

cat ~/.ssh/id_rsa.pub | ssh user@remote-host-ip "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"

從主機 B 上執行,以手動方式複製:

cd ~/.ssh
mv id_rsa.pub host-A-hostname.pub
cat host-A-hostname.pub >> authorized_keys
chmod 0700 ~/.ssh
chmod 0640 authorized_keys

NOTE:

如果 .ssh 目錄裡已經有 authorized_keys 檔案,可以另存一個檔名加上 2,例如 authorized_keys2

測試連線: 從主機 A 上執行

ssh <remote-userB>@<remote-hostB-name>

不需要輸入密碼就可以登入。

sshpass

整合 shell 做自動化的指令

1. ssh 執行指令

# Use the -p (this is considered the least secure choice and shouldn't be used)
sshpass -p !4u2tryhack ssh -o StrictHostKeyChecking=no username@host.example.com hostname

# Use the -f option (the password should be the first line of the filename)
echo '!4u2tryhack' >pass_file
chmod 0400 pass_file
sshpass -f pass_file ssh -o StrictHostKeyChecking=no username@host.example.com hostname

# Use the -e option (the password should be the first line of the filename)
SSHPASS='!4u2tryhack' sshpass -e ssh -o StrictHostKeyChecking=no username@host.example.com hostname

2. 整合 rsync

# Use -e
SSHPASS='!4u2tryhack' rsync --rsh="sshpass -e ssh -l username" /custom/ host.example.com:/opt/custom/

# Use -f
rsync --rsh="sshpass -f pass_file ssh -l username" /custom/ host.example.com:/opt/custom/

3. 整合 scp 

scp -r /var/www/html/example.com --rsh="sshpass -f pass_file ssh -l user" host.example.com:/var/www/html

4. With a GPG-encrypted file

echo '!4u2tryhack' > .sshpasswd
gpg -c .sshpasswd
rm .sshpasswd
gpg -d -q .sshpassword.gpg > pass_file; sshpass -f pass_file ssh user@srv1.example.com hostname
OTP - Google Authenticator
限制遠端登入
AllowUsers joe root@192.168.1.32 axer@163.* axer@120.109.* axer@2001:288:5400:*

# OR
AllowGroups ssh-users

 


Revision #8
Created Fri, Aug 21, 2020 8:27 PM by Admin
Updated Tue, Jan 5, 2021 3:20 AM by Admin