Unix reminder

All those little things, that as a unix newbie, i keep forgetting.
apache | asm | awk | bash | bc | convert | cut | debian apt-get | docker | emacs | enscript | exim | gentoo | git | iptables | kernel | make | mount | mutt | ps | qemu | sabayon | sed | ssh-keygen | svn | tail | tcsh | ubuntu | uml | virtualbox

Apache

Proxy configuration Enable the right modules:
a2enmod proxy
a2enmod proxy_http
a2enmod proxy_html
Perform the correct configuration:
        <Proxy *>
           Allow from all
           Require all granted
        </Proxy>
        <Location "/path_in_url/">
          Order allow,deny
          Allow from all
          # do not forget the '/' at the end
          ProxyPass "http://127.0.0.1:8888/"
          ProxyPassReverse "http://127.0.0.1:8888/"
        </Location>
Prevent to access the *.inc files:
<FilesMatch \.inc$>
    Require all denied
</FilesMatch>

Asm

Example of asm directives for use in gnu programs:
#include <stdio.h>
int main(void) {
        int foo = 10, bar = 15;
        __asm__ __volatile__("addl  %%ebx,%%eax"
                             :"=a"(foo)               /* ensures foo (a) is the output */
                             :"a"(foo), "b"(bar)      /* ensures foo is maped to a and bar to b */
                             );
        printf("foo+bar=%d\n", foo);                  /* displays 25 */
        return 0;
}

Awk

Lines of an apache log file look like:
127.0.0.1 - - [24/May/2004:05:06:01 +0200] "GET /keepalive.html HTTP/1.0"
In order to sort IP addresses of the log files by frequency type:
cut -d ' ' -f 1 < /var/log/apache/access.log | awk -f count.a | sort -n
Where count.a is the following script:
{ counter[$1] += 1 }
END { for (u in counter)
        printf "%d %s\n", counter[u], u
}

Bash

Setting the prompt

To get a prompt like user@host /path/to/current/dir $ which displays current path as the title of the xterm window add to your bashrc:
PS1='\[\033]0;\w\007\033[32m\]\u@\h \[\033[33m\w\033[0m\] $'
Sequence \[\033]0;\w displays current path (\w) as xterm title.
Sequence \033[32m\]\u@\h displays user@host in green.
Sequence \[\033[33m\w\033[0m\] display path (\w) and return to default color.
Example from gentoo:
# for root
export PS1='\[\033[01;31m\]\h\[\033[01;34m\] \W \$\[\033[00m\] '
# for other users
export PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\]'
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\007"'

Redirections

Redirect standard out and standard error separately:
$ cmd > stdout-redirect 2> stderr-redirect
Redirect standard error and out together:
$ cmd > stdout-redirect 2>&1
Merge standard error with standard out and pipe:
$ cmd 2>&1 | cmd2

'If' tests

Here is how to do something if a file my_file.txt contains pattern pattern:
if [[ $(grep pattern my_file.txt | wc -l) -gt 0 ]]
then echo "Stuff found"
else echo "Stuff not found"
fi

'For' loops

Here is a complicated way to do ls:
for i in `ls *~`; do echo $i; done
Which is equivalent to
for i in `ls *~`
do
  echo $i
done

'While' loops

Here is how to display numbers from 0 to 10:
i=0; while [ $i -le 10 ] ; do echo $i ; i=$((i+1)) ; done
Here is another construct to increment i:
i=0; while [ $i -le 10 ] ; do echo $i; let "i += 1"; done
Do do infinite loop use the empty command ':' which always returns true:
while : ; do sleep 2 ; printf '.' ; done

'Case' tests

    case $n in 
    0 )
      echo n is 0
      ;;
    1 )
      echo n is 1
      ;;
    * )
      echo $n is not 0 or 1
      ;;
    esac

Random number

Here is how to set variable n to a random value between 0 and 10:
RANGE=10
n=$RANDOM
let "n %= $RANGE"

