CentOS series password-free login script sharing

CentOS series password-free login script sharing

introduction

In the field of automated operation and maintenance, frequent server operations are a common task. In order to simplify this process and improve work efficiency, password-free login has become an important technology. The CentOS series' password-free login scripts can help automated operation and maintenance personnel quickly achieve password-free login to the server, thereby simplifying operations and improving the efficiency of automated deployment, configuration, and management. This article will introduce how to use this script to implement password-free login for the CentOS series in automated operation and maintenance.

Quick to use

wget https://gitee.com/useryc/secret_free_login/raw/main/secret_free_login.sh
# 或者
wget wget https://raw.githubusercontent.com/liuyuanchengweb/secret_free_login/main/secret_free_login.sh
chmod +x secret_free_login.sh
./secret_free_login.sh [用户名] [主机地址] [密码]

Target

The goal of this article is to show readers how to use the password-free login script of the CentOS series to implement password-free login to the server in automated operation and maintenance. By using this script, you can easily configure password-free login, improve work efficiency, and make other scripts call this script.

Script overview

The password-free login script of the CentOS series uses the OpenSSH tool and the Expect tool. Its main functions include:

  • Check the installation of required tools: The script automatically checks whether the required tools (such as OpenSSH and Expect) are installed. If tools are found not installed, the script will automatically install them.

  • Generate key pair: The script generates a pair of RSA keys (public and private keys) for encrypted communication and authentication.

  • Copy the public key to the remote server: The script will copy the generated public key to the target server to enable password-free login.

  • Verify password-free login: The script will verify whether password-free login is successful and output the corresponding results.

prerequisite

Before using the password-free login script of the CentOS series, please ensure that the following prerequisites are met:

  • CentOS series operating systems: This script is suitable for openEuler, CentOS, Red Hat and other CentOS-based distributions.
  • Local machine: You need to execute the script on your local machine.
  • Remote server: You need to have login credentials (username and password) for the target server and have permission to connect remotely via SSH.

Script implementation

The following is the code to implement the password-free login script of the CentOS series:

#! /bin/bash

user=$1
ip_add=$2
pass=$3
timeout=10

ssh_keygen(){
    
    
    if [ -e $id_rsa_path ];then
        echo -e "已经生成密钥:$id_rsa_path"
    else
        pass_path=$(/bin/expect -c "
        spawn  ssh-keygen -q -t rsa
        expect {
            \"*save the key*\" { send \"\r\"; exp_continue }
            \"*passphrase*\" { send \"\r\";exp_continue }
            \"*again*\" { send \"\r\"}
            }
        " | awk -F '\(' 'NR==2{print $NF}' 2>/dev/null | awk -F '\)' '{print $1}' 2>/dev/null)
        echo -e "密钥存放路径:$pass_path"
    fi

    if [ $? -eq 1 ];then
        echo "生成密钥失败"
    fi
}
scp_key(){
    
    
        output=$(expect -c "
        set timeout $timeout
        spawn ssh-copy-id $user@$ip_add

        expect {
                \"password:\" {
                        # 发送密码
                        send \"$pass\r\"
                        exp_continue
                }
                \"yes/no\" {
                        # 确认远程主机的公钥
                        send \"yes\r\"
                        exp_continue
                }
                \"Number of key(s) added\" {
                        # 配置免密登录成功
                        puts  \"succed\"
                        exit 0
                }
                \"WARNING: All keys were skipped because they already exist on the remote system.\" {
                        # 已经配置过免密登录
                        puts  \"outmoded\"
                        exit 1
                }
                \"Permission denied\" {
                        # 登录失败:权限被拒绝
                        puts  \"Permission denial\"
                        exit 2
                }
                \"ERROR: No identities found\" {
                        # 未生成密钥
                        puts  \"Ungenerated key\"
                        exit 3
                        }
                \"ERROR: ssh: connect to host\" {
                        # 连接超时
                        puts \"ssh: connect to host\"
                        exit 4
                        }
                timeout {
                        # 超时处理
                        puts  \"Timeout\"
                        exit 4
                }
        }
        expect eof
        ")
        case $output in
                *"succed"*)
                        echo "配置免密登录成功"
                        ;;
                *"outmoded"*)
                        echo "已经配置过免密登录"
                        ;;
                *"Permission denial"*)
                        echo "登录失败:权限被拒绝"
                        ;;
                *"Ungenerated key"*)
                        echo "未生成密钥"
                        ;;
                *"ssh: connect to host"*)
                        echo "主机连接超时"
                        ;;
                *)
                        echo "其他错误"
                        ;;
        esac
}

check_ip(){
    
    
    IP=$(echo $ip_add|cut -d "/" -f 1)
    if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null; then
        res=$(echo $IP|awk -F . '$1>=1&&$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
        if [ "X${res}" == "X" ]; then
            echo -e "请输入合法的IP地址"
            return 1
        fi
    fi
}

check_expect_installation() {
    
    
  if ! command -v expect >/dev/null 2>&1; then
    echo "正在安装Expect..."
        if command -v yum >/dev/null ; then
            sudo yum install -y expect >/dev/null
    else
      echo "无法安装Expect,请手动安装"
      exit 1
    fi
    echo "Expect已成功安装"
  else
    echo "Expect已经安装"
  fi
}

run_secret_free_login(){
    
    
    if [ -n "$user" ] && [ -n "$ip_add" ] && [ -n "$pass" ];then
        cd ~
        echo -e "你要执行免密登的用户名是:$user"
        echo -e "执行免密登录的主机是:$ip_add "
        echo -e "你要执行免密登的密码是:$pass"
        id_rsa_path=`pwd`/.ssh/id_rsa.pub
        check_expect_installation &&  check_ip && ssh_keygen && scp_key
    else
        echo -e "脚本使用格式# ./secret_free_login 用户名 IP地址 密码 "
    fi
}

run_secret_free_login

  1. ssh_keygen()Function: This function is used to generate a key pair. First, determine whether the key file already exists. If it exists, print the generated key path. Otherwise, use the ssh-keygencommand to generate a key pair and extract the generated key file path.
  2. scp_key()Function: This function uses expectthe tool to execute ssh-copy-idthe command to copy the public key to the remote host to implement password-free login configuration. In expectthe statement, perform corresponding operations according to different matching situations, such as sending passwords, confirming the public key of the remote host, and so on. According to the command execution result, use putsthe command to output the corresponding character string as the basis for subsequent processing.
  3. check_ip()Function: This function is used to check whether the input IP address is legal. Use regular expressions to determine whether the format of the IP address meets the requirements.
  4. check_expect_installation()Function: This function is used to check if expectthe tool is installed. Use command -vthe command to check expectwhether the command exists, and if not, perform the installation operation. According to different system package managers, use the corresponding command to install.
  5. run_secret_free_login()Function: This function is the main function of the script and is used to perform password-free login operations. First check whether the input parameters meet the requirements, then call the function to check whether the tool check_expect_installation()is installed , then call the function to check the validity of the IP address, then call the function to generate a key pair, and finally call the function to perform the password-free login configuration operation.expectcheck_ip()ssh_keygen()scp_key()
  6. At the end of the script, call run_secret_free_login()the function to start the password-free login operation.

Instructions

Follow the steps below to use the CentOS series password-free login script:

  1. Create sh script file
  2. chmod +x 免密登录脚本.sh
  3. Run script command:./免密登录脚本.sh 用户名 IP地址 密码
  4. Wait for the script execution to complete and output the corresponding results.

Precautions

  • Before running the script, make sure you have installed OpenSSH tools and Expect tools.
  • Please make sure that the IP address entered is correct, and the target host can be accessed through the network.
  • If the script fails to execute or outputs an error message, carefully check the input parameters and preconditions.

Guess you like

Origin blog.csdn.net/qq_41816198/article/details/131544994