Categories
Powershell

smbclient

The following command enabled me to send a file from a linux host to a Windows SMB share

smbclient "//<HOST / IP>/<SHARENAME>" -U $username -c "put /path/to/local/linux/file $targetfilename_on_windows_host"
Categories
Linux

Transmission NordVPN Service

The following is a script I wrote to update the transmission-daemon ipv4 bind address with whatever is assigned to my devices tun0 interface.

#!/bin/bash

############################################################################################################
#A script to update the transmission bind-address-ipv4 value with the active tun0 IP from NordVPN.
#
#This script:
#
#       - Hard codes the transmission-daemon settings.json path
#       - Grabs the "bind-address-ipv4" line from the settings.json file
#       - Grabs the active IP on NordVPNs tun0 iface
#       - exits if there is no ip on tun0 iface and logs an error
#       - compares the settings.json ip with the tun0 ip:
#               If theyre different:
#                       - stops the transmission-daemon service
#                       - updates settings.json line "bind-address-ipv4" with the tun0 IP
#                       - starts the ransmission-daemon service
#                       - logs the change as local0.info and exits cleanly
#               If theyre the same:
#                       - logs the match as local0.info and exits cleanly
############################################################################################################
# Called via the simple service:
#
# NAME: /etc/systemd/system/update-transd-wnordvpnip.service
#
#[Unit]
#Description=Run script to update transmission config with nordvpn IP after nordvpnd.service has connected
#Requires=nordvpnd.service
#After=transmission-daemon.service
#
#[Service]
#Type=simple
#RemainAfterExit=yes
#ExecStart=/usr/local/bin/update_transmission_with_vpnip.sh
#Restart=on-failure
#RestartSec=10
#KillMode=process
#
#[Install]
#WantedBy=multi-user.target
#/etc/systemd/system/update-transd-wnordvpnip.service
############################################################################################################

############################################################################################################
# Define with the variables - these could be moved to script arguments in the future
############################################################################################################
# The transmission setttings file
transconf="/var/lib/transmission/.config/transmission-daemon/settings.json"

# locate the IP bind address and assign it
transbindip=$(grep "bind-address-ipv4" ${transconf})

# Get the ipv4 address of vpn tun0:
tunip=$(ifconfig tun0 | grep 'inet' | awk '{print $2}')

############################################################################################################
# Define the functions of the script
############################################################################################################
check_service_response(){

        if [ $? == 0 ]; then
                printf "\n$1 service $2"
        else
                printf "\n$1 service failed $2, exiting...\n\n"
                logger -p local0.err "transmission-ip-update : Failed to $2 the $1 service"
                exit 2
        fi
}

change_service_state(){

        if [ $(systemctl is-active $1)  == "active" ]; then
		
                printf "\nStopping the $1 service...\n\n"
                systemctl stop $1
                check_service_response transmission-daemon 'stop'
				
        else
		
                printf "\nStarting the $1 service...\n\n"
                systemctl start $1
                check_service_response transmission-daemon 'start'
				
        fi
}

update_transd_bindip(){
        change_service_state transmission-daemon

        printf "\nUpdating the $transconf file with the new IP $tunip\n\n"
        # update the $transconf with the $tunip
        sed -i "s/\"bind-address-ipv4\": \".*\",/\"bind-address-ipv4\": \"$tunip\",/g" ${transconf}

        # start the transmission-daemon service
        change_service_state transmission-daemon
}

eval_and_update_transdbindip(){
        # If there is not tun0 IP then log the error and wait 5 mins
        if [[ ${tunip} == "" || ${tunip} == "0.0.0.0"  ]]; then

                printf "\nThere is no IP assigned to tun0\n\n"
                # Log the failure as an error and exit on code 2
                logger -p local0.err "transmission-ip-update : NordVPNs tun0 interface has no IP assigned"

        # if the transmission-daemon ipv4bindIP is the same as the tun0 IP on the VPN just log and wait 5 mins
        elif  [ "${transbindip}" == "    \"bind-address-ipv4\": \"${tunip}\"," ]; then

                printf "\nThe Transmission daemon and tun0 IP match\n\n"
                logger -p local0.info "transmission-ip-update : NordVPNs tun0 ip ${tunip} matches the file (${transconf} = ${transbindip})"

        # if the transmission-daemon ipv4bindIP is not the same as the tun0 IPs then update the config and service
        elif [ "${transbindip}" != "    \"bind-address-ipv4\": \"${tunip}\"," ]; then

                printf "\nThe transmission-daemon $transbindip does not match $tunip\n\n"
                logger -p local0.info "transmission-ip-update : new tun0 IP ${tunip} discovered, updating ${transconf}"
                update_transd_bindip

        fi
}

############################################################################################################
# Main Section, 5 minute infinite while loop calling functions & resetting $tunip variable
############################################################################################################
while true; do

	# First refresh the $tunip & $transbindip variables with the latest values
	tunip=$(ifconfig tun0 | grep 'inet' | awk '{print $2}')
	transbindip=$(grep "bind-address-ipv4" ${transconf})

	# Then call the function to compare the tun0 iface IP ($tunip) with the
	# transmission-daemon settings.json bind ipv4 ($transbindip) and take action
	eval_and_update_transdbindip

	# Then sleep for 5 mins and repeat these checks forever
	sleep 5m

done
############################################################################################################
# END
############################################################################################################
Categories
Ukategorisert

Ansible Notes

Vim indentation config

autocmd FileType yaml setlocal ai ts=2 sw=2 et
facts associated with a managed host can be obtained using the command:
ansible system_hostname -i inventory_file -m setup

ansible-playbook command with the --ask-pass for:

- name: Public key is deployed to managed hosts for Ansible
  hosts: all

  tasks:
    - name: Ensure key is in root's ~/.ssh/authorized_hosts
      authorized_key:
        user: root
        state: present
        key: '{{ item }}'
      with_file:
        - ~/.ssh/id_rsa.pub

Categories
Ukategorisert

RHEL Useful Commands

The following are some basic command references

Systemctl

systemctl reload-or-restart <servicename>

systemctl list-unit-files --state=[enabled|disabled]

systemctl list-unit-files --type=[service|other]

systemctl list-dependencies <servicename>

systemctl [mask|unmask] <servicename>

systemctl enable [--now] <servicename>

systemctl disable [--now] <servicename>

Output redirection (bash)

#redirect stdout to overwrite a file	
command > file
#redirect stdout to append to a file	
command >> file
#redirect stderr to overwrite a file	
command 2> file
#discard stderr error messages by redirecting to /dev/null
command 2> /dev/null
#redirect stdout and stderr to overwrite the same file
command > file 2>&1
command &>file
#redirect stdout and stderr to append to the same file
command >> file  2>&1
command &>>file

Bash shell expansions

{item1,item2…} for each of the items in the list

$VARIABLE – include the value of the variable

$() command substitution, execute the command and use the STDOUT results within the current command
e.g.: echo The day is $(date +%A).

glob patternresults
*zero or more characters.
?A single character
[abc...]Any one character in the selection
[!abc...]Any one character not in the selection
[^abc...]Any one character not in the selection
[[:alpha:]]Any single alphabetic character
[[:lower:]]Any single lowercase character
[[:upper:]]Any single uppercase character
[[:alnum:]]Any single alphabetic character or digit
[[:punct:]]Any single printable character not a space or alphanumeric
[[:digit:]]Any single digit from 0 to 9.
[[:space:]]Any single white space character

SELinux

# list processes with SELinux contexts
ps axZ

#list files with SELinux contexts
ls -Z

# Manage system wide SELinux
/etc/selinux/config

getenforce

setenforce


# he kernel argument enforcing=0 boots the system into permissive mode; 
# enforcing=1 sets enforcing mode.
# Disable SELinux completely by passing on the kernel parameter 
# selinux=0 disables
# selinux=1 enables  

# change context temporarily:
chcon -t httpd_sys_content_t 

# restore default contexts recursively -R with verbose output -v:
restorecon -Rv [directory|file]

# Inspect contexts
semanage fcontext -l

# Apply new context permanently (all files and directories below /virtual):
semanage fcontext -a -t httpd_sys_content_t '/virtual(/.*)?'
restorecon -RFvv /virtual

# SELinux boolean controls
# list all current boolean settings:
getsebool -a

# switch a boolean on or off temporarily:
setsebool <boolean name> [on|off]

# switch a boolean on or off permanently:
setsebool -P <boolean name> [on|off]

# list boolean states running which differ from the default state :
semanage boolean -l -C