Functions

Here is how to do functions:
function my_fun {
  w=$1
  h=$2
  echo this is the body of function my_fun
  echo with arguments w=$w and h=$h  
}
my_fun 123 345
my_fun 90 30
interesting link

bc

Here is how to define functions in bc:
define fact (x) {
  if (x <= 1) return (1);
  return (fact(x-1) * x);
}
define comb(n,p) {
  return ((fact(n)/fact(p))/fact(n-p));
}
If bc is invoked with the -l option, a math library is preloaded. The loaded functions are: s (sinus), c (cosinus), l (natural logarithm), a (arctangent), e (exponentiation). For instance:
l(2)
.69314718055994530941
4*a(1)
3.14159265358979323844

Convert

To put side by side two images :
convert img1.jpg img2.jpg +append out.jpg
To put one image above the other:
convert img1.jpg img2.jpg -append out.jpg
To change colors use the -recolor option with the 3x3=9 parameters of the matrix
# to green :
convert in.jpg -recolor "0 0 0 0 1 0 0 0 0" out.jpg # out.jpg is in.jpg with green channel only
# to blue
convert in.jpg -recolor "1 0 0 0 0 0 0 0 0" out.jpg 
# to red
convert in.jpg -recolor "0 0 0 0 0 0 0 0 1" out.jpg
# with the identity matrix nothing changes
convert in.jpg -recolor "1 0 0 0 1 0 0 0 1" out.jpg #out.jpg is in.jpg
# lighten the image :
convert in.jpg  -recolor "1 .7 .7  .7  1 .7   .7 .7 1" out.jpg

Cut

Fields

Lines of an apache log file look like:
127.0.0.1 - - [24/May/2004:05:06:01 +0200] "GET /keepalive.html HTTP/1.0"
In order to list IP addresses of the log file:
cut -d ' ' -f 1 < /var/log/apache/access.log
Option -d ' ' specifies that space is the delimiter. Option -f 1 means 'return first field'.

Characters

To get only columns between column i and j type cut -ci-j. For instance on get only process number type:
ps | tail +2 |  cut -c0-5
The tail +2 is only here to remove first line of the output of the ps command.

debian apt-get

To get the new key for apt-get type as root:
wget http://ftp-master.debian.org/ziyi_key_2006.asc -O - | apt-key add -
For unattended upgrade
  sudo dpkg-reconfigure -plow unattended-upgrades

Docker

create image from scratch

No container is running
$docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
Create an image under ubuntu
sudo debootstrap bionic bionic > /dev/null
sudo tar -C bionic -c . | docker import - bionic
test the image
$docker run bionic cat /etc/lsb-release
One container was running
$docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS               NAMES
cad0564c0867        bionic              "cat /etc/lsb-release"   6 seconds ago       Exited (0) 4 seconds ago                       serene_nightingale
delete this info
$docker rm cad0564c0867
image list
$docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
bionic              latest              e4552d1785be        28 hours ago        289MB
run bash on the image and install apache
$docker run -it e4552d1785be /bin/bash
root@691b607eb802:/# apt-get install apache2
root@691b607eb802:/# exit
Look at exited process
$docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                     PORTS               NAMES
18fd3972c03e        e4552d1785be        "/bin/bash"         About a minute ago   Exited (0) 8 seconds ago                       modest_shaw
Commit the container
$ docker commit 18fd3972c03e apache
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
apache              latest              741dd47e03c8        12 seconds ago      360MB
bionic              latest              e4552d1785be        29 hours ago        289MB  

create a local registry server

To use the registry as part of your permanent infrastructure, you should set it to restart automatically when Docker restarts or if it exits. This example uses the --restart always flag to set a restart policy for the registry.
$ docker run -d \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  registry:2
List all
  $docker ps
  CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS
  cf4d76634aaa        registry:2          "/entrypoint.sh /etc/.." 2 minutes ago       Up 2 minutes       0.0.0.0:5000->5000/tcp   registry

