1. Practice#
-
Write a script to batch add users, with usernames starting with "user". The specific number of users to be added is determined by user input, and a random password (12 random characters) is set for each user. Record the created users and passwords, saving them to the /tmp/user file.
-
How to concatenate two strings, sum two integers, and divide 5 by 3, keeping two decimal places?
-
How to calculate how many users are on the local machine and how many are regular users?
-
How to remove all spaces from a string?
-
Backup the /var/log/nginx/access.log log every five minutes, naming it in the format 2020-11-15_10_05-access.log.tar.gz. Place the backup log files in the /nginx/ directory.
-
Find files in the /etc/ directory that were modified more than 3 days ago but within the last 10 days, and record these files in the /tmp/etc_log file.
1.1 Write a script to batch add users, with usernames starting with "user". The specific number of users to be added is determined by user input, and a random password (12 random characters) is set for each user. Record the created users and passwords, saving them to the /tmp/user file.#
Question 1: Write a script to batch add users, with usernames starting with "user". The specific number of users to be added is determined by user input, and a random password (12 random characters) is set for each user. Record the created users and passwords, saving them to the /tmp/user file.
Example 1
---------------------------------------------------------------------
read -p "Please enter the number of users you want to add: " num1
for i in `seq $num1` # Note: Loop how many times
do
id user$i &>/dev/null
a=`echo $?` # Note: The return value of the previous command 0 success non-0 failure
str1=`date +%s+%N | md5sum|head -c 4` # Note: %s timestamp
if [ $a -eq 0 ] ;then
echo "This user already exists, no new creation operation"
break
else
useradd user$str1$i &>/dev/null
b=`echo $?`
if [ $b -eq 0 ];then
echo "Creation successful"
passwd1=`mkpasswd -l 12` # Note: mkpasswd generates a random 12-character password string
echo $passwd1 |passwd user$str1$i --stdin &>/dev/null # Note: --stdin password comes from standard input
echo "user$str1$i:$passwd1" >>/tmp/user
else
echo "Creation failed"
fi
fi
done
---------------------------------------------------------------------
[root@cPen_web lianxi]# date +%s+%N # Note: Referencing the concept of nanoseconds to prevent username duplication
1605251515+012657467
[root@cPen_web lianxi]# man date
%% a literal %
%a locale's abbreviated weekday name (e.g., Sun) # Note: Sun
%A locale's full weekday name (e.g., Sunday) # Note: Sunday
%s seconds since 1970-01-01 00:00:00 UTC # Note: Timestamp from January 1, 1970 to now in seconds
%N nanoseconds (000000000..999999999) # Note: Nanoseconds 1 nanosecond = one billionth of a second
[root@cPen_web ~]# date +%s+N | md5sum|head -c 4
2b13[root@cPen_web ~]#
Example 2
---------------------------------------------------------------------
read -p "Enter the number of new users:" num
for i in `seq $num`
do
useradd user$i &>/dev/null
passwd=`mkpasswd -l 12`
echo $passwd |passwd user$i --stdin &>/dev/null
echo "Username:user$i" "Password:$passwd" &>>/tmp/user
done
1.2 How to concatenate two strings, sum two integers, and divide 5 by 3, keeping two decimal places?#
Question 2: How to concatenate two strings, sum two integers, and divide 5 by 3, keeping two decimal places?
Numerical operations: https://blog.csdn.net/weixin_34408624/article/details/92598137
Note: Write together to achieve concatenation of 2 strings#
Example
---------------------------------------------------------------------
[root@cPen_web ~]# a=abc
[root@cPen_web ~]# b=def
[root@cPen_web ~]# echo $a$b # Note: String concatenation
abcdef
[root@cPen_web ~]# echo abc$a
abcabc
[root@cPen_web ~]# a=3
[root@cPen_web ~]# b=4
[root@cPen_web ~]# echo $(($a+$b))
7
# Note: 1 parenthesis defaults to string concatenation, no numerical operation
[root@cPen_web ~]# a=123 # Note: Defaults are str type
[root@cPen_web ~]# a="123"
[root@cPen_web ~]# a='123'
------------------------------------------------------------
[root@cPen_web ~]# a=123
[root@cPen_web ~]# b=4
[root@cPen_web ~]# echo $(( $a > $b ))
1 # Note: Correct returns 1
[root@cPen_web ~]# echo $(( $a < $b ))
0 # Note: Incorrect returns 0
[root@cPen_web ~]# expr $a + $b # Note: expr command performs numerical operations
127
[root@cPen_web ~]# echo $(( $a + $b )) # Note: 2 parentheses achieve integer operations
127
[root@cPen_web ~]# echo $[ $a + $b ] # Note: Square brackets achieve integer operations
127
[root@cPen_web ~]# let c=$a+$b # Note: let can also achieve integer operations
[root@cPen_web ~]# echo $c # Note: let can only copy, cannot directly assign
# Note: Integer operations: 4 methods
[root@cPen_web ~]# expr $a + $b
[root@cPen_web ~]# echo $(( $a + $b ))
[root@cPen_web ~]# echo $[ $a + $b ]
[root@cPen_web ~]# let c=$a+$b # Note: let can only copy, cannot directly assign
Numerical operations: https://blog.csdn.net/weixin_34408624/article/details/92598137
------------------------------------------------------------------------
# Note: Decimal operations
echo "scale=3;5/3"|bc # Note: 3 means keep 3 decimal places 5/3
[root@cPen_web ~]# echo "scale=3;5/3"|bc # Note: Ensure bc is installed on the host
1.666
[root@cPen_web lianxi]# echo $((5/3))
1
[root@cPen_web lianxi]# echo |awk '{printf 5/3}' # Note: awk defaults to keep 5 decimal places
1.66667[root@cPen_web lianxi]#
[root@cPen_web lianxi]# echo |awk '{printf "%.2f",5/3}' # Note: Keep 2 decimal places
1.67[root@cPen_web lianxi]#
Numerical operations: https://blog.csdn.net/weixin_34408624/article/details/92598137
1.3 How to calculate how many users are on the local machine and how many are regular users?#
Question 3: How to calculate how many users are on the local machine and how many are regular users?
Example
---------------------------------------------------------------------
#3. How to calculate how many users are on the local machine and how many are regular users?
wc -l /etc/passwd # Note: How many users on the local machine
awk -F":" '$3>=1000{print $1}' /etc/passwd |wc -l # Note: How many regular users on the local machine
# Note: Regular users uid>1000
1.4 How to remove all spaces from a string?#
Question 4: How to remove all spaces from a string?
Example
---------------------------------------------------------------------
str="s t r i n g"
echo $str |tr -d " " # Note: -d deletes specified characters
1.5 Backup the /var/log/nginx/access.log log every five minutes, naming it in the format 2020-11-15_10_05-access.log.tar.gz. Place the backup log files in the /nginx/ directory.#
Question 5: Backup the /var/log/nginx/access.log log every five minutes, naming it in the format 2020-11-15_10_05-access.log.tar.gz. Place the backup log files in the /nginx/ directory.
Note: Ensure crontab is open#
Example
---------------------------------------------------------------------
[root@cPen_web ~]# crontab -e # Note: It's best to write absolute paths in scheduled tasks
*/5 * * * * tar czf /nginx/$(date +%Y-%m-%d_%H_%M-access.log.tar.gz) /var/log/nginx/access.log
1.6 Find files in the /etc/ directory that were modified more than 3 days ago but within the last 10 days, and record these files in the /tmp/etc_log file.#
Question 6: Find files in the /etc/ directory that were modified more than 3 days ago but within the last 10 days, and record these files in the /tmp/etc_log file.
Example
---------------------------------------------------------------------
[root@cPen_web ~]# find /etc -type f -mtime -10 -mtime +3 # Note: Note: This is to find files
/etc/dnf/modules.d/python27.module
/etc/selinux/config
/etc/vsftpd/vsftpd.conf
/etc/dconf/db/site
/etc/dconf/db/local
/etc/dconf/db/distro
[root@cPen_web ~]# stat /etc/selinux/config # Note: stat views the original information of the file
………………
Last accessed: 2020-11-13 10:14:37.388001468 +0800
Last changed: 2020-11-05 15:12:05.484883965 +0800
Last modified: 2020-11-05 15:12:05.485883965 +0800
[root@cPen_web lianxi]# find /etc -type f -mtime -10 -mtime +3 &>/tmp/etc_log
2. Practice#
Please write a simple rock-paper-scissors game in shell, with enumerated values (0 for rock, 1 for scissors, 2 for paper). There are two players, rob1 and rob2, whose moves are automatically enumerated by the system, and play ten rounds in total, finally giving the results of the ten rounds.
Example 1: Determine various situations using if statements
---------------------------------------------------------------------
#!/bin/bash
echo "The rock-paper-scissors game begins!!!"
echo "Today our two opponents are rob1 and rob2"
pingju=0
rob1_win=0
rob2_win=0
for i in `seq 10`
do
a=`echo $[RANDOM%3]`
b=`echo $[RANDOM%3]`
case $a in
0)
c=rob1 chose rock
;;
1)
c=rob1 chose scissors
;;
2)
c=rob1 chose paper
;;
esac
case $b in
0)
d=rob2 chose rock
;;
1)
d=rob2 chose scissors
;;
2)
d=rob2 chose paper
;;
esac
if (($a==$b));then
echo -e "$c\n$d \nThey tied"
pingju=$[$pingju+1]
continue
fi
if [[ $a -eq 1 || $b -eq 1 ]];then # Note: If player 1 chose paper
if [[ $a -eq 0 || $b -eq 0 ]];then # Note: If player 1 chose rock
if (($a>$b));then
echo -e "$c\n$d, rob2 wins"
rob2_win=$[$rob2_win+1]
continue
else
echo -e "$c\n$d, rob1 wins"
rob1_win=$[$rob1_win+1]
continue
fi
fi
fi
if (($a>$b));then
echo -e "$c\n$d, rob1 wins"
rob1_win=$[$rob1_win+1]
else
echo -e "$c\n$d, rob2 wins"
rob2_win=$[$rob2_win+1]
fi
done
echo "rob1 wins $rob1_win times, rob2 wins $rob2_win times, ties $pingju
============================================================================================
Example 2: Using subtraction
# Note: Using if statements
---------------------------------------------------------------------
for i in `seq 10`
do
rob1=$(($RANDOM%3))
echo rob1=$rob1
rob2=$(($RANDOM%3))
echo rob2=$rob2
if [ $rob1 -eq $rob2 ]
then
echo "Tie"
elif [ $(($rob1-$rob2)) -eq -1 ] || [ $(($rob1-$rob2)) -eq 2 ] # Note: rob1 wins
then
echo "rob1 wins"
else
echo "rob2 wins"
fi
done
============================================================================================
Example 3
---------------------------------------------------------------------
r1_win=0
r2_win=0
equal=0
for i in `seq 10`
do
echo -ne "Round $i\t"
rob1_res=$(($RANDOM%3))
rob2_res=$(($RANDOM%3))
if [[ $(($rob1_res - $rob2_res)) = -1 ]]; then echo -ne "rob1 wins\t" &&r1_win=$(($r1_win + 1)); fi
if [[ $(($rob1_res - $rob2_res)) = 2 ]]; then echo -ne "rob1 wins\t" &&r1_win=$(($r1_win + 1)); fi
if [[ $(($rob2_res - $rob1_res)) = -1 ]]; then echo -ne "rob2 wins\t" &&r2_win=$(($r2_win + 1)); fi
if [[ $(($rob2_res - $rob1_res)) = 2 ]]; then echo -ne "rob2 wins\t" &&r2_win=$(($r2_win + 1)); fi
if [[ $(($rob1_res - $rob2_res)) = 0 ]]; then echo -ne "Tie\t" && equal=$(($equal + 1)); fi
[[ $rob1_res = 0 ]] && echo -ne "rob1: rock\t"
[[ $rob1_res = 1 ]] && echo -ne "rob1: scissors\t"
[[ $rob1_res = 2 ]] && echo "rob1: paper\t\t"
[[ $rob2_res = 0 ]] && echo "rob2: rock"
[[ $rob2_res = 1 ]] && echo "rob2: scissors"
[[ $rob2_res = 2 ]] && echo "rob2: paper"
done
echo "rob1 wins: $r1_win"
echo "rob2 wins: $r2_win"
echo "Number of ties: $equal"
Example 4: Generate a random number within 3, excluding 3
---------------------------------------------------------------------
# Note: Generate a random number within 3, excluding 3
[root@cPen_web lianxi]# echo $[RANDOM%3]
2
[root@cPen_web lianxi]# echo $[RANDOM%3]
1
[root@cPen_web lianxi]# echo $[RANDOM%3]
0
SSH Service
3. Introduction to SSH Service#
Remote Shell Application
- Allows users to execute any command on a remote machine
- Redirects standard output to local
- Early plaintext remote protocol: telnet
SSH (Secure Shell)
- Provides a secure shell environment for clients for remote management
- Default port: TCP
22
SSH is based on public key encryption (asymmetric encryption) technology
- Data is encrypted during transmission
- Authentication of client and server
Note: Port 23 is plaintext and has been phased out#
.--------------------------------------------------------------------------------------------------------------
What is ssh?
ssh --> secure shell
remote login program -- remote login mode
A service that encrypts data transmission, mainly used for remote login
Note: Putting data into an encrypted shell is a secure protocol#
.--------------------------------------------------------------------------------------------------------------
The ssh protocol is an application layer protocol, and the service implemented based on the ssh protocol is called the ssh service.
The ssh service is mainly available on HP-UX, LINUX, AIX, and UNIX systems (Unix-like systems), and is not available on Windows.
Note: The ftp protocol is also an application layer protocol, and the service implemented based on the protocol is called the ftp service.#
.--------------------------------------------------------------------------------------------------------------
Two common login methods for ssh:
-
Password login
-
Key login (passwordless login) # Note: No password required
Note: To log into a host, you need to know the host's IP, be allowed to log in, and have a network connection to access that host.#
Note: The default port for ssh service is port 22, which can be changed.#
.--------------------------------------------------------------------------------------------------------------
Note: /etc/services
can view the default port numbers for common services#
[root@cPen_web lianxi]# less /etc/services
ssh 22/tcp # The Secure Shell (SSH) Protocol
ssh 22/udp # The Secure Shell (SSH) Protocol
# Note: Generally, ssh uses tcp for transmission
.--------------------------------------------------------------------------------------------------------------
Note: Because all its data is encrypted, it is considered a secure shell.#
Note: Data exchange between two hosts involves packet transmission.#
Note: Making a request to another service is essentially sending a packet to it, which contains the request.#
Note: Normally, if not encrypted, the information is in plaintext and is not secure; the ssh service encrypts the data, so only host A and host B know how to decrypt it, while others do not.#
Note: After installing the system (minimum installation), the ssh service is generally included and usually starts automatically with the system.#
.--------------------------------------------------------------------------------------------------------------
Example: Check if the ssh service is running
---------------------------------------------------------------------------------
1. Check the process
[root@cPen_web lianxi]# ps ef |grep ssh # Note: The process name is sshd
2. pidof sshd # Note: Determine if a service has a pid
[root@cPen_web lianxi]# pidof sshd # Note: If the service is running, there must be a pid
2545 2543 2542 2538 2537 2536 909
# There must be a pid if the service is running
3. Check the network connection listening status using netstat
# Note: yum install net-tools
[root@cPen_web lianxi]# netstat -atpl |grep ssh # Note: a all; t tcp; p port
[root@cPen_web lianxi]# netstat -atpln |grep ssh
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 909/sshd
# Note: listen status indicates it is listening, meaning others can connect to me
tcp 0 0 192.168.0.21:22 192.168.0.42:58697 ESTABLISHED 2536/sshd: root [pr
# Note: ESTABLISHED indicates a connection has been established and data exchange can occur.
tcp 0 36 192.168.0.21:22 192.168.0.42:58698 ESTABLISHED 2537/sshd: root [pr
tcp6 0 0 :::22 :::* LISTEN 909/sshd
# Note: 0.0.0.0:22 indicates listening on port 22 on all IPs of the local machine (anyone can access through any IP). If it is set to listen on 192.168.0.135/24, then others can only access me through address 135.
# Note: listen status indicates the service is up and listening, meaning others can connect to me.
# Note: establish indicates a client has connected to me (the connection has been established).
# Note: 0.0.0.0:* indicates allowing any IP, any port client to connect (the * represents any port client).
# Note: 0.0.0.0:22 indicates all IPs on the local machine (on the local machine).
# Note: 0.0.0.0:* indicates allowing any IP, any port client to connect (any port client).
------------------------------------------------------------------------------------------------------
# Note: The local loopback address represents the local machine, testing if the network card is okay 127.0.0.1/8 local loopback address
# Note: Actual network card address 192.168.0.21/24
# Note: Others cannot access through 127.0.0.1 because 127.0.0.1 represents local; every machine has a 127.0.0.1 local loopback address, and accessing through 127.0.0.1 only accesses itself.
4. lsof -i:22 # Note: Check if there is a listening state; establish indicates a connection has been established.
# Note: Knowing the port allows checking the port.
# Note: lsof --> list open file (full name)
[root@cPen_web ~]# lsof -i:22
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 908 root 4u IPv4 27707 0t0 TCP *:ssh (LISTEN) # Note: listen status
sshd 908 root 6u IPv6 27721 0t0 TCP *:ssh (LISTEN) # Note: ESTABLISHED connection
sshd 1419 root 5u IPv4 29943 0t0 TCP cPen_web:ssh->10.112.68.22:49959 (ESTABLISHED)
sshd 1421 root 5u IPv4 29943 0t0 TCP cPen_web:ssh->10.112.68.22:49959 (ESTABLISHED)
=============================================================================================
Example: Add an IP address
[root@cPen_web lianxi]# ip a add 192.168.0.144/24 # Note: Add an IP address
[root@cPen_web lianxi]# ip add # Note: It's best to keep it in the same subnet
inet 127.0.0.1/8 scope host lo # Note: dev ens3 device ens33
inet 192.168.0.21/24 brd 192.168.0.255 scope global dynamic noprefixroute ens33
inet 192.168.0.144/24 scope global secondary ens33
=============================================================================================
Example: Check which package the command belongs to
[root@cPen_web lianxi]# which netstat # Note: Find the absolute path of the command
/usr/bin/netstat
[root@cPen_web lianxi]# rpm -qf /usr/bin/netstat # Note: Check which package this absolute path executable file belongs to
net-tools-2.0-0.51.20160912git.el8.x86_64
4. Key Login#
[root@cPen_web ~]# ssh-keygen # Note: Create a key pair
Generating public/private rsa key pair. # Note: RSA algorithm generates a pair of public and private keys (two keys, not the same)
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
SHA256:JZh0IhlTUDkIvuXuv7Iw7zYsoucwfLjpPWrHYN7P63g root@cPen_web
The key's randomart image is:
+---[RSA 2048]----+
| ..=B=.. |
| . o+o= |
| . . o.. . |
| + o |
| . . S |
|.o.. |
|=o*o. |
|.=BXBE |
|=O+*XX+. |
+----[SHA256]-----+
[root@cPen_web ~]#
Encryption
-
Symmetric Encryption
Encryption and decryption use the same key.
How to securely store this password, this key is shared between the machines that need encryption.
It is difficult to ensure that this key is not leaked.
-
Asymmetric Encryption # Note: The keys for encryption and decryption are different.
Generate a pair of public and private keys, keep the private key safe, and the public key can be given to others.
The public and private keys exist as a pair; one is used for encryption, and the other for decryption. Which is the private key and which is the public key depends on the user's management.
Note:
Use the public key for encryption and the private key for decryption, mainly for data encryption.
Use the private key to encrypt and the public key to decrypt, mainly for authentication.
[root@cPen_web ~]# ssh-keygen # Note: Create a key pair
Generating public/private rsa key pair. # Note: RSA algorithm generates a pair of public and private keys (two keys, not the same)
Enter file in which to save the key (/root/.ssh/id_rsa): # Note: Path to store public and private keys, for root user
Enter passphrase (empty for no passphrase): # Note: Set key password # Note: Not global
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:
SHA256:JZh0IhlTUDkIvuXuv7Iw7zYsoucwfLjpPWrHYN7P63g root@cPen_web # Note: Algorithm hash algorithm
The key's randomart image is: # Note: Information digest uses SHA256 hash algorithm
+---[RSA 2048]----+
| ..=B=.. |
| . o+o= |
| . . o.. . |
| + o |
| . . S |
|.o.. |
|=o*o. |
|.=BXBE |
|=O+*XX+. |
+----[SHA256]-----+
[root@cPen_web ~]#
# Note: Hash algorithm maps an input of any length to a fixed-length output
--------------------------------------------------------------------------------------------
# Note: Encryption is divided into 2 methods: 1. Symmetric encryption; 2. Asymmetric encryption
# Note: Symmetric encryption: Machine A sends something to Machine B, both A and B know a password called aa; Machine A encrypts date using aa, and Machine B uses aa to decrypt. Both machines know the same key, and the condition is that both A and B know what the key is and it is the same.
# Note: Problem: Cannot ensure the key is not known by others.
# Note: Asymmetric encryption: Machine A and Machine B perform data encryption transmission (communication). Machine A generates a public and private key pair locally, keeps both keys on Machine A, and sends the public key to Machine B (it can also send the public key to Machine C; the public key can be given to anyone). However, only Machine A knows the private key. Machine B uses the public key given by Machine A to encrypt, and Machine A receives it and decrypts it using the private key.
The only key that can decrypt is the private key, which only Machine A has, so only Machine A can decrypt.
# Note: For data information encryption, use the public key for encryption and the private key for decryption; only Machine A can decrypt.
# Note: Asymmetric encryption is used for data encryption when using the public key for encryption and the private key for decryption.
5. SSH Configuration#
SSH Configuration
Directory: /etc/ssh # Note: All SSH configuration files are stored here
[root@cPen_web ~]# cd /etc/ssh/
[root@cPen_web ssh]# ls
moduli sshd_config ssh_host_ecdsa_key.pub ssh_host_ed25519_key.pub ssh_host_rsa_key.pub
ssh_config ssh_host_ecdsa_key ssh_host_ed25519_key ssh_host_rsa_key
# Note: sshd_config is the client configuration file
# Note: ssh_config is the server configuration file
# Note: ssh_host_ecdsa_key and ssh_host_ecdsa_key.pub are a pair of public and private keys
# Note: ssh_host_ecdsa_key.pub is the public key, and ssh_host_ecdsa_key is the private key
# Note: When the ssh service starts, it automatically creates a pair of public and private keys
Example: The created public and private keys are stored in the /root/.ssh/ directory by default
[root@cPen_web ~]# cd .ssh
[root@cPen_web .ssh]# ls
id_rsa id_rsa.pub known_hosts
# Note: id_rsa private key
# Note: id_rsa.pub public key
6. Implement Public Key Authentication (Passwordless Login)#
# Note: On machine A (after generating the public key)
[root@cPen_web ~]# cd .ssh
[root@cPen_web .ssh]# ls
id_rsa id_rsa.pub known_hosts
[root@cPen_web .ssh]# cat id_rsa.pub
ssh-rsa
AAAAB3NhQX......jXDv87iERv/z9XepKCeYqCfF2Dvv0n/g+IeFmzhW0iOppExskimMPGGWcN+7rXWlwaLNTiknmSTl+mFvZV8uIY5DnQXv root@cPen_web
# Note: On machine B
[root@cPen_web ~]# mkdir .ssh # Note: Create .ssh folder if it doesn't exist
[root@cPen_web ~]# cd .ssh/
[root@cPen_web .ssh]# ls
known_hosts
[root@cPen_web .ssh]# vim authorized_keys # Note: Create the authorized_keys file
ssh-rsa # Note: Paste the public key from machine A
AAAAB3NhQX......jXDv87iERv/z9XepKCeYqCfF2Dvv0n/g+IeFmzhW0iOppExskimMPGGWcN+7rXWlwaLNTiknmSTl+mFvZV8uIY5DnQXv root@cPen_web
[root@cPen_web .ssh]# chmod 600 authorized_keys
# Note: Set its permissions to 600, preventing others or other groups from having any permissions
# Note: On machine A
[root@cPen_web .ssh]# ssh root@10.122.148.108 # Note: Use the client to log in as root user
………………………
Are you sure you want to continue connecting (yes/no)? yes
………………………
[root@cPen_web ~]# # Note: No password is required, indicating successful passwordless login
Implementing public key authentication for passwordless login
A --> B Machine A wants to log into Machine B
- Generate a public key pair on Machine A (if there is already a public key pair, there is no need to regenerate it), which will be stored in the .ssh/ directory under the current user's home directory by default.
Generate an id_rsa (private key) and id_rsa.pub (public key).
Note: If it already exists, there is no need to regenerate the public key pair, as it will overwrite. It is not significant to change the default path, as it will look for it in the default path.#
[root@cPen_web ~]# ssh-keygen # Note: Generate, press enter continuously to select defaults.
- On Machine B, copy and paste the public key from Machine A into the ~/.ssh/authorized_keys file of the target user.
If this file does not exist, create it, and ensure that its permissions are set to 600.
- Check if public key authentication is successful.
Execute ssh root@B machine's IP
on Machine A.
If you can log into Machine B without entering a password, it indicates that passwordless login is successful.
The public key is placed under which user on Machine B, and you log in through that user.
To log in as which user, check under which user the public key is placed on Machine B.
[root@cPen_web ~]# useradd wy
[root@cPen_web ~]# su - wy # Note: su switch does not go through ssh service
[wy@cPen_web ~]$
# Note: The su switch does not go through ssh
# Note: ssh is remote login
su and su - su switch does not change the bash environment (still the original user's bash environment)
su - switches to wy's bash environment
Public Key Authentication Troubleshooting
-
Ensure the public key is correct.
-
Ensure the ~/.ssh/authorized_keys file has permissions set to 600.
-
Ensure the home directory and the .ssh directory have permissions set to 755 or lower, meaning the group and others do not have 7 permissions.