Author Archives: artandfact_admin

A Linux Bash script to sync the most recent version of a file on a remote host to a local host (using SFTP) and a password

This bash script will log in to a remote host using SFTP, find the most recently modified file in a directory, and download it to a specified local directory.

#!/bin/bash

datestamp=$(date +%Y-%m-%dT%H:%M:%S%z)
echo $datestamp

fileName=$(echo "ls -1rt" | sshpass -p PASSWD sftp user@host | tail -1)

echo "Latest file is: " $fileName

echo "lcd /the/local/target/directory/to/place/downloaded/file
get $fileName targetfilename.txt" | sshpass -p PASSWD sftp user@host

echo "-----"
echo ""

This script uses sshpass. Sshpass is a utility you can use to pass along a password to an ssh prompt when using a key is not feasible. It’s great for scripts. Just make sure that the script which contains your password is not world readable.

n.b. This script works on the default directory on the target machine. If you want to change directories on the remote host, you’ll need to echo a “cd /your/path/here” before the “lcd” statement.

The script was written to facilitate logging, which is why it has echo statements echoing the datestamp, filename of the file which is being retrieved, and separator markers.


  • You’ll need to update the script to replace user@host with the username and hostname of the user which has SFTP access to the remote host.
  • You’ll need to update PASSWD with the cleartext password of the above user.
  • Replace targetfilename.txt with the filename you want the downloaded file to have after you’ve downloaded a copy. If you want the same filename (no name change), then remove targetfilename.txt altogether.
  • And finally, replace ‘/the/local/target/directory/to/place/downloaded/file‘ with your target directory for where to download the file locally.

Set the script to run via cron at the appropriate times. Pipe the output using &>> to append all output (standard out and err) to the log file. e.g.

/usr/local/sbin/syncscript.sh &>> /var/log/syncscript.log

A Memento Mori from a Chinese poet

The years of a lifetime do not reach a hundred,
Yet they contain a thousand years’ sorrow.
When days are short and the dull nights long,
Why not take a lamp and wander forth?
If you want to be happy you must do it now,
There is no waiting till an after-time.
The fool who’s loath to spend the wealth he’s got
Becomes the laughing-stock of after ages.
It is true that Master Wang became Immortal,
But how can we hope to share his lot?

https://en.wikisource.org/wiki/A_Hundred_and_Seventy_Chinese_Poems/Seventeen_Old_Poems

How to manually set up GeoIP geolocation using MaxMind and without using a package manager

GeoIP is the process of determining a geographic location of a requestor based on an IP address.

On many Linux systems, like Centos, Debian or Ubuntu, you can install an Apache mod called mod_geoip, which you can then use either within your Apache stanza config, .htaccess or within PHP by calling a function with the IP as an argument.

In this tutorial, I will briefly show you how to set up GeoIP using MaxMind Reader and GeoLite2 Free Geolocation Data.

You will need two things:

  • The MaxMind Reader class, which is free to download and available from here. You can download the whole project as a Zip file. If you’re on the command-line, you can right-click on the green link to grab the URL. At the time of writing, it was here.
  • The GeoLiteIP database from MaxMind. GeoLite2 Database is located here, and is free. Unfortunately, you will need to register first to download it. The download page is here, and in this example we’ll use the ‘GeoLite2 Country’ binary database which has the file extension .mmdb

Download the MaxMind project folder and put it in a subfolder of the PHP page from which it will be needed. Let’s say we have an index.php page which is at the document root, which has the path /var/www/public_html/mywebsite/index.php. Your unzipped folder of MaxMind will be named: MaxMind-DB-Reader-php-main. Rename it ‘MaxMind’.

Inside the MaxMind project folder should be a file called ‘autoload.php’ and a subfolder named ‘src’.

Next, download the GeoLite2 .mmdb Country database. By convention, this should go in the: /usr/share/GeoIP/ folder or subfolder, but you can put it wherever you like.

We can now add some code to our index.php page to use the MaxMind libraries and perform a GeoIP lookup.

First, load the autoloader in the MaxMind folder. Next you need the ‘use‘ keyword to use to declare the namespace. Third, create a variable pointing to the MaxMind database you just downloaded. Finally, instantiate a reader of the MaxMind Reader class:

require('MaxMind/autoload.php');
use MaxMind\Db\Reader;
$databaseFile = "/usr/share/GeoIP/GeoLite2-Country.mmdb";
$reader = new Reader($databaseFile);

Once you’ve done those four things, you’re ready to look up the geo-location of an IP.

If you want to test for a proxy IP (HTTP_X_FORWARDED_FOR), then I suggest you use the following code:

if (getenv('HTTP_X_FORWARDED_FOR')) {
        $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
        $ipaddress = getenv('REMOTE_ADDR');
        //echo "Your Proxy IP address is : ".$pipaddress." (via $ipaddress)";
} else {
        $ipaddress = getenv('REMOTE_ADDR');
        //echo "Your IP address is : $ipaddress";
}