put newly created image in registry

Tag the newly created image with the server
$docker image tag bionic localhost:5000/bionic
We can check the result
$docker images
REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
bionic                  latest              e4552d1785be        22 minutes ago      289MB
localhost:5000/bionic   latest              e4552d1785be        22 minutes ago      289MB
now push the image
docker push localhost:5000/bionic

create a modified image

$docker run -it apache bash
root@a2c10bb22d01:/# apt-get install apache2
root@a2c10bb22d01:/# exit
$



  $ docker run -d -p 5000:5000 --restart=always --name registry registry:2
Copy an image from Docker Hub:
  $ docker pull ubuntu:18.04
Copy an image from Docker Hub:
  $ docker pull ubuntu:18.04

Emacs

Here is how to re-open a scratch buffer:
C-x b *scratch* RET
Set initial size:
(setq initial-frame-alist
      '((width . 102) (height . 54)))
Set visual bell:
(setq visible-bell 1)
Here are my default Emacs settings:
;; shortcuts i like
(global-set-key [f1] 'font-lock-fontify-buffer)  ;; put colors
(global-set-key [f2] 'toggle-truncate-lines)     ;; switch trucate line mode
(global-set-key [f3] 'call-last-kbd-macro)       ;; recall last macro
(global-set-key [f9] 'compile)                   ;; run makefile
To have *.h files in c++ mode:
(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
Here is how to configure multi-web-mode:
(add-to-list 'load-path "~/.emacs.d/plugins")
(load "multi-web-mode.el")
(require 'multi-web-mode)
(setq mweb-default-major-mode 'html-mode)
(setq mweb-tags 
  '((php-mode "<\\?php\\|<\\? \\|<\\?=" "\\?>")
    (js-mode  "<script[^>]*>" "</script>")
    (css-mode "<style[^>]*>" "</style>")))
(setq mweb-filename-extensions '("php" "htm" "html" "ctp" "phtml" "php4" "php5"))
(multi-web-global-mode 1)

enscript

Here are the standard options i used to print listings withe enscript
enscript -2r -C1 my_file_to_print.cc -o my_file_to_print.ps
ps2pdf my_file_to_print.ps

exim

Configuration for exim : at the top of the config file:
primary_hostname = derepas.com
domainlist local_domains = @:derepas.com
domainlist relay_to_domains =
hostlist   relay_from_hosts = 127.0.0.1
To use the smtp server of my isp, add at the top of the router section:
 send_to_gateway: 
        driver = manualroute 
        domains = !+local_domains 
        transport = remote_smtp 
        route_list = * smtp.server.of.my.isp.com
To launch reconfiguration on debian:
dpkg-reconfigure exim4-config
To print the list of messages:
exim -bp
To remove a message in the list:
exim -Mrm {message-id}
To remove everything:
exim -bp | awk '/^ *[0-9]+[mhd]/{print "exim -Mrm " $3}' | bash

Gandi

#!/bin/bash
cd `dirname $0`

APIKEY="$(cat my_secret_api_key.txt)"
MY_IP=$(curl -s http://whatismyip.akamai.com/)
if [ -e last_ip_addr.txt ]; then
    OLD_IP="$(cat last_ip_addr.txt)"
    if [ "$OLD_IP" == "$MY_IP" ]; then
       	exit 0
    else
	echo "new IP $MY_IP"
	echo $MY_IP > last_ip_addr.txt
    fi
else
    echo $MY_IP > last_ip_addr.txt
fi

function set_host {
    domain=$1
    host=$2
    curl --silent --show-error -X DELETE -H "Content-Type: application/json" \
               -H "X-Api-Key: $APIKEY" \
               https://dns.api.gandi.net/api/v5/domains/$domain/records/$host > /dev/null
    curl --silent --show-error -X POST -H "Content-Type: application/json" \
         -H "X-Api-Key: $APIKEY" \
         -d '{"rrset_ttl": 1800,
              "rrset_values": ["'$MY_IP'"]}' \
		  https://dns.api.gandi.net/api/v5/domains/$domain/records/$host/A 
}

function set_mx {
    domain=$1
    value=$2
    curl --silent --show-error -X POST -H "Content-Type: application/json" \
	 -H "X-Api-Key: $APIKEY" \
	 -d "{\"rrset_ttl\": 1800,\"rrset_type\": \"MX\",\"rrset_values\": [\"$value\"]}" \
	 https://dns.api.gandi.net/api/v5/domains/$domain/records/@ > /dev/null
}

set_host "example.com" "@"
set_host "example.com" "link" 
set_host "example.com" "git"
set_host "example.com" "www"
set_host "example.com" "mail"
set_mx   "example.com" "10 mail.example.com."
set_host "example.com" "ns" 
set_host "example.com" "drive"
set_host "example.com" "docker"




Gentoo

Emerge is Gentoo command line tool to access the package system. To update the entire system:
emerge --sync
emerge -av --newuse --update --deep world
To mask package dev-db/mysql-community:
echo 'dev-db/mysql-community' >> /etc/portage/package.mask 
To check contents of package nstx:
cat /var/db/pkg/net-misc/nstx-1.1_beta6-r2/CONTENTS
qfile in the portage-utils package finds the package to which a file belongs:
$ qfile /etc/fonts/fonts.conf
media-libs/fontconfig (/etc/fonts/fonts.conf)
Security : glsa-check is part of app-portage/gentoolkit. Check if your system is affected by GLSAs (Gentoo Linux Security Advisories):
glsa-check -t all
To apply required fixes
glsa-check -f $(glsa-check -t all)

Git

Git is an easy to use, distributed, version control system. To create a new repository
cd (project-directory)
git init
(add some files)
git add .
git commit -m 'Initial commit'
To add a complete directory and all sub directories:
git add --all my_repo
To remove a file
git rm path/to/file
To perform a "checkout" and submit a patch:
git clone git://github.com/git/hello-world.git
cd hello-world
(edit files)
git add (files)
git commit -m 'Explain what I changed'
git format-patch origin/master
This generates the 0001-Explain-what-I-changed.patch file. To check out using ssh:
git clone ssh://derepas.com/~git/snstx
To push stuff in local:
git config receive.denyCurrentBranch ignore
Some other stuff:
# list config 
git config --list
# change original repository
git config remote.origin.url ssh://mydomain.org/~git/my_repo
# configure user name and email
git config --global user.name "Your Name"
git config --global user.email you@example.com
# list untracked (other) files
git ls-files -o
If you do not want to check certificate:
export GIT_SSL_NO_VERIFY=1

Add remote repository access via ssh:

git remote add origin login@IP/path/to/repository
with access via http:
git remote add origin http://IP/path/to/repository
Do not check ssl:
git config --global http.sslverify false
To manage tags:
# list all existing tags
git tag -l
# switch to tag STEP_0
git checkout STEP_0
# put a tag on a new version
git tag -a "MY_TAG_NAME" -m "My comment"
# add an already existing tag to a new source file
git tag -f "MY_EXISTING_TAG_NAME" -m "My comment"
# to push all tags :
git push origin --tags
Create a new branch and switch to it:
$ git checkout -b STEP_1
Switched to a new branch 'STEP_1'

Iptables

The iptables command is used to manipulated the way ip packets are handled. This is usefull to create a firewall. Here is how to create the firewall. First of all let us define some parameters:
IPTABLES=/sbin/iptables
#private lan network
INTERNAL_LAN="192.168.0.0/24"
#private lan interface
INTERNAL_LAN_INTERFACE="eth1"
#private lan interface address for the firewall
INTERNAL_LAN_INTERFACE_ADDR="192.168.0.1"
#external lan interface
EXTERNAL_LAN_INTERFACE="eth0"
# external lan interface addr
EXTERNAL_LAN_INTERFACE_ADDR="xxx.xxx.xxx.xxx"
First of all we have to erase all possible rules:
# flush all
$IPTABLES -F
$IPTABLES -t nat -F
And specify that by default all IP packets are dropped:
# set default policy
$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP
We then decide to enable loop back as well as any ping request:
# enable loop back
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A OUTPUT -o lo -j ACCEPT

# enable ping requests
$IPTABLES -A INPUT -p icmp -j ACCEPT
$IPTABLES -A OUTPUT -p icmp -j ACCEPT
In order to have the privates machines on the network "appear" with the internet address of the firewall we have to enable masquerading:
$IPTABLES -t nat -A POSTROUTING -o $EXTERNAL_LAN_INTERFACE \
          -s $INTERNAL_LAN \
          -j MASQUERADE
Ip forwaring should be enabled:
echo 1 > /proc/sys/net/ipv4/ip_forward
We can then define the following bash function which enables local machines to access some port of machines on the internet:
allow_lan_to_access() {
  # outbound traffic rules
  $IPTABLES -A OUTPUT -o $EXTERNAL_LAN_INTERFACE -p tcp \
          -s $EXTERNAL_LAN_INTERFACE_ADDR \
          -d 0/0 --destination-port $1 -j ACCEPT
  # inbound traffic rules
  $IPTABLES -A INPUT -i $EXTERNAL_LAN_INTERFACE -p tcp \
          -s 0/0 --source-port $1 \
          -d $EXTERNAL_LAN_INTERFACE_ADDR \
          -j ACCEPT
}

allow_lan_to_access_udp() {
  # outbound traffic rules
  $IPTABLES -A OUTPUT -o $EXTERNAL_LAN_INTERFACE -p udp \
          -s $EXTERNAL_LAN_INTERFACE_ADDR \
          -d 0/0 --destination-port $1 -j ACCEPT
  # inbound traffic rules
  $IPTABLES -A INPUT -i $EXTERNAL_LAN_INTERFACE -p udp \
          -s 0/0 --source-port $1 \
          -d $EXTERNAL_LAN_INTERFACE_ADDR \
          -j ACCEPT
}
These functions can be used the following way, for instance to allow local machines to surf on web pages, port 80 of any machine should be possible:
allow_lan_to_access 80
If you want to perform DNS requests on DNS located on the internet, you need to allow UDP connections on port 53:
allow_lan_to_access_udp 53
If some servers are running on the computer which is the firewall you then need to open some ports for the outside world. This is acheived via the following function:
allow_outside_access_on_firewall()
{
  $IPTABLES -A INPUT -i $EXTERNAL_LAN_INTERFACE \
          -p tcp \
          -s 0/0 \
          -d $EXTERNAL_LAN_INTERFACE_ADDR --destination-port $1 \
          -j ACCEPT
  $IPTABLES -A OUTPUT -o $EXTERNAL_LAN_INTERFACE \
          -p tcp \
          -s $EXTERNAL_LAN_INTERFACE_ADDR --source-port $1 \
          -d  0/0  \
          -j ACCEPT
}
For instance if you have a mail server, you should allow access to port 25,this would be 80 for a web server, 22 for an ssh server, 20 for an sftp server:
allow_outside_access_on_firewall 20
allow_outside_access_on_firewall 22
allow_outside_access_on_firewall 25
allow_outside_access_on_firewall 80
If you have a server running not on the firewall but on a computer in you local area, you need to have a port forward:
port_forward() {
  $IPTABLES -t nat -A PREROUTING -d $EXTERNAL_LAN_INTERFACE_ADDR -p tcp \
    --dport $1 \
    -j DNAT \
    --to-dest $2
}

port_forward_udp() {
  $IPTABLES -t nat -A PREROUTING -d $EXTERNAL_LAN_INTERFACE_ADDR -p udp \
    --dport $1 \
    -j DNAT \
    --to-dest $2
}
For instance if you have a web server running on port 80 of 192.168.0.2, which can be accessed by port 8080 on the firewall you can perform the port forwarding using the instruction:
port_forward 8080 192.168.0.2:80

Kernel

To make a single module (here fs/ext4)
# cleaning evething
make mrproper
# getting the kernel ready
make defconfig && make prepare 
sed -e 's/^CONFIG_EXT4_FS=y$/CONFIG_EXT4_FS=m/' < .config  > tmp
mv tmp .config
rm fs/ext4.o
# to make the fs/ext4
make SUBDIRS=fs/ext4 modules
Here is how to get a simple configuration:
make allnoconfig
make menuconfig
 +General setup
  +Initial Ram Filesystem
 +Enable loadable module support
 +Processor type and features
  +Generic x86 support
 +Bus options
  +PCI support
 +Executable file format
  +Kernel support for ELF binaries
  +Kernel support for files starting with #!
  +Kernel support for a.out
 +Device drivers
 +File Systems
  +Second extended fs support
  +ext3
  +ext4
To install busybox:
wget http://www.busybox.net/downloads/busybox-1.21.0.tar.bz2
tar xvfj busybox-1.21.0.tar.bz2
cd busybox-1.21.0/
make defconfig
make menuconfig
make
Now write the init script to launch the system ~/my_init.txt:
#!/bin/sh

#Clear the screen
clear

#Create all the symlinks to /bin/busybox
busybox --install -s

# mout stuff which has to be mounted
mount -t proc none /proc
mount -t sysfs none /sys
mount -t configfs none /sys/kernel/config
mount -t debugfs none /sys/kernel/debug
mount -t tmpfs none /tmp

#Disable kernel messages from popping onto the screen
#echo 0 > /proc/sys/kernel/printk

#Create device nodes
mknod /dev/null c 1 3
mknod /dev/tty c 5 0
mdev -s

#Function for parsing command line options with "=" in them
# get_opt("init=/sbin/init") will return "/sbin/init"
get_opt() {
        echo "$@" | cut -d "=" -f 2
}

#Defaults
init="/sbin/init"
root="/dev/hda1"

#Process command line options
for i in $(cat /proc/cmdline); do
        case $i in
        root\=*)
                root=$(get_opt $i)
                ;;
        init\=*)
                init=$(get_opt $i)
                ;;
        esac
done

#Mount the root device
mount "${root}" /newroot

#Check if $init exists and is executable
if [[ -x "/newroot/${init}" ]] ; then
        #Unmount all other mounts so that the ram used by
        #the initramfs can be cleared after switch_root
        umount /sys /proc

        #Switch to the new root and execute init
        exec switch_root /newroot "${init}"
fi

#This will only be run if the exec above failed
echo "Failed to switch_root, dropping to a shell"
exec sh
Now state all the files we want in the initramfs in the ~/my_cpio_list:
# A simple initramfs config file
dir /dev 0755 0 0
nod /dev/console 0600 0 0 c 5 1
dir /root 0700 0 0
dir /sbin 0755 0 0
dir /bin 0755 0 0
file /sbin/init /home/fabrice/my_init.txt 0755 0 0 
file /bin/busybox /home/fabrice/busybox/busybox-1.21.0/busybox 0755 0 0 
slink /bin/sh /bin/busybox 0755 0 0 
Now from the linux source directory we can create the initramfs file:
usr/gen_init_cpio ~/my_cpio_list | gzip > initramfs.gz
We create a hard disk image:
qemu-img create -f qcow2 vdisk.img 10G 
And to test the result we can launch qemu:
kvm -kernel arch/x86/boot/bzImage -initrd initramfs.gz

Make

Make is used to automate compilation commands. Here is a typical makefile to compile all *.cc files in current directory into an executable named myexe:
# definitions
CXX:=g++
CXXFLAGS:=-Wall -g
SOURCES := $(wildcard *.cc)      # all *.cc files in the directory
OBJ := $(SOURCES:.cc=.o)         # remplace all .cc by .o
EXE_NAME := myexe

# targets
$(EXE_NAME) : $(OBJ)
        $(CXX) -o $@ $(OBJ)
%.o : %.cc .deps
        $(CXX) $(CXXFLAGS) -c $<
.deps : $(SOURCES)
        $(CXX) $(CXXFLAGS) -MM $(SOURCES) > $@
-include .deps

# suppress generated files
clean :
        rm -f *.o $(EXE_NAME) *~ .dep
To have a "clean" target which calls make file in subdirectory other than .git
clean :
        for i in `/bin/ls -F | grep '/' | grep -v .git` ; do \
                cd "$$i"; make clean; cd ..; \
        done

mount

To mount a windows directory via a guest virtual box:
mount -t vboxsf username /my/mount/point/

mutt

Here is my .muttrc file with the interface to spamassassin:
 
set realname = "Fabrice Derepas"  
set from = "fabrice@derepas.com"  
# Set DEFAULT status color 
color status    blue      white 
 
#color any message with a spam score header in bright red
color index brightred default '~h "X-Spam_score_int:.*[0-9]+"' 
 
unset confirmappend

# Delete is re-bound to move messages to Trash. They will be filed as ham when pressing 'R'
macro index d "s=Trash\n" "move message to trash"
macro pager d "s=Trash\n" "move message to trash"
# send messages to spam folder. They will be procesesd as spam when pressin 'R'
macro index X "s=junkmail\n" "file as Spam"
macro pager X "s=junkmail\n" "file as Spam"
# process spam and ham
macro index R "!/home/fabrice/bin/processSpam"
The script /home/fabrice/bin/processSpam processes the Trash and junkmail folder:
#!/bin/sh
TRASH=/home/fabrice/Mail/Trash
SPAMBOX=/home/fabrice/Mail/junkmail
[ -w $TRASH ] || exit 1
[ -w $SPAMBOX ] || exit 1

# process Trash as ham, delete if ok
if /usr/bin/sa-learn --mbox --ham $TRASH
then
  /bin/cat /dev/null > $TRASH
  echo "ham processed"
else
    echo "ham not processed";
fi

# process Spam, delete if ok
if /usr/bin/sa-learn --mbox --spam $SPAMBOX
then 
  /bin/cat /dev/null > $SPAMBOX 
  echo "spam processed" 
else 
    echo "spam not processed"; 
fi
/usr/bin/sa-learn --sync
Mark Stosberg has a nice mutt tutorial.

PS

To list processes with a longer list of arguments:
ps -A o "pid command"

QEmu



Sabayon

equo is the command line tool for package management in Sabayon.
equo update
equo install entropy sulfur
equo cleanup
equo search <pkg-name>
equo remove <pkg-name>
equo upgrade --ask
Query commands
equo query files <pkg-name>     # lists all files of a package
equo query belongs <file-name>  # search from what package a file belongs 
Security related commands:
equo security list --affected
equo security install --ask

Sed

Syntax is sed -e "<regular expression>". To convert resize all current png file in current directory with a width of 100 pixels simply type :
for i in `/bin/ls *.png| grep -v small` ; do j=`echo $i | sed -e "s/.png/_small.png/"` ; convert $i -resize 100 $j; echo $j ; done

Ssh-keygen

Pem to id_rsa format:
 chmod 600 gpg-key.pem
 cp gpg-key.pem ~/.ssh/id_rsa
 ssh-keygen -y -f gpg-key.pem > ~/.ssh/id_rsa.pub
Using another key than the default one for ssh:
ssh -i /path/to/id_rsa user@server.mydomain.com

Svn

In order to ignore some files in an svn directory, type:
svn propedit svn:ignore .
This launches an editor in which you can enter files which will be ignored by snv. For instance, if you enter
*/*.cm*
bin
lib
This will ignore directory bin and lib in current directory from svn, and also all files which matches *.cm* in all directories below currrent directory.

Tail

To output the last tree lines of a file named my_file.txt:
tail -n 3 my_file.txt
To output all but the first three lines of a file named my_file.txt:
tail -n +4 my_file.txt 

Tcsh

Prompt

To get a prompt which looks like 12:37 /path/to/current/dir >, which displays current path as the title of the xterm window add to your .tcshrc:
set prompt="%{\033]0;%~\007%}%{\033[32m%}%P%{\033[0m%} %B%~%b%#"
Sequence %{\033]0;%~\007%} displays current path (%~) as xterm title.
Sequence {\033[32m%}%P%{\033[0m%} display time (%P) in green, and goes back to normal color.
Sequence %B%~%b%# displays current path (%~) in bold and default prompt (%#).

'For' loops

Here is a complicated way of doing 'ls':
>foreach i ( `ls` )
foreach? echo $i
foreach? end

Ubuntu

  sudo apt update && sudo apt upgrade
  sudo apt install unattended-upgrades apt-listchanges bsd-mailx
  sudo dpkg-reconfigure -plow unattended-upgrades

Uml

How to set up user mode linux

Compiling from source

Download a kernel from kernel.org, then:
>tar xvfj linux-3.6.6.tar.bz2 
>cd linux-3.6.6
>export ARCH=um
>make defconfig ARCH=um
>make menuconfig ARCH=um
>make ARCH=um
>strip linux
Then compile modules:
>make modules ARCH=um

The linux binary is the uml executable.

Creating a file system

This works under ubuntu:
# create a sparse 400 meg file full of zeroe
dd if=/dev/zero of=new_filesystem seek=400 count=1 bs=1M
sudo mke2fs new_filesystem
mkdir image
# map contents of new_filesystem in the image directory
sudo mount -o loop new_filesystem image/
sudo apt-get install debootstrap
#The program contact the Ubuntu archive servers 
# to generate stuff in image/
sudo debootstrap --arch=i386 --include=nano precise image/
sudo mount --bind /dev image/dev
sudo cp /etc/apt/sources.list image/etc/apt/sources.list
sudo chroot image
# Now we are inside the new file system, as user 'root'
mount -t proc none /proc
mount -t sysfs none /sys
export LC_ALL=C
export HOME=/root
apt-get update
# now fix stuff to have only one console when booting:
cd /etc/init/
ls
rm tty2.conf tty3.conf tty4.conf tty5.conf tty6.conf 
# prevent openning X windows stuff
cd /etc/default
nano console-setup
# replace 'ACTIVE_CONSOLES="/dev/tty[1-6]"' 
# by      'ACTIVE_CONSOLES="/dev/tty1"'
# now completely remove any xterm stuff:
cd /etc/init
mv tty1.conf tty0.conf
nano tty0.conf
# change the last line to read
# 'exec /sbin/getty -8 38400 tty0'
nano /etc/securetty
# add tty0 in the list to allow root to log in
nano /etc/fstab
# put the contents:
# /dev/ubda     /      ext3     defaults     0     1
# proc          /proc  proc     defaults     0     0
nano /etc/network/interfaces
# put the following:
# auto lo
# iface lo inet loopback

#now set root passwd:
passwd

#now leave chroot:
umount /proc
umount /sys
exit
sudo umount image/dev

# now install kernel modules
cd /path/to/kernel/sources
sudo make modules_install INSTALL_MOD_PATH=/path/to/image ARCH=um
cd /back/to/path/where/image/is
sudo umount image


Virtualbox

How to setup NAT on the host:
VBoxManage natnetwork add --netname natnet1 --network "192.168.15.0/24" --enable
To add dhcp after creation:
VBoxManage natnetwork modify --netname natnet1 --dhcp on
VBoxManage natnetwork modify --netname natnet1 --port-forward-4 "web:tcp:[]:8081:[192.168.15.5]:8080"

Back to my home page Last-Updated: ven. nov. 4 13:58:32 2011 (+0100)