Hide nick-name in social-share on WordPress

<?php
/*
    Plugin Name: Remove Nick
    Plugin URI: http://www.mikjaer-consulting.dk
    Description: Stuff
    Author: Mikkel Mikjaer Christensen
    Version: 1.0.0
    Author URI: https://www.mikjaer-consulting.dk
 */

add_filter( 'oembed_response_data', 'disable_embeds_filter_oembed_response_data_' );
function disable_embeds_filter_oembed_response_data_( $data ) {
    unset($data['author_url']);
    unset($data['author_name']);
    return $data;
}

Source: https://wordpress.stackexchange.com/questions/369151/how-to-remove-author-name-and-link-from-a-shared-link-preview

Udgivet i Uncategorized | Skriv en kommentar

Fetching and parsing backuppc host summary with Python

#!/usr/bin/python
import requests, pprint, pandas  # pip install pandas

url = 'http://backuppc.mycompany.com/backuppc/index.cgi?action=summary'
username = '<USERNAME>';
password = '<PASSWORD>';

def fetchSummary(url, username, password):
    response = requests.get(url, auth = requests.auth.HTTPBasicAuth(username, password))
    tables = pandas.read_html(response.content)

    hosts = {}

    for i,host in enumerate(tables[0][0]):
        if not i == 0:
            hosts.update({
                    host : {
                            'hostname'              : host,
                            'user'                  : tables[0][1][i],
                            'fullBackups'           : tables[0][2][i],
                            'lastFullAge'           : tables[0][3][i],
                            'lastFullSize'          : tables[0][4][i],
                            'lastFullSpeed'         : tables[0][5][i],
                            'incrementalBackups'    : tables[0][6][i],
                            'lastIncrementalAge'    : tables[0][7][i],
                            'lastBackup'            : tables[0][8][i],
                            'state'                 : tables[0][9][i],
                            'xferErrors'            : tables[0][10][i],
                            'lastAttempt'           : tables[0][11][i]
                        }
                })
    return hosts


pprint.pprint(fetchSummary(url, username, password))

Udgivet i Backuppc, Python | Skriv en kommentar

Distributing SSH Keys with Ansible

This method is designed to fully take over the distribution of SSH Keys, meaning if you use this method you, or individual users, can no longer manually add their own keys to the systems.

./roles/ssh-keys/tasks/main.yml:

---
- name: Making sure .ssh directories exists
  ansible.builtin.file:
    path: /root/.ssh/
    state: directory
    mode: '0700'

- name: Distributing admin-ssh-keys, /root/.ssh/authorized_keys
  template:
    src: authorized_keys
    dest: /root/.ssh/authorized_keys
    mode: 0700
  vars:
    username: root

- name: Making sure .ssh directories exists for users
  ansible.builtin.file:
    path: /home/{{ item.username }}/.ssh
    state: directory
    mode: '0700'
  loop: "{{ sshkeys | json_query(_query) | flatten | unique }}"
  when: item.username != "root" and item.hostname == ansible_fqdn
  vars:
    _query: "[].hosts"


- name: Distributing user-ssh-keys
  template:
    src: authorized_keys
    dest: /home/{{ item.username }}/.ssh/authorized_keys
    mode: 0700
  loop: "{{ sshkeys | json_query(_query) | flatten | unique }}"
  when: item.username != "root" and item.hostname == ansible_fqdn
  vars:
    _query: "[].hosts"
    username: "{{item.username}}"

- name: Fetching
  getent:
    database: passwd

- name: Building lookup table
  set_fact:
    managedkeys: "{{ managedkeys | default({}) | combine( {item.hostname: [item.username]} , list_merge='append') }}"
  loop: "{{ sshkeys | json_query(_query) | flatten | unique }}"
  when: item.username != "root" #and item.hostname == ansible_fqdn
  vars:
    managedkeys: {}
    _query: "[].hosts"

- name: Removing un-managed authorized_keys
  debug:
    msg: User {{ item }} found
  loop: "{{ getent_passwd.keys()|list }}"
  when: item not in managedkeys[ansible_fqdn] and item != "root"

