Skip to content

Instantly share code, notes, and snippets.

@nikolaik
Last active March 21, 2017 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikolaik/eff807dc7e865eaf39ef to your computer and use it in GitHub Desktop.
Save nikolaik/eff807dc7e865eaf39ef to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
wp_upgrade.py upgrades wordpress installations recursively.
- looks for Wordpress installations
- tries to update WP core, plugins and themes
Requires: WP-CLI http://wp-cli.org/
"""
import grp
import os
import pwd
import sys
import subprocess
from subprocess import Popen
def get_owner(path):
s = os.stat(path)
return {
'uid': s.st_uid,
'gid': s.st_gid,
'username': pwd.getpwuid(s.st_uid).pw_name,
'group': grp.getgrgid(s.st_gid).gr_name,
}
def demote(user_uid, user_gid):
def result():
os.setgid(user_gid)
os.setuid(user_uid)
return result
def run_cmd(cmd, run_as=None):
preexec_fn = None
if run_as is not None:
preexec_fn = demote(run_as['uid'], run_as['gid'])
print("Running \'{}\' as {}:{}".format(' '.join(cmd), run_as['username'], run_as['group']))
p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec_fn)
return p.communicate() + (p.returncode,)
def upgrade_wp(path):
wp_dirs = ['wp-content', 'wp-includes', 'wp-admin']
WP_CLI = '/usr/local/bin/wp'
# wp cmds
wp_update_cmd = [WP_CLI, 'core', 'update']
wp_theme_update_cmd = [WP_CLI, 'theme', 'update-all']
wp_plugin_update_cmd = [WP_CLI, 'plugin', 'update-all']
upgrade_cmds = [
wp_update_cmd,
wp_theme_update_cmd,
wp_plugin_update_cmd,
]
os.chdir(path) # move in!
print("Upgrading {}".format(path))
for cmd in upgrade_cmds:
owner = get_owner(path)
stdout, stderr, returncode = run_cmd(cmd, run_as=owner)
# on error bail
if returncode != 0:
print('Last command returned non zero ({}): \'{}\', bailing...'.format(returncode, ' '.join(cmd)))
print(stderr)
return
print('OK')
def get_wp_dirs(path, max_depth=2):
# Look for wp-config.php 2 dir deep
wp_config = 'wp-config.php'
wp_dirs = []
for root, dirs, files in os.walk(path, topdown=True):
depth = root[len(path) + len(os.sep):].count(os.sep)
if depth >= max_depth:
dirs[:] = [] # don't go deeper
if wp_config in files:
wp_dirs.append(root) # match!
return wp_dirs
if __name__ == '__main__':
cur_path = os.getcwd()
paths = get_wp_dirs(cur_path)
print('Found {} Wordpress installations\n{}'.format(len(paths), '\n'.join(paths)))
for path in paths:
upgrade_wp(path)
os.chdir(cur_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment