Download and insert salt string inside wordpress wp-config.php with Bash

前端 未结 10 2277
有刺的猬
有刺的猬 2021-02-13 06:27

How can I insert the content of the variable $SALT in a specific point (line or string) of a file like wp-contet.php from wordpress using Bash script?



        
10条回答
  •  伪装坚强ぢ
    2021-02-13 06:40

    I was challenged with the same issue. Here is the script I wrote to replace the salts and keys from ones downloaded from WordPress. You can use it at any time to replace them if/when needed. I run it as sudo, and the script tests for that. If you use an account that can download to the directory and make updates to the wp-config.php file, then you can delete that part of the script.

    #!/bin/sh
    # update-WordPress-Salts: Updates WordPress Salts
    # written by Wayne Woodward 2017
    
    if [ $# -lt 1 ]; then
        echo "Usage: update-WordPress-Salts directory"
        exit
    fi
    
    if [ "$(whoami)" != "root" ]; then
      echo "Please run as root (sudo)"
      exit
    fi
    
    WPPATH=$1
    
    # Update the salts in the config file
    
    # Download salts from WordPress and save them locally
    curl http://api.wordpress.org/secret-key/1.1/salt/ > /var/www/$WPPATH/wp-keys.txt
    
    # Iterate through each "Saltname" and append 1 to it
    # For a couple names that may match twice like "AUTH_KEY" adds extra 1s to the end
    # But that is OK as when this deletes the lines, it uses the same matching pattern
    # (Smarter people may fix this)
    for SALTNAME in AUTH_KEY SECURE_AUTH_KEY LOGGED_IN_KEY NONCE_KEY AUTH_SALT SECURE_AUTH_SALT LOGGED_IN_SALT NONCE_SALT
    do
       sed -i -e "s/$SALTNAME/${SALTNAME}1/g" /var/www/$WPPATH/wp-config.php
    done
    
    # Find the line that has the updated AUTH_KEY1 name
    # This is so we can insert the file in the same area
    line=$(sed -n '/AUTH_KEY1/{=;q}' /var/www/$WPPATH/wp-config.php)
    
    # Insert the file from the WordPress API that we saved into the configuration
    sed -i -e "${line}r /var/www/$WPPATH/wp-keys.txt" /var/www/$WPPATH/wp-config.php
    
    # Itererate through the old keys and remove them from the file
    for SALTNAME in AUTH_KEY SECURE_AUTH_KEY LOGGED_IN_KEY NONCE_KEY AUTH_SALT SECURE_AUTH_SALT LOGGED_IN_SALT NONCE_SALT
    do
       sed -i -e "/${SALTNAME}1/d" /var/www/$WPPATH/wp-config.php
    done
    
    # Delete the file downloaded from Wordpress
    rm /var/www/$WPPATH/wp-keys.txt
    

提交回复
热议问题