- name: Removing un-managed (all) authorized_keys2
  file:
    path: ~{{item}}/.ssh/authorized_keys2
    state: absent
  loop: "{{ getent_passwd.keys()|list }}"

./roles/ssh-keys/tasks/authorized_keys

# This file is maintained by Ansible, changes will be automatically overwritten
# Username: {{username}}
{%- for sshkey in sshkeys -%}
        {%- if sshkey.admin is defined and sshkey.admin and username == "root" %}


# {{sshkey.owner}}
{{sshkey["key"]}}
        {%- else -%}
                {%- if sshkey["hosts"] is defined -%}
                        {%- for host in sshkey.hosts -%}
                                {%- if ansible_fqdn == host.hostname and username == host.username %}


# {{sshkey.owner}}
ZZZ {{sshkey["key"]}}
                                {%- endif -%}
                        {%- endfor -%}
                {%- endif -%}
        {%- endif -%}
{%- endfor %}


# This file is maintained by Ansible, changes will be automatically overwritten

And finally ./roles/ssh-keys/vars/main.yaml

sshkeys:
  - owner: Firstname Lastname
    admin: true
    key: ssh-rsa AAAA.....PQZ firstname@laptop

  - owner: Another firstname another lastname
    admin: true
    key: ssh-rsa AAAA.....QJE another@workstation

  - owner: Automated backup
    key: ssh-rsa AAAA.....EMT backup@backupcluster
    hosts:
      - hostname: targetsystem.mydomain.com
        username: backup
      - hostname: targetsystem.mydomain.com
        username: mysql
      - hostname: anothertarget.mydomain.com
        username: backup

This will install Firstnames and Another firstnames ssh keys on the root account on all servers targeted with this task, and the automated backup key on targetsystem user backup and mysql and finally on anothertarget user backup.

Every other key on the system will be deleted every time this script is being run, it checks every .ssh folder in every homedir for authorized_keys and authorized_keys2 files and deletes them, unless the homedir belongs to one of the above users. Authorized_keys2 er always deleted since we don’t use them.

If you don’t want this functionality you can remove either both or one of the last blocks in the tasks/main.yaml

Udgivet i Ansible, Linux | Skriv en kommentar

Nagios / Incinga plugin for BackupPC

This plugin scrapes the BackupPC web-interface and uses it to fire off an alert if one or more jobs needs attention.

<?php
$hostname="http://localhost/backuppc/index.cgi";

$username="username"; $password="password";
$ignore = array("foobar.dk");
$auth = base64_encode("$username:$password");
$context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ]]);
$homepage = file_get_contents($hostname, false, $context );

preg_match("/Failures that need attention.+<\/table/sim", $homepage, $matches);
preg_match_all("/<tr\>(.+?)<\/tr\>/sim", $matches[0], $m);

$failures = array();

foreach ($m[0] as $_)
{
        preg_match("/<a href=.+?>(.+?)</", $_, $m2);

        if (!in_array($m2[1], $ignore))
              $failures[] = $m2[1];
}

if (count($failures) == 0)
{
        print "OK: Alles ist gut\n";
        die(0);
}
else
{
        print "CRITICAL: ".count($failures)." errors: ".implode(", ", $failures)."\n";
        die(2);
}
?>
Udgivet i Nagios | Skriv en kommentar

Adding a secondary qemu2 disk to a kvm using virsh

First create the image:

qemu-img create -f qcow2 /var/kvm/images/vm-secondary.qcow2 50GB

Then attach it to the virtual machine:

virsh attach-disk vm /var/kvm/images/vm-secondary.qcow2 vdb --persistent --subdriver qcow2

Enter VM and format disk, you don’t need to restart.

Udgivet i KVM, Linux | Skriv en kommentar

Installing OpenZFS on Debian 11

Installing OpenZFS

Install the repository management system:

root@server:~# apt-get install -y software-properties-common

Enable contrib repositories:

root@server:~# apt-add-repository contrib
'contrib' distribution component enabled for all sources.
root@db2:~#

Upgrade system:

root@server:~# apt update
...
root@dserver:~# apt -y upgrade

Reboot system to boot with the new kernel:

root@server:~# reboot

Ssh back in to the host, and install the needed packages:

root@server:~# apt install -y linux-headers-$(uname -r) linux-image-amd64 spl kmod zfsutils-linux zfs-dkms zfs-zed

Say “OK” to imkompatability warning, and load the newly build kernel module:

root@server:~# modprobe zfs

Creating ZFS pools and datasets

Get a quick overview over the block devices in the system:

root@server:~# lsblk
NAME    MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
vda     254:0    0   160G  0 disk
├─vda1  254:1    0    59G  0 part /
├─vda2  254:2    0 100.9G  0 part
├─vda14 254:14   0     3M  0 part
└─vda15 254:15   0   124M  0 part /boot/efi
vdb     254:16   0   472K  1 disk

Creating the pool “storage”:

root@server:~# zpool create -f storage /dev/vda2
root@server:~# zpool list
NAME      SIZE  ALLOC   FREE  CKPOINT  EXPANDSZ   FRAG    CAP  DEDUP    HEALTH  ALTROOT
storage   100G   129K   100G        -         -     0%     0%  1.00x    ONLINE  -

Create the dataset “mysql” in the “storage” pool:

root@server:~# zfs create storage/mysql
root@server:~# df -h |grep storage
storage          97G  128K   97G   1% /storage
storage/mysql    97G  128K   97G   1% /storage/mysql

Udgivet i Linux | Skriv en kommentar

Shrinking the root filesystem on a Linux machine

This was needed by me in order to run ZFS on a DigitalOcean droplet, but the process should be applicable to more or less any Linux system.

1: Boot into rescue mode

Click the “Recover” link in the left vertical menu on the droplet in Digital Ocean, select “Boot from Recover ISO” now log into the system and type:

root@server:~# poweroff

Wait 10 seconds, and click the power button in the top-left corner of the DigitalOcean interface, let the machine power down and then power it up again, reboot takes approximately 20 seconds, then ssh back in: (Host keys have change because it is now running the rescue system, so add the StrictHostKeychecking=no option to the command)

user@workstation:~$ ssh -o "StrictHostKeyChecking=no" root@server 

Resize an unmounted partition

Get an overview over our current partition table:

root@server:~# fdisk -l /dev/vda
Disk /dev/vda: 160 GiB, 171798691840 bytes, 335544320 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 890B1932-7DF1-C144-BC7B-9077D65BBCFC

Device      Start       End   Sectors   Size Type
/dev/vda1  262144 335544286 335282143 159.9G Linux filesystem
/dev/vda14   2048      8191      6144     3M BIOS boot
/dev/vda15   8192    262143    253952   124M EFI System

Partition table entries are not in disk order.

We want to divide vda1 into vda1 of 59GB and vda2 of 100GB for using with ZFS, so first we will need to shrink the filesystem om vda1:

root@server:~# e2fsck -f /dev/vda1
e2fsck 1.44.1 (24-Mar-2018)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/vda1: 29873/10477568 files (0.1% non-contiguous), 941511/41910267 blocks
root@server:~# resize2fs /dev/vda1 59G
resize2fs 1.44.1 (24-Mar-2018)
Resizing the filesystem on /dev/vda1 to 15466496 (4k) blocks.
The filesystem on /dev/vda1 is now 15466496 (4k) blocks long.

This will have changed the filesystem inside of the partition, which means that the last 100GB of the partition is now unused, we now use fdisk to delete vda and create vda1 and 2:

root@server:~# fdisk /dev/vda

Welcome to fdisk (util-linux 2.31.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/vda: 160 GiB, 171798691840 bytes, 335544320 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 890B1932-7DF1-C144-BC7B-9077D65BBCFC

Device      Start       End   Sectors   Size Type
/dev/vda1  262144 335544286 335282143 159.9G Linux filesystem
/dev/vda14   2048      8191      6144     3M BIOS boot
/dev/vda15   8192    262143    253952   124M EFI System

Partition table entries are not in disk order.

Command (m for help): d
Partition number (1,14,15, default 15): 1

Partition 1 has been deleted.

Command (m for help): n
Partition number (1-13,16-128, default 1): 1
First sector (262144-335544286, default 262144): <enter>
Last sector, +sectors or +size{K,M,G,T,P} (262144-335544286, default 335544286): +59G

Created a new partition 1 of type 'Linux filesystem' and of size 59 GiB.
Partition #1 contains a ext4 signature.

Do you want to remove the signature? [Y]es/[N]o: N

Command (m for help): n
Partition number (2-13,16-128, default 2): 2
First sector (123994112-335544286, default 123994112): <enter>
Last sector, +sectors or +size{K,M,G,T,P} (123994112-335544286, default 335544286): <enter>

Created a new partition 2 of type 'Linux filesystem' and of size 100.9 GiB.

Command (m for help): p
Disk /dev/vda: 160 GiB, 171798691840 bytes, 335544320 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 890B1932-7DF1-C144-BC7B-9077D65BBCFC

Device         Start       End   Sectors   Size Type
/dev/vda1     262144 123994111 123731968    59G Linux filesystem
/dev/vda2  123994112 335544286 211550175 100.9G Linux filesystem
/dev/vda14      2048      8191      6144     3M BIOS boot
/dev/vda15      8192    262143    253952   124M EFI System

Partition table entries are not in disk order.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

Boot back into the server own operating system, and start using your new partition.

Udgivet i Linux | Skriv en kommentar

Changing from GPT to MBR

Run gdisk /dev/had and type r and press enter followed by g and press enter, quit the program and restart the system.

Udgivet i Uncategorized | Skriv en kommentar

Wiping the partition table on a USB Stick in Windows

When you try to flash a Linux boot USB Stick from Windows, typically using Balena Etcher, the process will fail due to there already being partitions on the stick.

If you open up Windows Disk Management it will typically show up like this:

Windows Disk Management does not play nice with Linux Partitioned USB Sticks

The solution is to Windows program “diskpart”, by pressing Meta key + R, typing “diskpart” and pressing enter. Here you can list the hard drives in your system and select the one you which to wipe, or clean, and have it done for you, like so:

The above commands should then result in an empty partition table which you can now either partition using Windows Disk Management, or flash an image onto using Balena Etcher, to verify this you can check the partition table with Windows Disk Management:

How a cleaned partition looks in Windows Disk Management

Udgivet i Windows | Skriv en kommentar

Auto-updating timestamp column i MariaDB/MySQL

If you need a colum that will automagically show when a row was created or changed you can use the following:

 CREATE TABLE `vars` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(45) DEFAULT NULL,
  `value` longtext DEFAULT NULL,
  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `key_UNIQUE` (`key`)
); 

Now try to insert some data:

MariaDB [portal]> insert into vars (`key`,`value`) values ('foo','bar');
Query OK, 1 row affected (0.010 sec)

MariaDB [portal]> select * from vars;
+----+------+-------+---------------------+
| id | key  | value | timestamp           |
+----+------+-------+---------------------+
|  1 | foo  | bar   | 2021-08-09 10:43:30 |
+----+------+-------+---------------------+
1 row in set (0.001 sec)

MariaDB [portal]>

And then change those data:

MariaDB [portal]> update vars set value = "BAR" where id=1;
Query OK, 1 row affected (0.005 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [portal]> select * from vars;
+----+------+-------+---------------------+
| id | key  | value | timestamp           |
+----+------+-------+---------------------+
|  1 | foo  | BAR   | 2021-08-09 10:44:44 |
+----+------+-------+---------------------+
1 row in set (0.001 sec)

MariaDB [portal]>

Enjoy 😉

Udgivet i Uncategorized | Skriv en kommentar