Here is a collection of commands I've picked up over time, when searching the Internet for answers to 'common questions'

Which usb device is which?

cat /proc/bus/input/devices
dmesg | grep usb

Mount remote FTP directory host into local linux filesystem

curlftpfs ftpuser:pass@location /mnt/mountpoint

Laptop display switching

xrandr -q | grep 'VGA-1 connected' && xrandr --output LVDS-1 --off --output VGA-1 --auto

Mounting Samba shares

mount -t cifs //server-name/share-name /mnt/cifs -o username=shareuser,password=sharepassword,domain=

http://www.thegeekstuff.com/2013/01/mount-umount-examples/
[Improving Performance]

Dstat - http://dag.wieers.com/home-made/dstat/#screenshot

Sysstat - http://www.maketecheasier.com/monitor-linux-performance-with-sysstat/2012/05/15

Ifstat - http://linux.softpedia.com/get/System/Networking/ifstat-14020.shtml

Sysctl -  When it comes to actual performance tuning, you'll want to know sysctl. The sysctl utility is actually used to configure kernel parameters stored in /proc/sys/. The parameters will change with each kernel version, and how it's configured. To see all the parameters that are available, run sysctl -a, or sysctl -a | sort if you want them alphabetically.

It should go without saying that if you're going to tweak these settings you should either be working on a test system, or be quite sure what you're doing. Or both. Preferably both.

To change one of the parameters, run sysctl -w key.value="newvalue". Note that this will only hold the change until the next time the system is rebooted. To make a setting permanent, you can add it to /etc/sysctl.conf.

Configure X11 server to start at login

sudo echo [[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && exec startx >> /etc/zsh/zprofile

Execute i3 on login

cp /etc/skel/.xinitrc ~
echo exec i3 >> ~/.xinitrc

Set keyboard layout for X

/etc/X11/xorg.conf OR /etc/X11/xorg.conf.d/00-keyboard.conf
Section "InputClass"
          Identifier "keyboard-all"
          Driver "evdev"
          Option "XkbLayout"    "us,bg"
      Option "XkbVariant"   "intl,phonetic"
          Option "XkbOptions"   "grp:alt_shift_toggle,grp_led:scroll"
          MatchIsKeyboard "on"
EndSection

Set touchpad to scroll

/etc/X11/xorg.conf.d/50-synaptics.conf
Section "InputClass"
        Identifier "touchpad catchall"
        Driver "synaptics"
        MatchIsTouchpad "on"
        Option "TapButton1" "1"
        Option "VertEdgeScroll" "1"
        Option "HorizEdgeScroll" "1"
EndSection

Set feh background image

feh --bg-scale /path/to/image.file

Set background image permanently

echo sh ~/.fehbg & >> ~.xinitrc

Fix VLC not opening folders

~/.config/vlc/vlcrc

# Demux module (string)
demux=any

# Demux module (string)
demux=

Lid close & lock

mkdir /etc/acpi/local
vim /etc/acpi/local/lid.sh.post

 #!/bin/bash
 if grep -q closed /proc/acpi/button/lid/*/state
 then
     DISPLAY=:0.0 su $USER -c /usr/bin/i3lock
     /usr/sbin/pm-suspend
 fi

Find out date of system creation

tune2fs -l /dev/sda1 | grep 'Filesystem created:'

Disable and enable SWAP

sudo swapoff -a
sudo swapon -a

Set Linux memory killer

For testing, you can just write to the proper pseudo-file in /proc/sys/vm/, which will be undone on the next reboot:

echo 1 | sudo tee /proc/sys/vm/oom_kill_allocating_task

For a permanent fix, write the following to /etc/sysctl.conf or to a new file under /etc/sysctl.d/, with a .conf extension (/etc/sysctl.d/local.conf for example):

vm.oom_kill_allocating_task = 1

Setting Linux limits

ulimit -a
/etc/security/limits.conf

Wireless under console

https://wireless.wiki.kernel.org/en/users/documentation/iw
getting device capabilities  -> iw list
scanning                     -> iw dev wlan0 scan
listen to events             -> iw event -t(iming) -f(assoc/dissassoc/deauth)
getting link status          -> iw dev wlan0 link
establish a basic connection -> iw wlan0 connect foo freq keys
getting station statistics   -> iw dev wlan0 station dump
modifying TX legacy bitrate  -> iw wlan0 set bitrates legacy-2.4(band) 12 18 24
modifying TX HT MCS bitrate  -> iw dev wlan0 set bitrates mcs-5(band) 4
settintg TX power            -> iw dev <devname> set txpower <auto|fixed|limit> [<tx power in mBm>]
                             -> iw dev <phyname> set txpower <auto|fixed|limit> [<tx power in mBm>]
get power save               -> sudo iw dev wlan0 set power_save
set power save on/off        -> sudo iw dev wlan0 set power_save on
adding interfaces            -> iw phy phy0 interface add moni0 type mnitor|managed|mesh|wds|ibss
deleting interface           -> iw dev wlan0 del

Get complete disk storage in linux

df -m | awk ' NR>1 {print $2}' | paste -s -d '+' | awk '{print "("$0")/1024"}'

Mount SSH

sshfs -o allow_other root@server:/home/whatever /mnt/mountpoint/

Mount Samba share

sudo mount.cifs -o uid=$UID //server/share /mnt/mountpoint

Remove Nvidia HD ALSA sound device

lspci | grep -i audio
Find the correct folder
find /sys/devices -name "*01:00.1*"
/sys/devices/pci0000:00/0000:00:01.0/0000:01:00.1/remove

And add this to the /etc/rc.local
echo 1 > echo 1 > /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.1/remove

ssh tunnel and Firefox proxy

ssh -C2qTnN -D 8080 root@192.168.0.1 -p 371
Configure Firefox to socks5 listen on 8080

maximize a X-window

wmctrl -l <-- get window id
wmctrl -i -r window_id -b toggle,maximized_vert,maximized_horz

listen to VLANs

ip link add link enp0s25 name eth0.100 type vlan id 100
ip -d link show eth0.100
ip addr add 192.168.100.1/24 brd 192.168.100.255 dev eth0.100
ip link dev eth0.100 up
ip link delete eth0.100 // removes the device

remove a line from file

sed '/pattern to match/d' ./file

Cmus update cache

:update-cache -f
To update only marked / selected files regardless of modification time
:win-update-cache -f

MySQL database commands

Show where the files are located

SHOW VARIABLES WHERE Variable_Name LIKE "%dir";

Show users

SELECT USER,HOST from mysql.user;

Show privileges

SHOW grants for '<user>'@'localhost';

Create database

CREATE DATABASE <database_name>;

Create user & grant privileges

CREATE USER '<user>'@'localhost' IDENTIFIED BY '<password>';
GRANT ALL PRIVILEGES ON <database_name> . * TO '<user>'@'localhost';
FLUSH PRIVILEGES;

Delete user

DROP USER '<user>'@'localhost';
FLUSH PRIVILEGES;

Backup / dump

mysqldump -u root -p <database_name>  > dumpfilename.sql

Restore

mysql -u root -p<root_password> <database_name> < dumpfilename.sql

Hijack SSH agent

export  SSH_AUTH_SOCK=/tmp/ssh-tqiEl28473/agent.28473

View contents of a .tar.gz & tar.bz2

tar -ztvf file.tar.gz
tar -jtvf file.tar.bz2

Create tar.gz file

tar -cvzf tarballname.tar.gz itemstocompress

Extract a tar file to a new folder

tar -xzvf tarballname.tar.gz -C /target/directory

SSH debug problem

debug2: channel 0: open confirm rwindow 0 rmax 32768

A problem can arise when you are trying to connect from behind a NAT router using OpenSSH. During session setup, after the password has been given, OpenSSH sets the TOS (type of service) field in the IP datagram. Some routers are known to choke on this. The fix is to make ssh send all its traffic via netcat, because netcat won't set the TOS field.

Test if nc resolves issue
-------------------------
ssh -o "ProxyCommand nc %h %p" {user-name}@server
If yes, then add: ProxyCommand nc %h %p to /home/.ssh/config

Add ACL recursively for user to folder

setfacl -R -m u:user:rwx /var/www/folder
Set sticky bit add user to group that has ownership of folder
chmod -R g+s /var/www/folder; usermod -a -G groupowner username

Removing unused headers

uname -r    <-- to determine the one in use
sudo rm -rf /usr/src/linux-headers-3.13.1-{37,39,41,43,44,46,48}{,generic}
sudo rm -rf /lib/modules/3.13.0-{37,39,41,43,44,46,48}*
sudo rm -rf /boot/*-3.13.0-{37,39,41,43,44,46,48}-generic
apt-get -f install
apt-get purge linux-{headers,image}-3.13.0-{37,39,41,43,44,46,48}.*

Connect to wifi from command line

wpa_supplicant -D nl80211,wext -i wlan0 -c <(wpa_passphrase "your_SSID" "your_key")

Change linux console font to support Bulgarian

setfont LatArCyrHeb-16

Allow ssh forwarding

visudo
Defaults    env_keep+=SSH_AUTH_SOCK

Check if IMAP is working

openssl s_client -connect imap.example.com:993
a1 LOGIN username password
a2 LIST "" "*"
a3 EXAMINE INBOX
a4 FETCH 1 BODY[]
a5 LOGOUT

status of raid device or partition

cat /proc/mdstat
mdadm --detail /dev/mdX
mdadm -E /dev/sda1
mdadm -Q /dev/sda1
mdadm -D /dev/sda1

mdadm stop array

mdadm --stop /dev/mdX

Replacing a failed RAID 1 drive

mdadm --manage /dev/mdX --fail /dev/sdXX
mdadm --manage /dev/mdX --remove /dev/sdXX
sfdisk -d /dev/sdY | sfdisk /dev/sdX
mdadm --manage /dev/mdX --add /dev/sdXX

mdadm update configuration

mdadm --examine --scan >> /etc/mdadm/mdadm.conf

mdadm create raid 1 array

mdadm --create --verbose /dev/mdX --level=1 --name=name:1 --raid-devices=2 /dev/sdaX /dev/sdbY

mdadm find arrays from livecd

mdadm --assemble --scan

mdadm expand raid5 array from 4 to 5 disks

mdadm --add /dev/md0 /dev/sdf1
mdadm --grow --raid-devices=5 --backup-file=/root/grow_md0.bak /dev/md0
umount /dev/md0
e2fsck -f /dev/md0
resize2fs /dev/md0

OpenWRT 15.05 fix pptp connections

opkg install kmod-nf-nathelper-extra

Get apache memory usage

ps -ylC apache2 | awk '{x += $8;y += 1} END {print "Apache Memory Usage (MB): "x/1024; print "Average Process Size (MB): "x/((y-1)*1024)}'

Set limits on systemd

vim /etc/systemd/system.conf
vim /etc/security/limits.conf

Use netcat to transfer files

on recv side: nc -l -p 7000 | tar x
on send site: tar cf - * | nc 192.168.0.2 7000

Use rsync with sudo to alter user:group permissions for transfered files

rsync -ru --owner=www-data --group=www-data --rsync-path="sudo rsync" --chown=www-data:www-data --progress --stats --human-readable ./testfile01.txt -e "ssh -p 2222" user@host:/home/user/

Attach to container in case of missing cgroup folders

lxc-attach --elevated-privileges -n <container_name>

Resize a virtual machine that has libvirt use LVM as storage and that has LVM inside it

1. Shutdown the VM
2. lvresize -L+10G /dev/vgvirt/test
3. Boot VM with systemrescuecd
4. Use fdisk to delete and create partitions anew
5. Resize the PV -- pvresize /dev/vda5
6. Resize the LV -- lvextend -l +100%FREE /dev/mapper/test-vg--root
7. Resize FileSystem -- resize2fs /dev/mapper/test-bg--root

Mount raw/qcow image

losetup /dev/loop0 /dev/mapper/vgvirt-test
kpartx -a /dev/loop0
mount /dev/mapper/loop0p1 /mnt

When down
dmsetup info
dmsetup remove loop0p1

Alternative way is to specify direct offset to partition:

mount image.img /mnt/image -o loop,offset=32256

To mount qcow2 images there is (at least in F-11 qemu) very useful qemu-nbd util. It shares image through kernel network block device protocol and this allows to mount it:

modprobe nbd max_part=63
qemu-nbd -c /dev/nbd0 image.img
mount /dev/nbd0p1 /mnt/image

If LVM is present on image it could be initialized with:

vgscan
vgchange -ay
mount /dev/VolGroupName/LogVolName /mnt/image

Finishing is done with (depending on how it was initalized):

umount /mnt/image
vgchange -an VolGroupName
killall qemu-nbd
kpartx -d /dev/loop0
losetup -d /dev/loop0

OR

modprobe nbd max_part=8
qemu-nbd --connect=/dev/nbd0 /home/dragast/disk2.qcow2
fdisk /dev/nbd0 -l
mount /dev/nbd0p1 /mnt/somepoint/
umount /mnt/somepoint/
qemu-nbd --disconnect /dev/nbd0

FOR LEGACY SSH INTO MIKROTIKS

ssh -oHostKeyAlgorithms=ssh-dss -oKexAlgorithms=diffie-hellman-group1-sha1 user@host

LDAP search

ldapsearch -h 127.0.0.1 -b "dc=example,dc=com" -x -D "cn=admin,dc=example,dc=com" -W "cn=*"
ldapsearch -D 'cn=admin,dc=example,dc=com' -W -x -b 'dc=example,dc=com' 'uid=*'

# Find people belonging to specific group
ldapsearch -x -W -H ldaps://<HOST> -D 'OU=Users,DC=example,DC=com' -b 'DC=example,DC=com' '(&(objectClass=person)(memberOf=CN=<<GROUP_NAME>>,OU=Groups,DC=example,DC=com))'

LDAP change command line password

ldappasswd -h 127.0.0.1 -x -D "cn=admin,dc=example,dc=com" -W -S "uid=peter.petrov,ou=People,dc=example,dc=com"

LDAP delete user

ldapdelete -x -D "cn=admin,dc=example,dc=com" -W 'uid=kor,ou=People,dc=example,dc=com'

LDAP add schemas

Let's add a schema. It will first need to be converted to LDIF format. You can find unconverted schemas in addition to converted ones in the /etc/ldap/schema directory.

It is not trivial to remove a schema from the slapd-config database. Practice adding schemas on a test system.

Before adding any schema, you should check which schemas are already installed (shown is a default, out-of-the-box output):

sudo ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=schema,cn=config dn

dn: cn=schema,cn=config

dn: cn={0}core,cn=schema,cn=config

dn: cn={1}cosine,cn=schema,cn=config

dn: cn={2}nis,cn=schema,cn=config

dn: cn={3}inetorgperson,cn=schema,cn=config

he following example we'll add the CORBA schema.

Create the conversion configuration file schema_convert.conf containing the following lines:

include /etc/ldap/schema/core.schema
include /etc/ldap/schema/collective.schema
include /etc/ldap/schema/corba.schema
include /etc/ldap/schema/cosine.schema
include /etc/ldap/schema/duaconf.schema
include /etc/ldap/schema/dyngroup.schema
include /etc/ldap/schema/inetorgperson.schema
include /etc/ldap/schema/java.schema
include /etc/ldap/schema/misc.schema
include /etc/ldap/schema/nis.schema
include /etc/ldap/schema/openldap.schema
include /etc/ldap/schema/ppolicy.schema
include /etc/ldap/schema/ldapns.schema
include /etc/ldap/schema/pmi.schema

Create the output directory ldif_output.

Determine the index of the schema:

slapcat -f schema_convert.conf -F ldif_output -n 0 | grep corba,cn=schema

cn={2}corba,cn=schema,cn=config

When slapd ingests objects with the same parent DN it will create an index for that object. An index is contained within braces: {X}.

Use slapcat to perform the conversion:

slapcat -f schema_convert.conf -F ldif_output -n0 -H ldap:///cn={2}corba,cn=schema,cn=config -l cn=corba.ldif

The converted schema is now in cn=corba.ldif

Edit cn=corba.ldif to arrive at the following attributes:

dn: cn=corba,cn=schema,cn=config
...
cn: corba

Also remove the following lines from the bottom:

structuralObjectClass: olcSchemaConfig
entryUUID: 52109a02-66ab-1030-8be2-bbf166230478
creatorsName: cn=config
createTimestamp: 20110829165435Z
entryCSN: 20110829165435.935248Z#000000#000#000000
modifiersName: cn=config
modifyTimestamp: 20110829165435Z

Your attribute values will vary.

Finally, use ldapadd to add the new schema to the slapd-config DIT:

sudo ldapadd -Q -Y EXTERNAL -H ldapi:/// -f cn\=corba.ldif

adding new entry "cn=corba,cn=schema,cn=config"

Confirm currently loaded schemas:

sudo ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=schema,cn=config dn

dn: cn=schema,cn=config

dn: cn={0}core,cn=schema,cn=config

dn: cn={1}cosine,cn=schema,cn=config

dn: cn={2}nis,cn=schema,cn=config

dn: cn={3}inetorgperson,cn=schema,cn=config

dn: cn={4}corba,cn=schema,cn=config

Enter postgresql

su - postgres
psql --username=postgres

View decoded ssl certificate

openssl x509 -in certfile.crt -text -noout

View chain certs ALSO: When constructing a bundle file the order is (from top of file to bottom) your_domain.cert -> your intermediate.cert -> your root auth.cert

openssl crl2pkcs7 -nocrl -certfile file.crt | openssl pkcs7 -print_certs -text -noout

BTRFS show info

btrfs fi show

BTRFS show usage

btrfs fi df /mount/point

BTRFS start rebalance

btrfs fi balance start -dusage=5 /mount/point

BTRFS monitor rebalance

btrfs balance status /mountpoint
btrfs balance status /mountpoint

Wget recursive download

wget --cut-dirs=2 -r --no-host-directories --no-parent --reject "index.html*" -e robots=off https://<host>

LXD add bridge to default config

lxc profile device add default eth1 nic nictype=bridged parent=br1

Add a cryptokey for automatic unlock of partition

/etc/default/grub add cryptkey=rootfs:path to GRUB_CMDLINE_LINUX; aka GRUB_CMDLINE_LINUX=".. cryptkey=roofs:/file.bin"

Create LVM snapshot

lvcreate -L<size>G -s -n nameofbackup /dev/vgroup/volume

Restore snapshot

lvconvert --merge /dev/vgroup/snapshotname

Configure networking on CentOS

/etc/sysconfig/network-scripts/ifcfg-devicename

Connect to KVM hypervisior

virsh connect qemu:///system
virsh -c qemu:///system

Show all KVM guests

virsh list

Get all info on KVM guest

virsh dumpxml <guest_name>

Add disk to KVM guest

virsh # attach-disk <guestname>  /dev/sdb9 vdj

Start postgresql in debug mode

su - postgres
/usr/lib/postgresql/9.3/bin/postgres -d 3 -D /var/lib/postgresql/9.3/main -c config_file=/etc/postgresql/9.3/main/postgresql.conf

Find all necessary folders in a container and print their permissions, user and group

ionice -c 2 find . -type d \( -name dev -o -name proc -o -name sys -o -name tmp -o -name run -o -name mnt -o -name media -o -name lost+found \) -prune -o -exec stat -c "%N %a %u %g" {} \; > /home/username/outfile.txt

Boot when wrong crypto password is specified at the GRUB prompt

grub rescue> ls
grub rescue> cryptomount -a
grub rescue> insmod normal
grub rescue> normal

Show unique active connections and their status

netstat -tan | grep ':80 ' | awk '{print $6}' | sort | uniq -c

Import a zpool to an alternate location

zpool import -m -R <mount location> <pool name>

Get into Gentoo chroot environment

mount --rbind /dev dev
mount --rbind /proc proc
mount --rbind /sys sys
env -i HOME=/root TERM=$TERM chroot . bash -l

Fix Gentoo Locale

eselect locale list
eselect locale <locale number>
source /etc/profile

Find all the space consuming directories and show their size

find / -maxdepth 1 -type d -not -path "/" -not -path "/proc" -not -path "/dev" -not -path "/sys" -not -path "/run" -exec du -sh {} \;

Show all directory permissions in the path

namei -l </path/>

Create a clamscan cron-ready script

/usr/bin/clamscan --recursive --infected /srv/sites --move /home/clamav/infected -l /home/clamav/clamscan_$(date +%Y-%m-%d)

Samba ldap dump all objects

ldbsearch -H /var/lib/samba/private/sam.ldb '(objectclass=*)'

Show current system disk read/write speed

iostat -dmy 1

Check and set disk queue scheduler

grep . /sys/block/sd*/queue/scheduler
echo [deadline,noop,cfq] > /sys/block/sda/queue/scheduler

Crontab explanation

*     *     *   *    *  <command to be executed>
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

Resize LVM and ext4 filesystem

lvresize -r -L +10G /dev/mapper/vg/lv

Cisco set user ask on login

router#conf t
router(config)username root password <paswd>
router(config)#line vty 0 4
router(config-line)#login local

curl grep expiration date of cert

curl -v https://site.com --stderr - | grep "*  expire date:"

SSH forward local port via one hop

ssh -L 8888:10.0.0.1:22 root@10.0.0.11
        ^      ^     ^          ^
        |      |     |          \- hop through which to go through
        |      |     \- remote port
        |      \- remote IP
        \- local port

Bind mount a folder to a LXD container

lxc config device add {containername} {foldername_inside} disk source={path/to/folder} path={path/inside/the/container}

Bind mount an LVM partition to a LXD container

lxc config device add {containername} {device name} unix-block path=/dev/mapper/vg/

Add A record to zone in knot DNS

knotc zone-begin lan.example.org
knotc zone-set lan.example.org lan.example.org. 3000 A 1.1.1.1
knotc zone-diff lan.example.org
knotc zone-commit lan.example.org
knotc zone-read lan.example.org

Calculate amazon ssh key fingerprints

If ~/.ssh/ec2/primary.pem is a key generated by EC2 itself:
openssl pkcs8 -in ~/.ssh/ec2/primary.pem -nocrypt -topk8 -outform DER | openssl sha1 -c

If ~/.ssh/ec2/primary.pem is a private key you generated yourself and from which you created a public key and imported that into EC2:
openssl pkey -in ~/.ssh/ec2/primary.pem -pubout -outform DER | openssl md5 -c

List all current LXD operations

curl -s --unix-socket /var/lib/lxd/unix.socket a/1.0/operations | jq .

Get info on specific LXD operation

curl -s --unix-socket /var/lib/lxd/unix.socket a/1.0/operations/008bc02e-21a0-4070-a28c-633b79a46517 | jq .

Get openssl for mail server

echo | openssl s_client -connect mail.site.com:465 2>/dev/null | openssl x509 -noout -dates

iscsiadmin commands

iscsiadm -m node --portal 10.0.0.1 --logout
iscsiadm -m session -P 1
iscsiadm -m discovery -t st -p 10.0.0.1

use freebsd netcat to transfer KVM LVM images

on recv side: nc -l 4444 > /dev/mapper/vg0-test
on send side: cat /dev/mapper/vgvirt-test | pv | nc 10.0.0.0 4444
copy and edit the .xml file (network, storage device)
restart libvirt: systemctl restart libvirtd.service

Do a command on all containers on host

for container in `lxc list | awk 'NF > 1 {print $2}' | awk '(NR > 1) && (!/\|/) {print}'`; do lxc config show $container; done
for container in $(lxc list | awk '(NR > 2) && (NF > 1) {print $2}'); do lxc config show $container; done

Resize a partiton and a filesystem

# Add new disk to the system that can contain the expanded partition
# Copy the original disk layout to the new disk
sfdisk -d /dev/sdX > /tmp/orig_disk_partition_table
# sfdisk /dev/sdY < /tmp/orig_disk_partition_table
# Delete the partition and create it with the new size (if there is a SWAP partition after the root one, delete and recreate it as well)
# If partition starts at sector 63 instead of 2048, use compatability for DOS
fdisk /dev/sdY
d
n
p
1
+size
e2fsck -f /dev/sdY1
resize2fs /dev/sdY1
# If SWAP was recreated
mkswap /dev/sdY2
blkid
mount /dev/sdY1 /mnt
vim /etc/fstab # Edit the SWAP partition UUID
# Possibly regenerate the grub config
mount -t proc none /mnt/proc
mount -o bind /dev /mnt/dev
mount -t sysfs sys /mnt/sys
chroot /mnt/ /bin/bash
update-grub
/usr/sbin/grub-install --recheck --no-floppy /dev/sdY

Explanation of megacli RAID levels

# Explanation of Raid Levels:
['Primary-0, Secondary-0, RAID Level Qualifier-0'] = RAID-0
['Primary-1, Secondary-0, RAID Level Qualifier-0'] = RAID-1
['Primary-5, Secondary-0, RAID Level Qualifier-3'] = RAID-5
['Primary-6, Secondary-0, RAID Level Qualifier-3'] = RAID-6
['Primary-1, Secondary-3, RAID Level Qualifier-0'] = RAID-10

Bind put updates in master zone

vim zonefile
rndc freeze ZONE in VIEW
rndc reload ZONE in VIEW
rndc thaw ZONE in VIEW

HP embeded raid controller commands

show all physical devices

hpssacli ctrl slot=0 pd all show all

show all logical devices

hpssacli ctrl slot=0 ld all show all

create raid 1 from pd 1 and 2

hpssacli ctrl slot=0 create type=ld drives=1I:1:1,1I:1:2 raid=1

input licensekey

hpssacli controller slot=0 licensekey 34T62-N84MB-7DQGY-G7XGT-YTQ63

create a raid 0 from pd4 (to expose disk to OS)

hpssacli ctrl slot=0 create type=ld drives=1I:1:4 raid=0

show full logical device stats

hpssacli ctrl slot=0 ld 3 show detail

show full logical device status

hpssacli ctrl slot=0 ld 3 show status

rescan for new devices

hpssaacli ctrl slot=0 rescan

turn on and off led on pd 2

hpssacli ctrl slot=1 ld 2 modify led=on
hpssacli ctrl slot=1 ld 2 modify led=off

show controller configuration in detail

hpssacli ctrl slot=0 show config detail

ssacli force enable a logical drive

ssacli controller slot=0 ld 2 modify reenable forced

How to restore an app from TWRP recovery

get data partition on to computer's disk and untar
intall app again from store
push app data from root adb
adb push data/com.fsck.k9/* /data/data/com.fsck.k9/
dumpsys package com.fsck.k9 | grep userId
chown -R $id:$id /data/data/com.fsck.k9/
restorecon -Rv /data/data/com.fsck.k9

Flash hard disk leds

hdparm -tT /dev/sdX

Set tmux copy mode to vi bindings

set-window-option -g mode-keys vi
Ctrl+B + [  // enter copy mode
Space       // Start selection
Enter       // End selection | Leave copy mode
Ctrl+B + ]  // Paste
bind-key -T copy-mode-vi 'v' send -X begin-selection
bind-key -T copy-mode-vi 'y' send -X copy-selection-and-cancel
set-option -g lock-command vlock // enable vlock for tmux
set-option -g lock-after-time 900 // Lock after 15 mins of inactivity

Mikrotik for loop to set property

:for i from 2 to 12 do={ /routing filter set $i set-in-nexthop=1.1.1.1 }

Quagga down peer

vtysh
vtysh# conf t
(config)# router bgp <AS number>
(config-router)# neighbor <IP addr> shutdown
(config)#

Quagga restat network connection to peer

clear bgp <neighbour IP>

Get process ID per container

cd /sys/fs/cgroup/memory/lxc && for i in $(echo */); do echo $i && cat $i/cgroup.procs; done

Suppress annoying messages in console

dmesg -n 4

Allow insecure MD5 hashes for TLS connections for OpenVPN

Weak (MD5) hashes in certificate signature (SSL_CTX_use_certificate md too weak)
Starting with OpenSSL version 1.1, OpenSSL rejects weak signatures in certificates like MD5.

MD5 signatures are insecure and should not be used anymore. MD5 collisions can be created in few hours at a minimal cost.. You should update the VPN certificates as soon as possible.

Unfortunately, older easy-rsa distributions included the config option "default_md md5". If you are using an old easy-rsa version, update to the latest version) or change md5 to sha256 and regenerate your certificates.

If you really want to use old and broken certificates use the custom configuration option tls-cipher "DEFAULT:@SECLEVEL=0"

Generate new CA file for OpenVPN from old CA file

openssl x509 -in ca.crt -days 4650 -out ca_new.crt -signkey ca.key

Add atlassian products as services

bamboo_istall_dire$ ln -s atlassian-bamboo-X.Y/ current
vim /etc/init.d/bamboo

#!/bin/sh
set -e
### BEGIN INIT INFO
# Provides: bamboo
# Required-Start: $local_fs $remote_fs $network $time
# Required-Stop: $local_fs $remote_fs $network $time
# Should-Start: $syslog
# Should-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Atlassian Bamboo Server
### END INIT INFO
# INIT Script
######################################

# Define some variables
# Name of app ( bamboo, Confluence, etc )
APP=bamboo
# Name of the user to run as
USER=bamboo
# Location of application's bin directory
BASE=/opt/atlassian/bamboo/current

case "$1" in
  # Start command
  start)
    echo "Starting $APP"
    /bin/su - $USER -c "export BAMBOO_HOME=${BAMBOO_HOME}; $BASE/bin/startup.sh &> /dev/null"
    ;;
  # Stop command
  stop)
    echo "Stopping $APP"
    /bin/su - $USER -c "$BASE/bin/shutdown.sh &> /dev/null"
    echo "$APP stopped successfully"
    ;;
   # Restart command
   restart)
        $0 stop
        sleep 5
        $0 start
        ;;
  *)
    echo "Usage: /etc/init.d/$APP {start|restart|stop}"
    exit 1
    ;;
esac

exit 0
chmod a+x /etc/init.d/bamboo
update-rc.d bamboo defaults // For Debian
/sbin/chkconfig --add bamboo // For RedHat

create a single mdraid-autodetect parition with sfdisk

echo ',,fd;' | sfdisk /dev/sdb

Create and mount tmpfs

mount -t tmpfs -orw,nodev,nosuid,size=1G tmpfs /tmp/

VIM delete statements on multiple lines

\_s finds newline or space or tab: an underscore adds a newline to any character class
Get youtube url for RSS
<div id="microformat">
<title>FreqGen - YouTube</title>
<link rel="canonical" href="https://www.youtube.com/channel/UCKTPHbGGXtZ8xKoRCx3Wj4Q">

Add ssh-agent as a user systemd service and load keys automatically

mkdir -p .config/systemd/user
vim .config/systemd/user/ssh-agent.service

[Unit]
Description=SSH key agent

[Service]
Type=forking
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target


vim .zshrc
# Add SSH-agent
export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"

systemctl --user enable ssh-agent
systemctl --user start ssh-agent

vim .ssh/config
AddKeysToAgent yes

Gzip and encrypt logs

# Create new gpg key
gpg --full-generate-key

root@mantis:/var/log/nginx# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
  daily
  missingok
  rotate 14
  compress
  compresscmd /root/logrotate_encrypt.sh
  compressext .gz.gpg

root@mantis:/var/log/nginx# cat /root/logrotate_encrypt.sh
#!/bin/bash
# This captures all datastream input and saves it as a single file, that is then passed to gzip and gpg
echo "$(cat)" | gzip | gpg -e -r "logs@test.com"

Restrict user to specific command via .ssh/authorized_keys

command="/usr/bin/rsync --server --sender -logDtpre.iLsf ./var/backups/postgres/",no-pty,no-agent-forwarding,no-port-forwarding <ssh-key>

Add user/password for Basic Auth

echo -n 'user:' >> /etc/nginx/.htpasswd
openssl passwd -apr1 >> /etc/nginx/.htpasswd

Arch live CD grow /, cowspace, rootfs

mount -o remount,size=1G cowspace

awk get only IP addr from ip command

ip -o -4 a show eth0 | awk '/inet/ {split($4,ip,"/"); print ip[1]}'

When installing Arch Linux on md-raid and LVM at the same time

1. Create md-raid
2. Create LVM pv, vg and lv on the RAID
3. Modify /etc/mkinitcpio.conf and add the following line
HOOKS=(base systemd udev autodetect modconf block mdadm_udev sd-lvm2 filesystems keyboard fsck)

gentoo livecd mount proc, dev, sys and chroot

root # mount -t proc /proc /mnt/proc
root # mount --rbind /sys /mnt/sys
root # mount --make-rslave /mnt/sys
root # mount -rbind /dev /mnt/dev
root # mount --make-rslave /mnt/dev
root # chroot /mnt /bin/bash
root # source /etc/profile

Using heredocs in bash

read -r -d '' VARIABLE_NAME << 'EOF' <- quoted EOF will not expand $variables | EOF (unquoted will expand) 
$text more text
$text22 etc
EOF

Show MySQL table charset

SELECT table_name,CCSA.character_set_name FROM information_schema.TABLES T, information_schema.COLLATION_CHARACTER_SET_APPLICABILITY CCSA WHERE CCSA.collation_name = T.table_collation AND T.table_schema = 'TEST'

Show MySQL row charset

SELECT table_name,column_name,character_set_name FROM information_schema.`COLUMNS` WHERE table_schema = 'TEST' AND character_set_name is not NULL order by character_set_name;

Print all tables and columns with varchar type

awk 'START {table=""} /CREATE TABLE/,/^)/ {if (/CREATE TABLE/) {gsub("`","",$3) ; table=$3} ; if (/varchar/) {gsub("`","",$1) ; print table"."$1}}' test.sql

Get all Authorized Bulgarian Certificate Authorities by the EU

Using only valid certificates, then check if their names DON'T contain any OCSP, or timestamp (TSA, TSP, TiMeStAmP) and then append BEGIN and END to the certificates
curl -X GET "https://esignature.ec.europa.eu/efda/tl-browser/api/v1/browser/tl/bg" -H  "accept: application/json" | jq -r '.serviceProviders[].services[] | select(.active == true) | select(.digitalIdentity.certificates[].subjectShortName | ascii_downcase | test("ocsp| tsa| tsp|time|timestamp"; "i") | not) | "-----BEGIN CERTIFICATE-----\n" + .digitalIdentity.certificates[].base64 + "\n-----END CERTIFICATE-----"'

Scan for new hard disks

for host in /sys/class/scsi_host/*/scan; do echo "$host" && echo "- - -" > "$host"; done

Update disk size

echo 1 > /sys/class/block/sdX/device/rescan

Align format from any shell command via xargs and printf

curl -s -X GET --header "PRIVATE-TOKEN: <TOKEN_HERE>" https://gitlab/api/v4/projects/<PROJ>/members/all | jq -r '.[] | .name, (.access_level | tostring | sub("30" ; "developer") | sub("50"; "owner")) | @sh' | xargs printf "%-30s\t%s\n"

Printf repeated symbols

printf '=%.0s' {1..15}

List http headers via tcpdump

tcpdump -A -qni any -s 0 'tcp port <PORT_NUMBER> and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'

Remote tcpdump to local wireshark

ssh user@host 'tcpdump -qni any <FILTER> -s 0 -w -' | wireshark -k -i -

Convert pem to pkcs12

openssl pkcs12 -export -out Cert.p12 -in cert.pem -inkey key.pem -passin pass:root -passout pass:root

Fix pecl wrong PHP directory intall

pecl config-set php_suffix 7.4

Fetch key from ubuntu keyserver when behind apt-cacher-ng-proxy

apt-key adv --keyserver-options http-proxy=<proxy-ip>:3142/ --keyserver keyserver.ubuntu.com --recv-keys <key>

Invalidate SSSD cache for local user (AD)

sss_cache -u <user>

Run command inside temporary docker container

docker run --rm -it -v $PWD:/tmp <docker image> /bin/bash
--rm    == remove after exit
-it     == interactive TTY
-v      == mount directory : to /tmp inside container

Get IIS Server host/bindings via PowerShell

Import-Module Webadministration
Get-ChildItem -Path "IIS:\Sites"

tail -f | grep for Windows PowerShell

Get-Content <filename> -Tail 1 -Wait | where {$_.contains("pattern")}

Migrate LXD to new ZFS pool

  1. Create new LUKS encrypted partition
    cryptsetup --type luks2 --cipher aes-xts-plain64 --hash sha512 --iter-time 5000 --key-size 512 --pbkdf argon2id --use-urandom --verify-passphrase luksFormat /dev/sdXY
    cryptsetup --type luks2 --cipher aes-xts-plain64 --hash sha512 --iter-time 5000 --key-size 512 --pbkdf argon2id --use-urandom --verify-passphrase luksFormat /dev/sdXY
    
  2. Open new crypto devices
    cryptsetup open /dev/sdXY crypto_disk_01
    cryptsetup open /dev/sdXY crypto_disk_02
    
  3. Create new ZFS pool (assuming 4K sectors aka ashift=12)
    zpool create -f -o ashift=12 -O compression=zstd -O dnodesize=auto -O normalization=formD -O relatime=on -O xattr=sa <newtank> mirror /dev/mapper/crypto_disk_01 /dev/mapper/crypto_disk_02
    
  4. Stop all LXD containers
    lxc stop <container01> <container02>...
    
  5. Create a snapshot of the original pool/tank
    zfs snapshot -r <tank>@MIGRATION
    
  6. Send the snapshot to the new pool/tank
    zfs send -Rpv <tank>@MIGRATION | zfs receive -dFu <newtank>
    
  7. Delete the source pool/tank snapshot
    zfs destroy <tank>@MIGRATION
    
  8. Export the source pool/tank
    zpool export <tank>
    
  9. Change the LXD database to reflect the changes
    zfs send -Rpv <tank>@MIGRATION | zfs receive -dFu <newtank>
    
  10. Destroy destination pool/tank snapshot
    zfs destroy <newtank>@MIGRATION
    
  11. Commit LXD changes to disk
    lxd sql global .sync
    
  12. Start all containers with new storage
    lxc start <container01> <container02>...
    

F5 BigIP delete boot slot

tmsh delete sys software volume HD1.X

Lenovo IMM get port status

ipmitool raw 0xc 0x2 0x1 0xc0 0x0 0x0

The output will be one of the following:
11 00 00 - indicates shared on-board (expected here)
11 01 00 - indicates dedicated on-board
11 02 00 - indicates shared add-in (via ML2 adapter)

Lenovo IMM set port state

# Set to Dedicated mode
ipmitool raw 0xc 0x1 0x1 0xc0 0x1

# Set to Shared mode
ipmitool raw 0xc 0x1 0x1 0xc0 0x0

Linux set IPMI lan and user settings

# Do the network setup
ipmi lan print 1
ipmitool lan set 1 ipsrc static
ipmitool lan set 1 ipaddr XXX.XXX.XXX.XXX
ipmitool lan set 1 netmask 255.255.255.0
ipmitool lan set 1 defgw ipaddr XXX.XXX.XXX.XXX
ipmitool lan set 1 auth ADMIN MD5
ipmitool lan set 1 access on

# Verify the config
ipmitool lan print 1

# Get the users
ipmitool user list 1

# Create new user
ipmitool user set name 4 <USER>

# Set the password
ipmitool user set password 4

# Set the privilege level
ipmitool channel setaccess 1 4 link=on ipmi=on callin=on privilege=5

# Enable the user
ipmitool user enable 4

# Verify the user config
ipmitool user list 1

F5 change LCD status

# To show the current status
tmsh list sys db lcd.showmenu

# To disable the LCD panel
tmsh modify sys db lcd.showmenu value disable

# To enable the LCD panel
tmsh modify sys db lcd.showmenu value enable

Use curl to check HTTP and decrypt via Wireshark

SSLKEYLOGFILE=/tmp/curl_ssl_decrypt.log curl -A 'Debian APT-HTTP/1.3' https://url/path/to/resource

FFProbe get filename, size, codec, filename and duration

ffprobe -v error -hide_banner -select_streams v:0 -of default=noprint_wrappers=0 -print_format json -show_entries format=filename,size:stream=codec_name,duration,width,height <filename>

Openssl extract only x509v3 extensions from certificate

openssl x509 -in <filename> -noout -text -certopt no_header,no_version,no_signame, -certopt no_validity,no_subject,no_issuer,no_pubkey,no_sigdump,no_aux,no_serial

OpenSSL verify certificate, private key and CSR match

openssl req -noout -modulus -in  server.csr | openssl md5

openssl rsa -noout -modulus -in myserver.key | openssl md5

openssl x509 -noout -modulus -in ssl-bundle.crt | openssl md5

Decrypt Jenkins secret

  1. Navigate to /script
  2. Input encrypted key into script below
    println hudson.util.Secret.decrypt("{<ENCRYPTED_KEY_HERE>}") 
    

Upgrade PostgreSQL clusters

  1. Install new MAJOR version (ex 15)
    apt install postgresql-15 postgresql-client-15
    
  2. Check current clusters
    pg_listclusters
    
  3. If cluster for 15 is created, stop it
    pg_dropcluster --stop 15 main
    
  4. Start cluster upgrade
    pg_upgradecluster 14 main
    
  5. Start new cluster
    systemctl start postgresql@15-main.service
    
  6. Drop (delete) all cluster and it's data
    pg_dropcluster 14 main
    

Helpfull iSCSI commands

Discover available targets from a discovery portal:

iscsiadm -m discovery -t sendtargets -p ipaddress

Login to all targets:

iscsiadm -m node -l

Log into a specific target:

iscsiadm -m node -T targetname -p ipaddress -l

Log out of all targets:

iscsiadm -m node -u

Log out of a specific target:

iscsiadm -m node -T targetname -p ipaddress -u

Display information about a target:

iscsiadm -m node -T targetname -p ipaddress

Display statistics of a target:

iscsiadm -m node -s -T targetname -p ipaddress

Display a list of all current sessions logged in:

iscsiadm -m session

View iSCSI database regarding discovery:

iscsiadm -m discovery -o show

View iSCSI database regarding targets to login to:

iscsiadm -m node -o show

View iSCSI database regarding sessions logged in to:

iscsiadm -m session -o show

Find the newly created device name, using the iscsiadm command. In this test configuration, the new volume is /dev/sdb. At the end of the output you could see attached scsi disk name.

iscsiadm -m session -P3

Remove terminal colors

sed -e 's/\x1b\[[0-9;]*m//g'

Map PostgreSQL database and table names to /var/lib/postgresql files

SELECT oid FROM pg_database WHERE datname='mydb'
SELECT oid, relname FROM pg_class WHERE relname = 'mytable';

Run ffprobe in parallel to multiple video files

find /location -type f -name '*.mp4' | parallel 'ffprobe -v error -show_entries format=filename,duration,size -of csv="p=0:s=\ "' :::

Use find to locate a file with string containing current directory then copy and rename file to local directory

find /location -type f -name "*$(basename ${PWD})*" -exec bash -c 'cp -v ${@} $(basename ${@/pending_/})' _ {} \;

Useful perl one-liner to find the start of line and search untill the next for pattern

if (/(^\w+)/) { if (defined $start) {print "$start - FAIL" unless $seen} $start = $1 ; $seen = 0;} if (/PATTERN2/ and defined $start) {print "$start - OK"; $seen = 1} END {print "$start - FAIL" if defined $start and !$seen}'

Create safe DEVICE_ADMIN_PACKAGE_CHECKSUM

cat name-of-APK-latest.apk | openssl dgst -binary -sha256 | openssl base64 | tr '+/' '-_' | tr -d '='

Use curl's resolve feature

curl --resolve example.com:443:192.168.0.1 https://example.com/