# Investigate SELinux events:
tail /var/log/audit/audit.log
# look for "type=AVC" or "avc:  denied" or "scontext="

tail /var/log/messages
# look for "SELinux is preventing" and within the log "sealert -l <identifier>"

# To gather more detailed information on the SELinux event, using the identifier in the messages log:
sealert -l <identifier>

# also you can search messages for SELinux via:
ausearch -m AVC -ts recent

Disk Management

# list all block devices
lsblk 

# list /dev/vda partition table
parted /dev/vda print

# first define the partition table type 
parted /dev/vda mklabel  [msdos|gpt]

# create a partition of type xfs from the start to 1GB in size
parted /dev/vda mkpart primary xfs 2048s 1000MB

# for swap for the next logical partition and 500MB in size:
mkfs.xfs /dev/vda mkpart <name> linux-swap 1001MB 1501MB
swapon /dev/vda2
swapon --show

# make it permanent
lsblk --fs /dev/vda2
UUID=cb7f71ca-ee82-430e-ad4b-7dda12632328  swap  swap  defaults  0 0

# format that parition with a filesystem
mkfs.xfs /dev/vda1

Categories
Linux

Vi reminders

Cursor movement

  • h – move left
  • j – move down
  • k – move up
  • l – move right
  • w – jump by start of words (punctuation considered words)
  • W – jump by words (spaces separate words)
  • e – jump to end of words (punctuation considered words)
  • E – jump to end of words (no punctuation)
  • b – jump backward by words (punctuation considered words)
  • B – jump backward by words (no punctuation)
  • 0 – (zero) start of line
  • ^ – first non-blank character of line
  • $ – end of line
  • G – Go To command (prefix with number – 5G goes to line 5)

Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.

Insert Mode – Inserting/Appending text

  • i – start insert mode at cursor
  • I – insert at the beginning of the line
  • a – append after the cursor
  • A – append at the end of the line
  • o – open (append) blank line below current line (no need to press return)
  • O – open blank line above current line
  • ea – append at end of word
  • Esc – exit insert mode

Editing

  • r – replace a single character (does not use insert mode)
  • J – join line below to the current one
  • cc – change (replace) an entire line
  • cw – change (replace) to the end of word
  • c$ – change (replace) to the end of line
  • s – delete character at cursor and subsitute text
  • S – delete line at cursor and substitute text (same as cc)
  • xp – transpose two letters (delete and paste, technically)
  • u – undo
  • . – repeat last command

Marking text (visual mode)

  • v – start visual mode, mark lines, then do command (such as y-yank)
  • V – start Linewise visual mode
  • o – move to other end of marked area
  • Ctrl+v – start visual block mode
  • O – move to Other corner of block
  • aw – mark a word
  • ab – a () block (with braces)
  • aB – a {} block (with brackets)
  • ib – inner () block
  • iB – inner {} block
  • Esc – exit visual mode

Visual commands

  • > – shift right
  • < – shift left
  • y – yank (copy) marked text
  • d – delete marked text
  • ~ – switch case

Cut and Paste

  • yy – yank (copy) a line
  • 2yy – yank 2 lines
  • yw – yank word
  • y$ – yank to end of line
  • p – put (paste) the clipboard after cursor
  • P – put (paste) before cursor
  • dd – delete (cut) a line
  • dw – delete (cut) the current word
  • x – delete (cut) current character

Exiting

  • :w – write (save) the file, but don’t exit
  • :wq – write (save) and quit
  • :q – quit (fails if anything has changed)
  • :q! – quit and throw away changes

Search/Replace

  • /pattern – search for pattern
  • ?pattern – search backward for pattern
  • n – repeat search in same direction
  • N – repeat search in opposite direction
  • :%s/old/new/g – replace all old with new throughout file
  • :%s/old/new/gc – replace all old with new throughout file with confirmations

Working with multiple files

  • :e filename – Edit a file in a new buffer
  • :bnext (or :bn) – go to next buffer
  • :bprev (of :bp) – go to previous buffer
  • :bd – delete a buffer (close a file)
  • :sp filename – Open a file in a new buffer and split window
  • ctrl+ws – Split windows
  • ctrl+ww – switch between windows
  • ctrl+wq – Quit a window
  • ctrl+wv – Split windows vertically

thanks to Tim at https://www.worldtimzone.com