Tunneling HP ILO5 through SSH

Creates a tunnel to the ilo port, which in this example is 10.0.0.201 through the jumphost, after this you can connect to ILO by typing in https://locahost and accept the security warning, refreshing and logging in with your credentials.

 ssh jumphost.yourcompany.com -l root -L 443:10.0.0.201:443 -L 17990:10.0.0.201:17990 -L 80:10.0.0.201:80
Udgivet i Linux, SSH | Skriv en kommentar

Unmounting an NFS Share that has gone away

On Linux when an NFS share disappears it is not handled very well, to say it nicely, and in order to get a functioning machine again you need to drop that mount, but a simple umount command states that the device is busy.

So you need to both use the lazy and the force flag:

# umount -l -f /mnt/nfsshare
Udgivet i Linux | Skriv en kommentar

Fail2ban crash course

Just install fail2ban and the default settings will keep you protected just fine, after five failed login attempts the ip address of the offending login will be blocked for 10 minutes using iptables.

# apt-get install fail2ban

If you wish to keep tap on what is happening you can always tail the logfile:

# tail -f /var/log/fail2ban.log
... fail2ban.filter         [2374]: INFO    [sshd] Found 10.0.0.2 - 2022-09-14 22:08:01
... fail2ban.filter         [2374]: INFO    [sshd] Found 10.0.0.2 - 2022-09-14 22:08:05
... fail2ban.filter         [2374]: INFO    [sshd] Found 10.0.0.2 - 2022-09-14 22:08:08
... fail2ban.filter         [2374]: INFO    [sshd] Found 10.0.0.2 - 2022-09-14 22:08:16
... fail2ban.filter         [2374]: INFO    [sshd] Found 10.0.0.2 - 2022-09-14 22:08:20
... fail2ban.actions        [2374]: NOTICE  [sshd] Ban 10.0.0.2

Status of fail2ban can be shown with the following command:

# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 2
|  |- Total failed:     13
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 1
   |- Total banned:     2
   `- Banned IP list:   200.111.119.58

Unbanning an ip can be done with this command:

# fail2ban-client set sshd unbanip 196.216.253.24
1

If you wish to ignore one or more addresses create a file /etc/fail2ban/jail.d/whitelist.conf with the following command:

# echo -e '[DEFAULT]\nignoreip = 62.69.153.125' > /etc/fail2ban/jail.d/whitelist.conf

And restart fail2ban:

# systemctl restart fail2ban.service
Udgivet i Linux, Security | Skriv en kommentar

Check TLS Certificate with openssl

echo | openssl s_client -servername customersite.com -connect servername.com:443 2> /dev/null | openssl x509 -noout -dates
notBefore=May  3 06:49:29 2022 GMT
notAfter=Aug  1 06:49:28 2022 GMT
Udgivet i Linux | Skriv en kommentar

Running and monitoring rsync with Python

#!/usr/bin/python3

import subprocess,sys,time,re
import pprint
import string

def execute(cmd):
        process = subprocess.Popen(cmd, shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True)
        for stdout_line in iter(process.stdout.readline, ""):
                yield stdout_line
        process.stdout.close()
        return_code = process.wait()

        if return_code:
                raise subprocess.CalledProcessError(return_code, cmd)

for line2 in execute("rsync --info=progress2 -rl /usr/ ./mc"):
        line = ''.join(c for c in line2 if c.isprintable())
        result = re.search(r"([0-9\,]+)\s+([0-9]+)%\s+([0-9a-zA-Z\.\/]+)", line)
        if result:
                transfered = result.group(1)
                percentage = result.group(2)
                speed = result.group(3)
                print(f"Rsync process Transfered: {transfered} Percentage: {percentage} Speed: {speed}")
~                                                                                                         
Udgivet i Python | Skriv en kommentar

Printing out a gage in the console with Python

#!/usr/bin/python3

import math, time

def gauge(size, position):
        print("Size: ", size, "Position: ", position)
        block = (size -2) / 100
        print("Block: ", block)

        filled = block * position;

        print("Filled blocks: ", filled)

        print("Filled blocks: ", math.floor(filled))

        print("[",end="");
        for i in range(1,(size -2)):
                if i < filled:
                        print ("#", end="");
                else:
                        print (".", end="");
        print("]");


for i in range(1,100):
        print('\033[s', end ='');
        gauge(75,i)
        print('\033[u', end = '');
        time.sleep(.1)
Udgivet i Python | Skriv en kommentar

XCP-NG: Delete default templates

List the templates to get the uuid of the template you wish to delete:

# xe template-list
uuid ( RO)                : 7dd1341e-3261-7a68-f91e-f3625a5e9a97
          name-label ( RW): Debian 11 (Image)
    name-description ( RW): My own


uuid ( RO)                : bfb0c8e5-e1db-4a32-9d85-757b3de0f19f
          name-label ( RW): Debian Bullseye 11
    name-description ( RW): To use this template from the CLI, install your VM using vm-install, then set other-config-install-repository to the path to your network repository, e.g. http://<server>/<path> or nfs:server:/<path>


uuid ( RO)                : 7774689b-4ca1-4dea-8545-dddd6b64c17f
          name-label ( RW): Windows 10 (64-bit)
    name-description ( RW): Clones of this template will automatically provision their storage when first booted and then reconfigure themselves with the optimal settings for Windows 10 (64-bit).

....

And then remove the parameter “is-default-template” by doing this:

# xe template-param-set is-default-template=false uuid=17a818b5-20a6-4d34-a7ef-320da9ef4c14

And finally delete it by:

xe template-uninstall --force template-uuid=17a818b5-20a6-4d34-a7ef-320da9ef4c14

Udgivet i xcp-ng | Skriv en kommentar

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