After that, you can call the reader class to do a lookup:

if (isset($pipaddress)) {
        $geoip_array = $reader->get($pipaddress);
} else {
        $geoip_array = $reader->get($ipaddress);
}

The reader class will return an array of different information you can use. Here is an example of a print_r statement on the $geoip_array variable on a test page accessed by a Tor Browser:

Array
(
    [continent] => Array
        (
            [code] => EU
            [geoname_id] => 6255148
            [names] => Array
                (
                    [de] => Europa
                    [en] => Europe
                    [es] => Europa
                    [fr] => Europe
                    [ja] => ヨーロッパ
                    [pt-BR] => Europa
                    [ru] => Европа
                    [zh-CN] => 欧洲
                )

        )

    [country] => Array
        (
            [geoname_id] => 2750405
            [is_in_european_union] => 1
            [iso_code] => NL
            [names] => Array
                (
                    [de] => Niederlande
                    [en] => Netherlands
                    [es] => Holanda
                    [fr] => Pays-Bas
                    [ja] => オランダ王国
                    [pt-BR] => Holanda
                    [ru] => Нидерланды
                    [zh-CN] => 荷兰
                )

        )

    [registered_country] => Array
        (
            [geoname_id] => 2750405
            [is_in_european_union] => 1
            [iso_code] => NL
            [names] => Array
                (
                    [de] => Niederlande
                    [en] => Netherlands
                    [es] => Holanda
                    [fr] => Pays-Bas
                    [ja] => オランダ王国
                    [pt-BR] => Holanda
                    [ru] => Нидерланды
                    [zh-CN] => 荷兰
                )

        )

    [traits] => Array
        (
            [is_anonymous_proxy] => 1
        )

)

If you just want the Country ISO code, for example, you can use the code:

$geo_location = $geoip_array['country']['iso_code'];

Recovering an Admin account in WordPress using the command line

So, you’ve decided to lock yourself out of your WordPress admin account. Don’t worry, if you have shell access to your files there are a few ways you can recover and admin account or make a new one. I will show you two of them here.

Assuming your IP hasn’t been blocked by a plugin, or you’ve otherwise broken the WP login procedure, you can use one of the two methods to either create a new account or reset the password of an existing account:

1. Edit your functions.php file so that it will automatically create a new admin account for you when it loads.

Following this code:
https://stackoverflow.com/questions/17308808/create-an-admin-user-programmatically-in-wordpress

function rndprfx_add_user() {
    $username = 'username123';
    $password = 'azerty321';
    $email = 'example@example.com';

    if (username_exists($username) == null && email_exists($email) == false) {
        $user_id = wp_create_user( $username, $password, $email );
        $user = get_user_by( 'id', $user_id );
        $user->remove_role( 'subscriber' );
        $user->add_role( 'administrator' );
    }
}
add_action('init', 'rndprfx_add_user');

Copy and paste the above in your functions.php WordPress file (make a backup first). This file is located in wp-includes WordPress folder.

You will need to replace the variable assignments for $username, $password, and $email above once you’ve pasted in the code. Once you’ve logged in successfully once, remove the code from your functions.php file.

2. Use wp-cli to edit the password of an existing admin account

In case you’re not already using it, you should familiarize yourself with wp-cli.

WP-CLI is the command-line interface for WordPress. You can update plugins, configure multisite installations and much more, without using a web browser.

https://wp-cli.org/

It’s a very handy tool for administering a WordPress site via the command line and can be used to write scripts to automate tedious or periodic WP tasks.

The full list of wp-cli commands can be found here:

https://developer.wordpress.org/cli/commands/

Install wp-cli using the instructions on the wp-cli homepage, or use yum or your OS’s favourite package manager.

Go to the root directory of the WordPress installation. This is the public_html or similarly named folder which contains the wp-config.php file for your WP installation.

You will now need to be either the user who has ownership of the WordPress folder and files, or be root. If you are root, you can use the: ‘–allow-root’ argument to allow wp-cli to run as root. The wp-cli command gives you a warning about running as root because, like every other command run as root, it will have access to all files on the server.
Be careful about updating plugins as root, since the file permissions for the plugin will change.

We will continue this tutorial as root. Run the command:

wp --allow-root user list

To show you the list of users, including their login, display name, email, when they registered, and their role (access level). Admins have the role ‘administrator’.

From there, you can use:

wp --allow-root user update id --user_pass=password

…to update an admin user’s password by id. Id and password above are variables you need to replace.

Or alternatively:

wp --allow-root user update username --prompt=user_pass

Where username is the variable you need to replace. You’ll be prompted to enter a new password at the command line. You are only asked once, so be sure to test login.