Linux Advanced Tips

Here is a small memo for some advanced commands or one-liners that I found useful.

Check a port on a host every 5 seconds

while :; do echo -n `date +"[%Y-%m-%d %H:%M:%S]"`; echo -n "  "; nc -z 192.168.1.1 3389; if [ $? -eq 0 ]; then echo OK; else echo Unreachable; fi; sleep 5; done;

When you just added yourself a group, and do not want to reboot immediately:

  • To use webdev group id (and privileges) in your current shell use:
newgrp webdev
  • To start a command with some group id (and keep current privileges in your shell) use:
sg webdev -c "command"
  • Add this alias to your .profile to take quick notes with date in the filename:
alias vimn='f(){ vim `date +%Y%m%y-%H%M`_$1.txt; unset -f f; }; f'

Add this alias to your .profile to generate gpg encrypted messages in the console:

alias gpgb="echo '' | vipe | gpg -e --sign -a -r usr1@example.com -r usr2@example.com"

You can add extra recipients with -r behind the alias

Delete Docker generated DNS redirection (useful when it breaks):

LINE=$(iptables -t nat -L DOCKER-INGRESS --line-numbers | grep -E 'DNAT.*udp dpt:domain' | awk '{print $1};') && [ ${#LINE} -gt 0 ] && echo "Docker DNS DNAT rule was found at line $LINE in DOCKER-INGRESS chain." && iptables -t nat -D DOCKER-INGRESS $LINE

Convert images to a certain size, and use progressive jpeg with resize (in the example 1200px wide)

convert original.jpg -resize 1200 -define jpeg:extent=90k -interlace plane smaller.jpg

Convert all JPEG in a folder to progressive JPEG (backup before)

mogrify -interlace plane *.jpg

Test your jinja2 code in iPython REPL, for instance before placing it into Ansible playbook. Here is an example with mapping short codes to values:

In [42]: from jinja2 import Template

In [43]: Template(
    ...: 'Host Group: {{ host_groups.get(ansible_hostname.split("-")[2], "Missing host_group in host_groups") }}'
    ...: ).render(
    ...: ansible_hostname="mynet-qa-es-003",
    ...: host_groups={
    ...: 'rtk': 'RethinkDB',
    ...: 'dbms': 'MySQL',
    ...: 'pg': 'PostgreSQL',
    ...: 'es': 'ElasticSearch',
    ...: }
    ...: )
Out[43]: 'Host Group: ElasticSearch'