Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

Common Linux Commands

This is a collection of linux commands that have been helpful to me. Some are definitely better documented than others...

Active Directory / SSSD / Samba

#various methods to join and remove from AD based on OS version and AD settings
kinit admin@CORP.DOMAIN.COM
net ads join -v -k -U admin@CORP.DOMAIN.COM createcomputer="/ORG/Servers/LinuxServers"
net ads join -v -k -U admin@CORP.DOMAIN.COM -d10 createcomputer="/ORG/Servers/LinuxServers"
net ads join -v -U createcomputer="/ORG/Servers/LinuxServers"
adcli delete-computer -U admin@CORP.DOMAIN.COM -W -v computer
adcli join -U admin@CORP.DOMAIN.COM -v
adcli join -U admin@CORP.DOMAIN.COM -O "ou=LinuxServers,ou=Servers,ou=ORG,dc=corp,dc=domain,dc=com" -v
adcli join -v --show-details --domain-ou="ou=LinuxServers,ou=Servers,ou=ORG,dc=corp,dc=domain,dc=com" --login-user=admin --add-samba-data
realm leave

#show kerberos realms
realm list 

#show kerberos tickets
klist -ke

#destroy kerberos tickets
rm -f /etc/krb5.keytab

#join domain
realm join -v -U admin@CORP.DOMAIN.COM --computer-ou="ou=LinuxServers,ou=Servers,ou=ORG"

#leave and rejoin domain as one line (yes realm leave has to be executed twice sometimes)
realm leave; realm leave; kdestroy; rm -f /etc/krb5.keytab; realm join -v -U admin --computer-ou="ou=LinuxServers,ou=Servers,ou=ORG";

#clear SSSD cache
sss_cache -E 
rm -rf /var/lib/sssd/db/*
systemctl restart sssd

#fix samba shares not working after samba 4.9 update
net -s /dev/null groupmap add sid=S-1-5-32-546 unixgroup=nobody type=builtin


#awk print all after a specific field
awk '{ for (i=2; i<=NF; i++) print $i }'


Input / Output Redirection

Redirection can be configured using the "<" and ">" operators. Typically they are used just as you see them and redirect data in the direction they are pointing. Programs must be written to use these and thankfully, most linux/unix utilities are. Here are some examples using standard input (STDIN file descriptor "0") and standard output (STDOUT file descriptor "1"):

#input redirection - attach a file to an email
Mail -s "Subject" to-address < Filename

#creates file.log or replaces the contents if it already exists
grep ip_address /var/log/httpd/server_access.log > file.log

#appends to the contents of file.log or creates if it does not exist
grep ip_address /var/log/httpd/ssl_server_access.log >> file.log

Most commands send their output to STDOUT (file descriptor "1") but sometimes they send it to STDERR (file descriptor "2"). Sending this content to a log or just getting it off the screen can be done by adding a "2" to the ">" or "<" operators:

virt-customize [arguments] 2> /tmp/virt-customize.log
Mail -s "Subject" to-address <2 virt-customize [arguments]


#convert human readable timestamp to epoch
date "+%s" -d "Oct 28 15:30:11 2020 GMT"

#convert epoch to human readable timestamp
date -d @1603899011


curl -sSLk -D - -o /dev/null
curl -vsSLk > /dev/null

#prettify JSON output (yum install jq first)
curl ... | jq


diff -rq folder1 folder2
diff -wbr folder1 folder2

dnf / yum

sudo yum update --disablerepo=
sudo yum update --disablerepo=percona-release-noarch --disablerepo=percona-release-x86_64

yum updateinfo list security installed
yum updateinfo list sec
yum -y update --security
dnf -y update --security

sudo yum groupinstall "X Window System"

yum repolist
yum --disablerepo="*" --enablerepo="[ius]" list available |grep XXX

#install specific version of rpm package
yum --showduplicates list [package]
yum install [package-name]-[version].[architecture]

#yum update notice says it is broken or a bad duplicate
yum check-update --verbose 
yum clean all; yum check-update

#show which repo packages were installed from (requires yum-utils to be installed)

#check for packages that depend on an installed package
dnf repoquery --alldeps --whatrequires [package]
dnf repoquery --installed --whatrequires [package]


find . -ctime -5 #find files created in 5 hours or less
find . -mtime -5 #find files modified in 5 hours or less
find . -cmin -5 #find files created in 5 minutes or less
find . -mmin -1 #find files modified in 1 minute or less
find /usr/local/ -maxdepth 2 -name server.xml
find /usr/local -d -maxdepth 1
find . -type f -printf '%T@ %p\n' | sort -k1,1nr | head -5 #find 5 most recently modified files in a folder (date -d "@xxxxxx" to convert to human readable timestamp)


firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 1 -j ACCEPT
firewall-cmd --permanent --direct --remove-rule ipv4 filter INPUT 1 -j ACCEPT
firewall-cmd --permanent --zone=public --add-rich-rule='rule family=ipv4 source address= port protocol=tcp port=1842 accept'
firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" forward-port to-addr="" to-port="51253" protocol="udp" port="51253"'
firewall-cmd --permanent --new-zone=wireguard
firewall-cmd --permanent --zone=wireguard --change-interface=wg0
firewall-cmd --permanent --zone=public --add-masquerade
firewall-cmd --zone=public --add-port=5044/tcp
firewall-cmd --zone=public --remove-port=5044/tcp
firewall-cmd --get-services
firewall-cmd --add-service=ssh --permanent
firewall-cmd --remove-service=ssh --permanent
#reload is required after any command with --permanent in it
firewall-cmd --reload
firewall-cmd --list-all
#**WARNING**--list-all doesn't show direct rules, and maybe other stuff... WTF?!
firewall-cmd --runtime-to-permanent


git init .
git add ./
git commit -m "Initial Base Project"
git push --set-upstream master
git remote add origin

~/.gitconfig example


    ui = true

[color "branch"]
    current = yellow reverse
    local = yellow
    remote = green

[color "diff"]
    meta = yellow bold
    frag = magenta bold
    old = red bold
    new = green bold

[color "status"]
    added = yellow
    changed = green
    untracked = red

    name = C3P0
    email =


#flags to remember
-v, --invert-match: select non-matching lines
-f FILE, --file=FILE: use patterns from file, one per line
-i, --ignore-case
-x, --line-regexp
-l, --files-with-matches
-L, --files-without-match
-H, --with-filename
-h, --no-filename
-r, --recursive

#list only files that include pattern
grep -lr [pattern] [path]

#exclude blank lines
grep -v -e "^#\|^[[:space:]]*$" [path]

#search for multiple values
grep "pattern1\|pattern2\|pattern3" [path]

#show "missing" lines - exist in one file but not the other
for h in `cat hosts_real.txt`; do if ! grep -q "$h" hosts_nessus.txt; then echo $h; fi; done
grep -vf hosts_nessus.txt hosts_real.txt

#more detailed example and reverse use cases
#in this example, the breakfix_current file has machines in it that no longer exist on our network, and some that still have a warranty - we want both of those kind of entries removed. Also, we want to check to see if there are machines on our network that do not have a warranty but are not yet included in the breakfix_current list so we can add them. 
#First we check to see if any machines listed in the breakfix_current no longer exist in the pc_list_current (the full, live PC inventory list).
for s in `cat breakfix_current`; do if ! grep -q "$s" pc_list_current; then echo $s; fi; done > old_pcs
#then create a new file with old_pcs removed from breakfix_current
for s in `cat breakfix_current`; do if ! grep -q "$s" old_pcs; then echo $s; fi; done > bf_current_live
#then we check the warranty status list against the new bf_current_live list
for s in `cat has_warranty`; do if grep -q "$s" bf_current_live; then echo $s; fi; done > bf_has_warranty
#combine old_pcs and bf_has_warranty lists to show all that should be removed
cat old_pcs bf_has_warranty > bf_remove_list
#create new file showing live PCs without warranty
for s in `cat pc_list_current`; do if ! grep -q "$s" has_warranty; then echo $s; fi; done > live_pcs_no_warranty
#create list of live PCs with no warranty to add to the breakfix list
for s in `cat live_pcs_no_warranty`; do if ! grep -q "$s" breakfix_current; then echo $s; fi; done > add_pcs_to_breakfix

#and here are more concise grep statements to do the same thing (these run much faster when dealing with large files)
grep -vf pc_list_current breakfix_current > old_pcs
grep -vf old_pcs breakfix_current > bf_current_live
grep -f bf_current_live has_warranty > bf_has_warranty
cat old_pcs bf_has_warranty > bf_remove_list
grep -vf has_warranty pc_list_current > live_pcs_no_warranty
grep -vf breakfix_current live_pcs_no_warranty > add_pcs_to_breakfix


awk -F\' /^menuentry/{print\$2} /etc/grub2.cfg
#grub2-set-default 1 #whatever number matches what you want (list starts at 0)
grub2-reboot 1 #whatever number matches what you want (list starts at 0)
yum -y remove kernel-uek kernel-uek-devel

#show assigned boot kernel 
grub2-editenv list
#set to default latest kernel
sudo grub2-editenv /boot/grub2/grubenv set saved_entry=0


#show LVM basic config / stats

#show LVM detailed config / stats

#After increasing the virtual disk in the virtual platform, rescan the scsi disks within the OS:
for disk in /sys/class/scsi_disk/*; do echo '1' > $disk/device/rescan; done

#increase physical volume size to full disk
pvresize -v /dev/sdb

#increase physical volume size by specific amount
pvresize -v --setphysicalvolumesize [insert new size here]g /dev/sda2

#increase logical volume size
lvresize -v -L +32g /dev/vg01/lv_var_lib_prometheus

#grow XFS volume 
xfs_growfs /var/lib/prometheus

#grow EXT4 volume
resize2fs /var/lib/prometheus

multi-line replace

perl -i -0pe 's/<url-pattern>\/text\/\*<\/url-pattern>\n    <\/web-resource-collection>\n    <auth-constraint>\n       <role-name>manager-script<\/role-name>/<url-pattern>\/text\/\*<\/url-pattern>\n    <\/web-resource-collection>\n    <auth-constraint>\n       <role-name>manager-script<\/role-name>\n       <role-name>LinuxAdmins<\/role-name>\n       <role-name>TomcatDevelopers<\/role-name>/' file_name
import re
file = open("file_path", "w")
file_text =
text_updated = re.sub(r'<url-pattern>/text/\*</url-pattern>\n    </web-resource-collection>\n    <auth-constraint>\n       <role-name>manager-script</role-name>\n', r'<url-pattern>/text/*</url-pattern>\n    </web-resource-collection>\n    <auth-constraint>\n       <role-name>manager-script</role-name>\n       <role-name>LinuxAdmins</role-name>\n       <role-name>TomcatDevelopers</role-name>\n', file_text)

import os
import pprint
pp = pprint.PrettyPrinter()

import struct; print(struct.calcsize("P") * 8)


mongo --host hostname
use admin
    user: "mongoadmin",
    pwd: passwordPrompt(),
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]


#ping scan
nmap -sn [target]

#check for open port but don't ping
nmap -p 3389 -Pn [target]

#`ls /usr/share/nmap/scripts` to see available
nmap --script ssh2-enum-algos hostname.fqdn
nmap --script ssl-enum-ciphers -p 443 hostname.fqdn
nmap --script ssh2-enum-algos,ssl-enum-ciphers hostname.fqdn


#generate random password
openssl rand -base64 12

#extract PFX and create new pkcs12 file
openssl pkcs12 -in corp_wildcard_5.pfx -nocerts -out corp-wildcard-key.pem
openssl pkcs12 -in corp_wildcard_5.pfx -out corp-wildcard-cert.pem -nokeys
openssl pkcs12 -export -in corp-wildcard-cert.pem -inkey corp-wildcard-key.pem -out corp-wildcard-cert.p12 -name corp-wildcard -CAfile corp-ca.pem -caname "CORP CA" -chain

#convert PFX/pkcs12 to JKS
keytool -importkeystore -srckeystore corp-wildcard-cert.p12 -destkeystore corp-wildcard-keystore.jks -srcstoretype pkcs12 -deststoretype JKS

#create self-signed cert
openssl req -x509 -sha256 -newkey rsa:2048 -keyout sha256-2048.key -out sha256-2048.pem -days 1024 -nodes

#add/remove password from key
openssl rsa -aes256 -in your.key -out your.encrypted.key
openssl rsa -in your.encrypted.key -out your.key

#get SSL certificate chain; first cert should be site, followed by intermediate and then root CAs
echo quit |openssl s_client -connect -showcerts

#get first SSL cert in certificate chain
openssl s_client -showcerts -connect </dev/null 2>/dev/null|openssl x509 -outform PEM > certfile.pem

#list certificates in CA bundle
openssl crl2pkcs7 -nocrl -certfile cert-bundle.pem | openssl pkcs7 -print_certs -text -noout |less

#check issue date for CRL
openssl crl -in ./crl.pem -lastupdate -noout 

#show sha1 certificate fingerprint to compare with keytool list (use md5 or sha256 to get those)
openssl x509 -in ./cert.pem -noout -text -fingerprint -sha1 |grep Fingerprint 

#openssl-custom.cnf to generate certs for Windows from Linux/Cygwin
req_extensions = v3_req
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment #add 'dataEncipherment' for Sonatype Nexus
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

DNS.1 =
DNS.2 =
DNS.3 =
DNS.4 = *

#openssl create key and req (CSR) commands
openssl genrsa -out 4096
openssl req -new -out -key -config openssl-custom.cnf

pandoc themes

Syntax highlighting for code blocks use the Haskell "skylighting" library. The list of languages pandoc will recognize can be shown with pandoc --list-highlight-languages.

There are several built-in themes or you can use your own. To list the built-in themes, run pandoc --list-highlight-styles. Export any of the existing themes by running pandoc --print-highlight-style [style_name] > [style_name].theme. Then edit the theme as desired and use it with pandoc --highlight-style my.theme.

edit the kate or default "pygments" theme with this to make it easier to read: "text-color": null, "background-color": "#f8f8f8", "line-number-color": "#aaaaaa", "line-number-background-color": null,

To produce a custom reference.docx, first get a copy of the default reference.docx with: pandoc -o custom-reference.docx --print-default-data-file reference.docx. Then open custom-reference.docx in Word, modify the styles as you wish, and save the file. It can be used with the --reference-doc=path_to_file or put it in the user data directory (--data-dir - "%userprofile%\AppData\Roaming\pandoc" on Windows and "$HOME/.pandoc" on Linux).

pandoc examples

c:\utils\pandoc\pandoc.exe --from markdown --reference-doc=c:\utils\pandoc\reference.docx --output dest_file.docx
c:\utils\pandoc\pandoc.exe -t gfm -s file.docx -o --extract-media=file_media
pandoc -s -o file.docx --reference-doc=/cygdrive/c/utils/pandoc/reference.docx
pandoc -s -o file.docx --reference-doc=c:\utils\pandoc\reference.docx 
pandoc -s file.docx -o -t gfm --extract-media=./file_media 


psql -U postgres

help:                                       \?
quit:                                       \q
show history:                               \s
save history to file:                       \s filename
execute commands from file:                 \i filename
list databases:                             \l
list users:                                 \du
connect to database:                        \c db_name
list tables:                                \dt
describe specific table:                    \d table_name
switch output to HTML:                      \H
switch output between aligned/unaligned:    \a
show db version:                            select version();

find empty tables:

select n.nspname as table_schema, c.relname as table_name
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where c.relkind = 'r'
      and n.nspname not in ('information_schema','pg_catalog')
      and c.reltuples = 0
order by table_schema,


connect to PuppetDEV server:

puppet agent --server puppetdev --no-daemonize -v -t

fix puppet Error: Could not connect via HTTPS to -

sudo mv /opt/puppetlabs/puppet/ssl/cert.pem /opt/puppetlabs/puppet/ssl/cert.pem.bak
sudo ln -s /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /opt/puppetlabs/puppet/ssl/cert.pem

common certificate signing commands:

sudo puppetserver ca clean --certname[,,hostname3...]
sudo puppetserver ca list
sudo puppetserver ca sign --certname[,,hostname3...]
sudo puppetserver ca sign --all

upgrade puppet modules:

for m in `puppet module list |grep puppet |grep v[0-9] |awk '{print $2}'`; do puppet module upgrade --modulepath=/etc/puppetlabs/code/environments/production/modules $m; done


#unit testing
python -m unittest test_corp_web_apps.CorpURLTestAvailable
python -m unittest test_corp_web_apps.CorpURLTestLinks
python -m unittest test_corp_web_apps.CorpSeleniumChecks

#create or upgrade python virtualenv (same command):
python -m venv ./python_venvs/env_name

#upgrade already installed pip module:
pip install --upgrade module_name

#create requirements.txt:
pip freeze > requirements.txt

#install from requirements.txt:
pip install -r ./requirements.txt

#send email
import smtplib, ssl

port = 587  # For starttls
smtp_server = ""
sender_email = ""
receiver_email = ""
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
#download file from URL
import urllib.request 
url = ''
with urllib.request.urlopen(url) as response, open('/path/to/file', 'wb+') as real_rootca_crl_outfile:
    data =

#work with date / datetime
import subprocess
from datetime import datetime 
from datetime import timdelta

current_time =
crl_time_format = "%b %d %H:%M:%S %Y %Z"
crl_lastupdate ="openssl crl -in " + path_to_crl_file + " -noout -lastupdate |awk -F= '{print $2}'",
str_crl_lastupdate = crl_lastupdate.stdout.decode('utf-8').strip('\n')
date_crl_lastupdate = datetime.strptime(str_crl_lastupdate, crl_time_format)


#rebuild RPM database ( 
mkdir /var/backups
tar -zcvf /var/backups/rpmdb-$(date +"%d%m%Y").tar.gz  /var/lib/rpm
rm -f /var/lib/rpm/__db*
/usr/lib/rpm/rpmdb_verify /var/lib/rpm/Packages
rpm -vv --rebuilddb

rm -f /var/lib/rpm/__db*; /usr/lib/rpm/rpmdb_verify /var/lib/rpm/Packages; rpm --rebuilddb


#append to beginning of line if pattern match:
sed '/isbz120:\/data02\/oradata/ s/^/#/' /etc/fstab
#add a new line after a pattern match:
sed '/#isbz120:\/data02\/oradata/a entbackint:\/ifs\/smdc\/corp\/corp_ora\/rman_corp       \/oradata\/remote     nfs     rw,bg       0 0' /etc/fstab
#delete a line:
sed '/\/mnt\/oracle\/accimg/d' /etc/fstab
#replace a whole line containing a phrase or word
#there's no need for the extra search on the second example, but it does the same thing
sed 's/.*service_port.*/        service_port: "8443"/'
sed -i '/FirewallBackend=/ s/.*FirewallBackend=.*/FirewallBackend=iptables/' /etc/firewalld/firewalld.conf

sed '/DOMAIN/ s/^'
sed -i -e '/^DOMAIN=/ c\DOMAIN=""'
sed '/^pattern.*/a after=me' test.txt
sed '/^pattern.*/i before=me' test.txt

#case insensitive search/replace
iwconfig wlo1 |sed s/00:10:FA:6E:38/UpstairsAP/I |sed s/66:A5:EF:A8:0B/DownstairsAP/I

#replace value between quotes
sed -i '/Default Folder/ s/path="[^"][^"]*"/path="\/var\/lib\/syncthing\/data\/Sync"/' /var/lib/syncthing/etc/config.xml

#work with file paths
cat file_paths.txt | sed 's/\//\\\//g' > sed_paths
#show the changes that would be made
for p in `cat sed_paths`; do sed --quiet "s/$p/#$p/p" /path/to/config_file ; done
for p in `cat sed_paths`; do sed --quiet 's/'"$p"'/'"#$p"'/p' /path/to/config_file ; done
#make the changes
for p in `cat sed_paths`; do sed -i "/$p/ s/^/#/" /path/to/config_file ; done
for p in `cat sed_paths`; do sed -i '/'$p'/ s/^/#/' /path/to/config_file ; done


setenforce 0 #to set selinux to permissive mode
getenforce # to show selinux mode 
sestatus # show more details about SELinux status
setsebool -P httpd_can_network_connect on
setsebool -P httpd_use_cifs on
semanage port -a -t http_port_t -p tcp 8888
semanage fcontext -a -s system_u -t httpd_passwd_exec_t "/etc/httpd/private/.ssl_passphrase"
semanage fcontext -a -s system_u -t samba_var_t "/var/lib/samba(/.*)?"
restorecon -R -v /var/www/html 


setfacl -R -bn /usr/local/apache-2.4.41/htdocs
setfacl -R -d -m /usr/local/apache-2.4.4
setfacl -R -m /usr/local/apache-2.4.4
setfacl -R -d -m g::rwx /usr/local/symmetricds
setfacl -R -m g::rwx /usr/local/symmetricds
for f in `ls`; do getfacl $f |setfacl --set-file=- -R $f; done


systemctl stop snmpd; net-snmp-create-v3-user -ro -A [password] -a MD5 -x DES [username]; systemctl start snmpd;


sqlite3 filename.db
.schema table
select * from rrs_closures order by id desc limit 10; 
select * from rrs_incidents where event like '%town%'; 


<logon> is: {<username>[/<password>][@<connect_identifier>] | / }
<connect_identifier> can be in the form of Net Service Name
    or Easy Connect.

      @[<net_service_name> | [//]Host[:Port]/<service_name>]

sqlplus jaspertmp@DEVLNX


systemctl list-units --state=failed
journalctl -u service-name -f
systemctl get-default
systemctl set-default
systemctl set-default

#systemd/systemctl timers - cron job replacement
systemctl list-timers
# start a service in 12 hours and 30 minutes
systemd-run --on-active="12h 30m" --unit someunit.service
# run a command 30 seconds from now
systemd-run --on-active=30 /bin/touch /tmp/foo


tar --acls --same-owner -pzcf
tar --acls --same-owner -zxf


sudo twadmin --generate-keys -L /etc/tripwire/${HOSTNAME}-local.key
sudo twadmin --generate-keys -L /etc/tripwire/site.key
twadmin --create-cfgfile -S /etc/tripwire/site.key /etc/tripwire/twcfg.txt
twadmin --create-polfile -S /etc/tripwire/site.key /etc/tripwire/twpol.txt
sudo tripwire --init
sudo tripwire --check | grep Filename |awk '{print $2}' |sed 's/\//\\\//g' > sed_paths
for p in `cat sed_paths`; do sed -i "/$p/ s/^/#/" /etc/tripwire/twpol.txt ; done
sudo tripwire --init
#once the policy file is generated from the last "tripwire --init", it can be saved/used on other machines. Verify???


#list sessions
tmux ls 

#attach session
tmux a -t [session_name]:

#disconnect a session
CTRL+b d 

#kill session
CTRL+b :kill-session

#enter scroll mode (allows you to view previous buffer contents)
CTRL+b [

#search in scroll mode
CTRL+r #enter value to search for and hit enter. Press n to find next value. Will search "up".

#exit scroll mode

#use vi key bindings in scroll/copy buffer
CTRL+b :setw -g mode-keys vi

#create a horizontal split
CTRL+b "
#create a vertical split 
CTRL+b %

#move/swap windows 
CTRL+b :
swap-window -s 3 -t 1 #swap 3 with 1
swap-window -t 1 #swap current window with a specific window (1 in this case)
swap-window -t -1 #move current window to the left
swap-window -t +1 #move current window to the right

#tmux preferences
#show current working directory on left-hand status bar, increase path length to 48 change update interval to every second (default 15 seconds), set active window status to different color, increase default scroll-back value for new panes
tmux set -g status-left "#{pane_current_path} - "
tmux set -g status-interval 1
tmux set -g status-left-length 64
tmux tmux set-window-option -g window-status-current-bg blue
tmux set -g history-limit 5000
#echo "set-option -g history-limit 5000" >> ~/.tmux.conf

#SSH AUTH Forwarding
#add the following to ~/.ssh/rc
if [ -S "$SSH_AUTH_SOCK" ]; then
    ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock

#and then 


#allow ip to forward all traffic through
ufw route allow from

#allow all traffic routed to eth2 and coming in on eth1 to traverse the firewall
ufw route allow in on eth1 out on eth2

#allows any packets coming in on eth0 to traverse the firewall out on eth1 to tcp port 80 on
ufw route allow in on eth0 out on eth1 to port 80 proto tcp


#vim search and replace regular expression examples: 
%s/\(service_port: "\)\([0-9]\{2,5}\)\("\)/service_port: \2/
%s/\(app_name: "\)\([a-zA-Z]*\)\("\)/app_name: \2/
%s/\(tomcat_instance: "\)\([a-z]*\)\("\)/tomcat_instance: \2/

#vim show diff without actually writing or saving changes: 
:w !diff % -

#vim delete lines containing a pattern

#vim show whitespace characters:
:set listchars=eol:$,nbsp:_,tab:>-,trail:~,extends:>,precedes:<
:set list
:set nolist 

#vim show settings:
:set value?
:set listchars?
:set paste?

#vim 8 add packages 
mkdir -p ~/.vim/pack/vendor/start/puppet 
git clone ~/.vim/pack/packages/start/puppet

git submodule add vim/pack/vendor/start/vim-airline
git add .gitmodules vim/pack/vendor/start/vim-airline
git commit

#vim 8 remove packages
git submodule deinit vim/pack/vendor/start/vim-airline
git rm vim/pack/vendor/start/vim-airline
rm -Rf .git/modules/vim/pack/vendor/start/vim-airline
git commit


#vm commands
virsh list --all #list all VMs/domains
virsh list #list all running VMs/domains
virsh start VM 
virsh shutdown VM #ACPI shutdown (gracefully)
virsh destroy VM #force shutdown
virsh undefine VM #delete VM (still need to remove/manage storage)
virsh undefine VM [--remove-all-storage] [--delete-storage-volume-snapshots] [--snapshots-metadata] #only use if you're sure
virsh autostart VM
virsh autostart disable VM

#network commands
virsh net-list #list networks
virsh net-dhcp-leases NET #show dhcp leases on specific network, usually "default"
virsh domiflist VM #list network interfaces on VM/domain
virsh domifstat VM INT #show network statistics for interface in VM

#storage commands
virsh pool-list
virsh domblklist VM #show block storage devices attached to VM/domain
virsh domblkstat diskname vda --human
virsh detach-disk VM PATH_TO_DISK --persistent #remove disk from VM
virsh attach-disk VM PATH_TO_DISK TARGET --persistent #target is [vd|sd|hd][a,b,c...]
virsh vol-delete diskname.qcow2 --pool default #delete storage device

#add firewall rules after libvirtd starts
firewall-cmd --direct --add-rule ipv4 filter LIBVIRT_FWI 2 -p tcp --destination --destination-port 3389 -j ACCEPT

vs code

Keyboard Shortcuts

    // Toggle between terminal and editor focus
    { "key": "ctrl+`", "command": "workbench.action.terminal.focus"},
    { "key": "ctrl+`", "command": "workbench.action.focusActiveEditorGroup", "when": "terminalFocus"}



#create files of specific size
truncate -s 5M 5mb.file
fallocate -l $((5*1024*1024)) 5mb.file

#split files
split -b 1024m big_file big_file-part

#gpg encrypt files
for f in `ls |grep big_file-part`; do gpg --passphrase-file ./pass --batch --symmetric --cipher-algo AES256 --output $f.gpg $f; done

#gpg decrypt file
gpg --decrypt filename.gpg > filename

#gpg on mobaxterm
gpg2 --symmetric --cipher-algo AES256 --output filename.gpg filename
gpg2 --decrypt filename.gpg > filename

#monitor file transfer progress
progress -M
progress -mp

rsync -viaPAXS [--exclude=PATTERN] [--log-file=PATH] source dest
-i, --itemize-changes       output a change-summary for all updates
-a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
-P                          same as --partial --progress
-A, --acls                  preserve ACLs (implies -p)
-X, --xattrs                preserve extended attributes
-S, --sparse                handle sparse files efficiently
-r, --recursive             recurse into directories
-l, --links                 copy symlinks as symlinks
-p, --perms                 preserve permissions
-t, --times                 preserve modification times
-g, --group                 preserve group
-o, --owner                 preserve owner (super-user only)
-D                          same as --devices --specials
-H, --hard-links            preserve hard links
-z, --compress              compress file data during the transfer (only use over slow WAN links)


tcpdump -s0 -vv -w tcp_dump.pcap tcp port 1842
tcpick -C -yP -r tcp_dump.pcap

#restart stuck gnome session
#ALT+F2, then "r" and Enter is preferred, but if that doesn't do anything, open a CLI terminal (CTRL+ALT+F6) and run this:
killall -3 gnome-shell

#add fonts without rebooting
fc-cache -fv [optional_extra_fonts_folder]

#crop/resize a 1280×720 rectangle from a 1920×1080 resolution video with a starting rectangle position of 10, 10
ffmpeg -i in.mp4 -filter:v "crop=1280:720:10:10" out.mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment