notes

Things I've written down that I might want to reference later.
Log | Files | Refs | README

unixtoolbox.xhtml (160332B)


      1    Unix Toolbox
      2 
      3    This document is a collection of Unix/Linux/BSD commands and tasks which
      4    are useful for IT work or for advanced users. This is a practical guide
      5    with concise explanations, however the reader is supposed to know what
      6    s/he is doing.
      7 
      8    Unix Toolbox revision 14.5
      9    The latest version of this document can be found at
     10    http://cb.vu/unixtoolbox.xhtml. Replace .xhtml on the link with .pdf for
     11    the PDF version and with .book.pdf for the booklet version. On a duplex
     12    printer the booklet will create a small book ready to bind. This XHTML
     13    page can be converted into a nice PDF document with a CSS3 compliant
     14    application (see the script example). See also the about page.
     15    Error reports and comments are most welcome - c@cb.vu Colin Barschel.
     16 
     17    © Colin Barschel 2007-2016. Some rights reserved under Creative Commons.
     18 
     19     1. System
     20     2. Processes
     21     3. File System
     22     4. Network
     23     5. SSH SCP
     24     6. VPN with SSH
     25     7. RSYNC
     26     8. SUDO
     27     9. Encrypt Files
     28    10. Encrypt Partitions
     29    11. SSL Certificates
     30    12. CVS
     31    13. SVN
     32    14. Useful Commands
     33    15. Install Software
     34    16. Convert Media
     35    17. Printing
     36    18. Databases
     37    19. Disk Quota
     38    20. Shells
     39    21. Scripting
     40    22. Programming
     41    23. Online Help
     42 
     43    white black
     44 
     45 System
     46 
     47    Hardware | Statistics | Users | Limits | Runlevels | root password |
     48    Compile kernel | Repair grub | Misc
     49    Running kernel and system information
     50 # uname -a                           # Get the kernel version (and BSD version)
     51 # lsb_release -a                     # Full release info of any LSB distribution
     52 # cat /etc/SuSE-release              # Get SuSE version
     53 # cat /etc/debian_version            # Get Debian version
     54 
     55    Use /etc/DISTR-release with DISTR= lsb (Ubuntu), redhat, gentoo,
     56    mandrake, sun (Solaris), and so on. See also /etc/issue.
     57 # uptime                             # Show how long the system has been running
     58 + load
     59 # hostname                           # system's host name
     60 # hostname -i                        # Display the IP address of the host. (Linux
     61  only)
     62 # man hier                           # Description of the file system hierarchy
     63 # last reboot                        # Show system reboot history
     64 
     65 Hardware Informations
     66 
     67    Kernel detected hardware
     68 # dmesg                              # Detected hardware and boot messages
     69 # lsdev                              # information about installed hardware
     70 # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 # Read BIOS
     71 
     72 Linux
     73 
     74 # cat /proc/cpuinfo                  # CPU model
     75 # cat /proc/meminfo                  # Hardware memory
     76 # grep MemTotal /proc/meminfo        # Display the physical memory
     77 # watch -n1 'cat /proc/interrupts'   # Watch changeable interrupts continuously
     78 # free -m                            # Used and free memory (-m for MB)
     79 # cat /proc/devices                  # Configured devices
     80 # lspci -tv                          # Show PCI devices
     81 # lsusb -tv                          # Show USB devices
     82 # lshal                              # Show a list of all devices with their prop
     83 erties
     84 # dmidecode                          # Show DMI/SMBIOS: hw info from the BIOS
     85 
     86 FreeBSD
     87 
     88 # sysctl hw.model                    # CPU model
     89 # sysctl hw                          # Gives a lot of hardware information
     90 # sysctl hw.ncpu                     # number of active CPUs installed
     91 # sysctl vm                          # Memory usage
     92 # sysctl hw.realmem                  # Hardware memory
     93 # sysctl -a | grep mem               # Kernel memory settings and info
     94 # sysctl dev                         # Configured devices
     95 # pciconf -l -cv                     # Show PCI devices
     96 # usbdevs -v                         # Show USB devices
     97 # atacontrol list                    # Show ATA devices
     98 # camcontrol devlist -v              # Show SCSI devices
     99 
    100 Load, statistics and messages
    101 
    102    The following commands are useful to find out what is going on on the
    103    system.
    104 # top                                # display and update the top cpu processes
    105 # mpstat 1                           # display processors related statistics
    106 # vmstat 2                           # display virtual memory statistics
    107 # iostat 2                           # display I/O statistics (2 s intervals)
    108 # systat -vmstat 1                   # BSD summary of system statistics (1 s inte
    109 rvals)
    110 # systat -tcp 1                      # BSD tcp connections (try also -ip)
    111 # systat -netstat 1                  # BSD active network connections
    112 # systat -ifstat 1                   # BSD network traffic through active interfa
    113 ces
    114 # systat -iostat 1                   # BSD CPU and and disk throughput
    115 # ipcs -a                            # information on System V interprocess
    116 # tail -n 500 /var/log/messages      # Last 500 kernel/syslog messages
    117 # tail /var/log/warn                 # System warnings messages see syslog.conf
    118 
    119 Users
    120 
    121 # id                                 # Show the active user id with login and gro
    122 up
    123 # last                               # Show last logins on the system
    124 # who                                # Show who is logged on the system
    125 # groupadd admin                     # Add group "admin" and user colin (Linux/So
    126 laris)
    127 # useradd -c "Colin Barschel" -g admin -m colin
    128 # usermod -a -G <group> <user>       # Add existing user to group (Debian)
    129 # groupmod -A <user> <group>         # Add existing user to group (SuSE)
    130 # userdel colin                      # Delete user colin (Linux/Solaris)
    131 # adduser joe                        # FreeBSD add user joe (interactive)
    132 # rmuser joe                         # FreeBSD delete user joe (interactive)
    133 # pw groupadd admin                  # Use pw on FreeBSD
    134 # pw groupmod admin -m newmember     # Add a new member to a group
    135 # pw useradd colin -c "Colin Barschel" -g admin -m -s /bin/tcsh
    136 # pw userdel colin; pw groupdel admin
    137 
    138    Encrypted passwords are stored in /etc/shadow for Linux and Solaris and
    139    /etc/master.passwd on FreeBSD. If the master.passwd is modified manually
    140    (say to delete a password), run # pwd_mkdb -p master.passwd to rebuild
    141    the database.
    142    To temporarily prevent logins system wide (for all users but root) use
    143    nologin. The message in nologin will be displayed (might not work with
    144    ssh pre-shared keys).
    145 # echo "Sorry no login now" > /etc/nologin       # (Linux)
    146 # echo "Sorry no login now" > /var/run/nologin   # (FreeBSD)
    147 
    148 Limits
    149 
    150    Some application require higher limits on open files and sockets (like a
    151    proxy web server, database). The default limits are usually too low.
    152 
    153 Linux
    154 
    155 Per shell/script
    156 
    157    The shell limits are governed by ulimit. The status is checked with
    158    ulimit -a. For example to change the open files limit from 1024 to 10240
    159    do:
    160 # ulimit -n 10240                    # This is only valid within the shell
    161 
    162    The ulimit command can be used in a script to change the limits for the
    163    script only.
    164 
    165 Per user/process
    166 
    167    Login users and applications can be configured in
    168    /etc/security/limits.conf. For example:
    169 # cat /etc/security/limits.conf
    170 *   hard    nproc   250              # Limit user processes
    171 asterisk hard nofile 409600          # Limit application open files
    172 
    173 System wide
    174 
    175    Kernel limits are set with sysctl. Permanent limits are set in
    176    /etc/sysctl.conf.
    177 # sysctl -a                          # View all system limits
    178 # sysctl fs.file-max                 # View max open files limit
    179 # sysctl fs.file-max=102400          # Change max open files limit
    180 # echo "1024 50000" > /proc/sys/net/ipv4/ip_local_port_range  # port range
    181 # cat /etc/sysctl.conf
    182 fs.file-max=102400                   # Permanent entry in sysctl.conf
    183 # cat /proc/sys/fs/file-nr           # How many file descriptors are in use
    184 
    185 FreeBSD
    186 
    187 Per shell/script
    188 
    189    Use the command limits in csh or tcsh or as in Linux, use ulimit in an
    190    sh or bash shell.
    191 
    192 Per user/process
    193 
    194    The default limits on login are set in /etc/login.conf. An unlimited
    195    value is still limited by the system maximal value.
    196 
    197 System wide
    198 
    199    Kernel limits are also set with sysctl. Permanent limits are set in
    200    /etc/sysctl.conf or /boot/loader.conf. The syntax is the same as Linux
    201    but the keys are different.
    202 # sysctl -a                          # View all system limits
    203 # sysctl kern.maxfiles=XXXX          # maximum number of file descriptors
    204 kern.ipc.nmbclusters=32768           # Permanent entry in /etc/sysctl.conf
    205 kern.maxfiles=65536                  # Typical values for Squid
    206 kern.maxfilesperproc=32768
    207 kern.ipc.somaxconn=8192              # TCP queue. Better for apache/sendmail
    208 # sysctl kern.openfiles              # How many file descriptors are in use
    209 # sysctl kern.ipc.numopensockets     # How many open sockets are in use
    210 # sysctl net.inet.ip.portrange.last=50000 # Default is 1024-5000
    211 # netstat -m                         # network memory buffers statistics
    212 
    213    See The FreeBSD handbook Chapter
    214    11http://www.freebsd.org/handbook/configtuning-kernel-limits.html for
    215    details. And also FreeBSD performance
    216    tuninghttp://serverfault.com/questions/64356/freebsd-performance-tuning-
    217    sysctls-loader-conf-kernel
    218 
    219 Solaris
    220 
    221    The following values in /etc/system will increase the maximum file
    222    descriptors per proc:
    223 set rlim_fd_max = 4096               # Hard limit on file descriptors for a singl
    224 e proc
    225 set rlim_fd_cur = 1024               # Soft limit on file descriptors for a singl
    226 e proc
    227 
    228 Runlevels
    229 
    230 Linux
    231 
    232    Once booted, the kernel starts init which then starts rc which starts
    233    all scripts belonging to a runlevel. The scripts are stored in
    234    /etc/init.d and are linked into /etc/rc.d/rcN.d with N the runlevel
    235    number.
    236    The default runlevel is configured in /etc/inittab. It is usually 3 or
    237    5:
    238 # grep default: /etc/inittab
    239 id:3:initdefault:
    240 
    241    The actual runlevel can be changed with init. For example to go from 3
    242    to 5:
    243 # init 5                             # Enters runlevel 5
    244      * 0       Shutdown and halt
    245      * 1       Single-User mode (also S)
    246      * 2       Multi-user without network
    247      * 3       Multi-user with network
    248      * 5       Multi-user with X
    249      * 6       Reboot
    250 
    251    Use chkconfig to configure the programs that will be started at boot in
    252    a runlevel.
    253 # chkconfig --list                   # List all init scripts
    254 # chkconfig --list sshd              # Report the status of sshd
    255 # chkconfig sshd --level 35 on       # Configure sshd for levels 3 and 5
    256 # chkconfig sshd off                 # Disable sshd for all runlevels
    257 
    258    Debian and Debian based distributions like Ubuntu or Knoppix use the
    259    command update-rc.d to manage the runlevels scripts. Default is to start
    260    in 2,3,4 and 5 and shutdown in 0,1 and 6.
    261 # update-rc.d sshd defaults          # Activate sshd with the default runlevels
    262 # update-rc.d sshd start 20 2 3 4 5 . stop 20 0 1 6 .  # With explicit arguments
    263 # update-rc.d -f sshd remove         # Disable sshd for all runlevels
    264 # shutdown -h now (or # poweroff)    # Shutdown and halt the system
    265 
    266 FreeBSD
    267 
    268    The BSD boot approach is different from the SysV, there are no
    269    runlevels. The final boot state (single user, with or without X) is
    270    configured in /etc/ttys. All OS scripts are located in /etc/rc.d/ and in
    271    /usr/local/etc/rc.d/ for third-party applications. The activation of the
    272    service is configured in /etc/rc.conf and /etc/rc.conf.local. The
    273    default behavior is configured in /etc/defaults/rc.conf. The scripts
    274    responds at least to start|stop|status.
    275 # /etc/rc.d/sshd status
    276 sshd is running as pid 552.
    277 # shutdown now                       # Go into single-user mode
    278 # exit                               # Go back to multi-user mode
    279 # shutdown -p now                    # Shutdown and halt the system
    280 # shutdown -r now                    # Reboot
    281 
    282    The process init can also be used to reach one of the following states
    283    level. For example # init 6 for reboot.
    284      * 0       Halt and turn the power off (signal USR2)
    285      * 1       Go to single-user mode (signal TERM)
    286      * 6       Reboot the machine (signal INT)
    287      * c       Block further logins (signal TSTP)
    288      * q       Rescan the ttys(5) file (signal HUP)
    289 
    290 Windows
    291 
    292    Start and stop a service with either the service name or "service
    293    description" (shown in the Services Control Panel) as follows:
    294 net stop WSearch
    295 net start WSearch                    # start search service
    296 net stop "Windows Search"
    297 net start "Windows Search"           # same as above using descr.
    298 
    299 Reset root password
    300 
    301 Linux method 1
    302 
    303    At the boot loader (lilo or grub), enter the following boot option:
    304 init=/bin/sh
    305 
    306    The kernel will mount the root partition and init will start the bourne
    307    shell instead of rc and then a runlevel. Use the command passwd at the
    308    prompt to change the password and then reboot. Forget the single user
    309    mode as you need the password for that.
    310    If, after booting, the root partition is mounted read only, remount it
    311    rw:
    312 # mount -o remount,rw /
    313 # passwd                             # or delete the root password (/etc/shadow)
    314 # sync; mount -o remount,ro /        # sync before to remount read only
    315 # reboot
    316 
    317 FreeBSD method 1
    318 
    319    On FreeBSD, boot in single user mode, remount / rw and use passwd. You
    320    can select the single user mode on the boot menu (option 4) which is
    321    displayed for 10 seconds at startup. The single user mode will give you
    322    a root shell on the / partition.
    323 # mount -u /; mount -a               # will mount / rw
    324 # passwd
    325 # reboot
    326 
    327 Unixes and FreeBSD and Linux method 2
    328 
    329    Other Unixes might not let you go away with the simple init trick. The
    330    solution is to mount the root partition from an other OS (like a rescue
    331    CD) and change the password on the disk.
    332      * Boot a live CD or installation CD into a rescue mode which will give
    333        you a shell.
    334      * Find the root partition with fdisk e.g. fdisk /dev/sda
    335      * Mount it and use chroot:
    336 
    337 # mount -o rw /dev/ad4s3a /mnt
    338 # chroot /mnt                        # chroot into /mnt
    339 # passwd
    340 # reboot
    341 
    342 Kernel modules
    343 
    344 Linux
    345 
    346 # lsmod                              # List all modules loaded in the kernel
    347 # modprobe isdn                      # To load a module (here isdn)
    348 
    349 FreeBSD
    350 
    351 # kldstat                            # List all modules loaded in the kernel
    352 # kldload crypto                     # To load a module (here crypto)
    353 
    354 Compile Kernel
    355 
    356 Linux
    357 
    358 # cd /usr/src/linux
    359 # make mrproper                      # Clean everything, including config files
    360 # make oldconfig                     # Reuse the old .config if existent
    361 # make menuconfig                    # or xconfig (Qt) or gconfig (GTK)
    362 # make                               # Create a compressed kernel image
    363 # make modules                       # Compile the modules
    364 # make modules_install               # Install the modules
    365 # make install                       # Install the kernel
    366 # reboot
    367 
    368 FreeBSD
    369 
    370    Optionally update the source tree (in /usr/src) with csup (as of FreeBSD
    371    6.2 or later):
    372 # csup <supfile>
    373 
    374    I use the following supfile:
    375 *default host=cvsup5.FreeBSD.org  # www.freebsd.org/handbook/cvsup.html#CVSUP-MIR
    376 RORS
    377 *default prefix=/usr
    378 *default base=/var/db
    379 *default release=cvs delete tag=RELENG_7
    380 src-all
    381 
    382    To modify and rebuild the kernel, copy the generic configuration file to
    383    a new name and edit it as needed (you can also edit the file GENERIC
    384    directly). To restart the build after an interruption, add the option
    385    NO_CLEAN=YES to the make command to avoid cleaning the objects already
    386    build.
    387 # cd /usr/src/sys/i386/conf/
    388 # cp GENERIC MYKERNEL
    389 # cd /usr/src
    390 # make buildkernel KERNCONF=MYKERNEL
    391 # make installkernel KERNCONF=MYKERNEL
    392 
    393    To rebuild the full OS:
    394 # make buildworld                    # Build the full OS but not the kernel
    395 # make buildkernel                   # Use KERNCONF as above if appropriate
    396 # make installkernel
    397 # reboot
    398 # mergemaster -p                     # Compares only files known to be essential
    399 # make installworld
    400 # mergemaster -i -U                  # Update all configurations and other files
    401 # reboot
    402 
    403    For small changes in the source you can use NO_CLEAN=yes to avoid
    404    rebuilding the whole tree.
    405 # make buildworld NO_CLEAN=yes       # Don't delete the old objects
    406 # make buildkernel KERNCONF=MYKERNEL NO_CLEAN=yes
    407 
    408 Repair grub
    409 
    410    So you broke grub? Boot from a live cd, [find your linux partition under
    411    /dev and use fdisk to find the linux partion] mount the linux partition,
    412    add /proc and /dev and use grub-install /dev/xyz. Suppose linux lies on
    413    /dev/sda6:
    414 # mount /dev/sda6 /mnt               # mount the linux partition on /mnt
    415 # mount --bind /proc /mnt/proc       # mount the proc subsystem into /mnt
    416 # mount --bind /dev /mnt/dev         # mount the devices into /mnt
    417 # chroot /mnt                        # change root to the linux partition
    418 # grub-install /dev/sda              # reinstall grub with your old settings
    419 
    420 Misc
    421 
    422    Disable OSX virtual memory (repeat with load to re-enable). Faster
    423    system, but a little risky.
    424 # sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.dynamic_pager.
    425 plist
    426 # sleep 3600; pmset sleepnow           # go to standby in one hour (OSX)
    427 # defaults write -g com.apple.mouse.scaling -float 8
    428                                      # OSX mouse acceleration (use -1 to reverse)
    429 
    430 Processes
    431 
    432    Listing | Priority | Background/Foreground | Top | Kill
    433 
    434 Listing and PIDs
    435 
    436    Each process has a unique number, the PID. A list of all running process
    437    is retrieved with ps.
    438 # ps -auxefw                         # Extensive list of all running process
    439 
    440    However more typical usage is with a pipe or with pgrep (for OS X
    441    install proctools from MacPorts):
    442 # ps axww | grep cron
    443   586  ??  Is     0:01.48 /usr/sbin/cron -s
    444 # ps axjf                            # All processes in a tree format (Linux)
    445 # ps aux | grep 'ss[h]'              # Find all ssh pids without the grep pid
    446 # pgrep -l sshd                      # Find the PIDs of processes by (part of) na
    447 me
    448 # echo $$                            # The PID of your shell
    449 # fuser -va 22/tcp                   # List processes using port 22 (Linux)
    450 # pmap PID                           # Memory map of process (hunt memory leaks)
    451 (Linux)
    452 # fuser -va /home                    # List processes accessing the /home partiti
    453 on
    454 # strace df                          # Trace system calls and signals
    455 # truss df                           # same as above on FreeBSD/Solaris/Unixware
    456 
    457 Priority
    458 
    459    Change the priority of a running process with renice. Negative numbers
    460    have a higher priority, the lowest is -20 and "nice" have a positive
    461    value.
    462 # renice -5 586                      # Stronger priority
    463 586: old priority 0, new priority -5
    464 
    465    Start the process with a defined priority with nice. Positive is "nice"
    466    or weak, negative is strong scheduling priority. Make sure you know if
    467    /usr/bin/nice or the shell built-in is used (check with # which nice).
    468 # nice -n -5 top                     # Stronger priority (/usr/bin/nice)
    469 # nice -n 5 top                      # Weaker priority (/usr/bin/nice)
    470 # nice +5 top                        # tcsh builtin nice (same as above!)
    471 
    472    While nice changes the CPU scheduler, an other useful command ionice
    473    will schedule the disk IO. This is very useful for intensive IO
    474    application (e.g. compiling). You can select a class (idle - best effort
    475    - real time), the man page is short and well explained.
    476 # ionice c3 -p123                    # set idle class for pid 123 (Linux only)
    477 # ionice -c2 -n0 firefox             # Run firefox with best effort and high prio
    478 rity
    479 # ionice -c3 -p$$                    # Set the actual shell to idle priority
    480 
    481    The last command is very useful to compile (or debug) a large project.
    482    Every command launched from this shell will have a lover priority. $$ is
    483    your shell pid (try echo $$).
    484    FreeBSD uses idprio/rtprio (0 = max priority, 31 = most idle):
    485 # idprio 31 make                     # compile in the lowest priority
    486 # idprio 31 -1234                    # set PID 1234 with lowest priority
    487 # idprio -t -1234                    # -t removes any real time/idle priority
    488 
    489 Background/Foreground
    490 
    491    When started from a shell, processes can be brought in the background
    492    and back to the foreground with [Ctrl]-[Z] (^Z), bg and fg. List the
    493    processes with jobs. When needed detach from the terminal with disown.
    494 # ping cb.vu > ping.log
    495 ^Z                                   # ping is suspended (stopped) with [Ctrl]-[Z
    496 ]
    497 # bg                                 # put in background and continues running
    498 # jobs -l                            # List processes in background
    499 [1]  - 36232 Running                       ping cb.vu > ping.log
    500 [2]  + 36233 Suspended (tty output)        top
    501 # fg %2                              # Bring process 2 back in foreground
    502 
    503 # make                               # start a long compile job but need to leave
    504  the terminal
    505 ^Z                                   # suspended (stopped) with [Ctrl]-[Z]
    506 # bg                                 # put in background and continues running
    507 # disown -h %1                       # detatch process from terminal, won't be ki
    508 lled at logout
    509 
    510    No straight forward way to re-attach the process to a new terminal, try
    511    reptyr (Linux).
    512    Use nohup to start a process which has to keep running when the shell is
    513    closed (immune to hangups).
    514 # nohup ping -i 60 > ping.log &
    515 
    516 Top
    517 
    518    The program top displays running information of processes. See also the
    519    program htop from htop.sourceforge.net (a more powerful version of top)
    520    which runs on Linux and FreeBSD (ports/sysutils/htop/). While top is
    521    running press the key h for a help overview. Useful keys are:
    522      * u [user name] To display only the processes belonging to the user.
    523        Use + or blank to see all users
    524      * k [pid] Kill the process with pid.
    525      * 1 To display all processors statistics (Linux only)
    526      * R Toggle normal/reverse sort.
    527 
    528 Signals/Kill
    529 
    530    Terminate or send a signal with kill or killall.
    531 # ping -i 60 cb.vu > ping.log &
    532 [1] 4712
    533 # kill -s TERM 4712                  # same as kill -15 4712
    534 # killall -1 httpd                   # Kill HUP processes by exact name
    535 # pkill -9 http                      # Kill TERM processes by (part of) name
    536 # pkill -TERM -u www                 # Kill TERM processes owned by www
    537 # fuser -k -TERM -m /home            # Kill every process accessing /home (to umo
    538 unt)
    539 
    540    Important signals are:
    541      * 1       HUP (hang up)
    542      * 2       INT (interrupt)
    543      * 3       QUIT (quit)
    544      * 9       KILL (non-catchable, non-ignorable kill)
    545      * 15     TERM (software termination signal)
    546 
    547 File System
    548 
    549    Disk info | Boot | Disk usage | Opened files | Mount/remount | Mount SMB
    550    | Mount image | Burn ISO | Create image | Memory disk | Disk performance
    551 
    552 Permissions
    553 
    554    Change permission and ownership with chmod and chown. The default umask
    555    can be changed for all users in /etc/profile for Linux or
    556    /etc/login.conf for FreeBSD. The default umask is usually 022. The umask
    557    is subtracted from 777, thus umask 022 results in a permission 0f 755.
    558 1 --x execute                        # Mode 764 = exec/read/write | read/write |
    559 read
    560 2 -w- write                          # For:       |--  Owner  --|   |- Group-|
    561 |Oth|
    562 4 r-- read
    563   ugo=a                              u=user, g=group, o=others, a=everyone
    564 
    565 # chmod [OPTION] MODE[,MODE] FILE    # MODE is of the form [ugoa]*([-+=]([rwxXst]
    566 ))
    567 # chmod 640 /var/log/maillog         # Restrict the log -rw-r-----
    568 # chmod u=rw,g=r,o= /var/log/maillog # Same as above
    569 # chmod -R o-r /home/*               # Recursive remove other readable for all us
    570 ers
    571 # chmod u+s /path/to/prog            # Set SUID bit on executable (know what you
    572 do!)
    573 # find / -perm -u+s -print           # Find all programs with the SUID bit
    574 # chown user:group /path/to/file     # Change the user and group ownership of a f
    575 ile
    576 # chgrp group /path/to/file          # Change the group ownership of a file
    577 # chmod 640 `find ./ -type f -print` # Change permissions to 640 for all files
    578 # chmod 751 `find ./ -type d -print` # Change permissions to 751 for all director
    579 ies
    580 
    581 Disk information
    582 
    583 # diskinfo -v /dev/ad2               # information about disk (sector/size) FreeB
    584 SD
    585 # hdparm -I /dev/sda                 # information about the IDE/ATA disk (Linux)
    586 # fdisk /dev/ad2                     # Display and manipulate the partition table
    587 # smartctl -a /dev/ad2               # Display the disk SMART info
    588 
    589 Boot
    590 
    591 FreeBSD
    592 
    593    To boot an old kernel if the new kernel doesn't boot, stop the boot at
    594    during the count down.
    595 # unload
    596 # load kernel.old
    597 # boot
    598 
    599 System mount points/Disk usage
    600 
    601 # mount | column -t                  # Show mounted file-systems on the system
    602 # df                                 # display free disk space and mounted device
    603 s
    604 # cat /proc/partitions               # Show all registered partitions (Linux)
    605 
    606 Disk usage
    607 
    608 # du -sh *                           # Directory sizes as listing
    609 # du -csh                            # Total directory size of the current direct
    610 ory
    611 # du -ks * | sort -n -r              # Sort everything by size in kilobytes
    612 # ls -lSr                            # Show files, biggest last
    613 
    614 Who has which files opened
    615 
    616    This is useful to find out which file is blocking a partition which has
    617    to be unmounted and gives a typical error of:
    618 # umount /home/
    619 umount: unmount of /home             # umount impossible because a file is lockin
    620 g home
    621    failed: Device busy
    622 
    623 FreeBSD and most Unixes
    624 
    625 # fstat -f /home                     # for a mount point
    626 # fstat -p PID                       # for an application with PID
    627 # fstat -u user                      # for a user name
    628 
    629    Find opened log file (or other opened files), say for Xorg:
    630 # ps ax | grep Xorg | awk '{print $1}'
    631 1252
    632 # fstat -p 1252
    633 USER     CMD          PID   FD MOUNT      INUM MODE         SZ|DV R/W
    634 root     Xorg        1252 root /             2 drwxr-xr-x     512  r
    635 root     Xorg        1252 text /usr     216016 -rws--x--x  1679848 r
    636 root     Xorg        1252    0 /var     212042 -rw-r--r--   56987  w
    637 
    638    The file with inum 212042 is the only file in /var:
    639 # find -x /var -inum 212042
    640 /var/log/Xorg.0.log
    641 
    642 Linux
    643 
    644    Find opened files on a mount point with fuser or lsof:
    645 # fuser -m /home                     # List processes accessing /home
    646 # lsof /home
    647 COMMAND   PID    USER   FD   TYPE DEVICE    SIZE     NODE NAME
    648 tcsh    29029 eedcoba  cwd    DIR   0,18   12288  1048587 /home/eedcoba (guam:/ho
    649 me)
    650 lsof    29140 eedcoba  cwd    DIR   0,18   12288  1048587 /home/eedcoba (guam:/ho
    651 me)
    652 
    653    About an application:
    654 ps ax | grep Xorg | awk '{print $1}'
    655 3324
    656 # lsof -p 3324
    657 COMMAND   PID    USER   FD   TYPE DEVICE    SIZE    NODE NAME
    658 Xorg    3324 root    0w   REG        8,6   56296      12492 /var/log/Xorg.0.log
    659 
    660    About a single file:
    661 # lsof /var/log/Xorg.0.log
    662 COMMAND  PID USER   FD   TYPE DEVICE  SIZE  NODE NAME
    663 Xorg    3324 root    0w   REG    8,6 56296 12492 /var/log/Xorg.0.log
    664 
    665 Mount/remount a file system
    666 
    667    For example the cdrom. If listed in /etc/fstab:
    668 # mount /cdrom
    669 
    670    Or find the device in /dev/ or with dmesg
    671 
    672 FreeBSD
    673 
    674 # mount -v -t cd9660 /dev/cd0c /mnt  # cdrom
    675 # mount_cd9660 /dev/wcd0c /cdrom     # other method
    676 # mount -v -t msdos /dev/fd0c /mnt   # floppy
    677 
    678    Entry in /etc/fstab:
    679 # Device                Mountpoint      FStype  Options         Dump    Pass#
    680 /dev/acd0               /cdrom          cd9660  ro,noauto       0       0
    681 
    682    To let users do it:
    683 # sysctl vfs.usermount=1  # Or insert the line "vfs.usermount=1" in /etc/sysctl.c
    684 onf
    685 
    686 Linux
    687 
    688 # mount -t auto /dev/cdrom /mnt/cdrom   # typical cdrom mount command
    689 # mount /dev/hdc -t iso9660 -r /cdrom   # typical IDE
    690 # mount /dev/scd0 -t iso9660 -r /cdrom  # typical SCSI cdrom
    691 # mount /dev/sdc0 -t ntfs-3g /windows   # typical SCSI
    692 
    693    Entry in /etc/fstab:
    694 /dev/cdrom   /media/cdrom  subfs noauto,fs=cdfss,ro,procuid,nosuid,nodev,exec 0 0
    695 
    696 Mount a FreeBSD partition with Linux
    697 
    698    Find the partition number containing with fdisk, this is usually the
    699    root partition, but it could be an other BSD slice too. If the FreeBSD
    700    has many slices, they are the one not listed in the fdisk table, but
    701    visible in /dev/sda* or /dev/hda*.
    702 # fdisk /dev/sda                     # Find the FreeBSD partition
    703 /dev/sda3   *        5357        7905    20474842+  a5  FreeBSD
    704 # mount -t ufs -o ufstype=ufs2,ro /dev/sda3 /mnt
    705 /dev/sda10 = /tmp; /dev/sda11 /usr   # The other slices
    706 
    707 Remount
    708 
    709    Remount a device without unmounting it. Necessary for fsck for example
    710 # mount -o remount,ro /              # Linux
    711 # mount -o ro -u /                   # FreeBSD
    712 
    713    Copy the raw data from a cdrom into an iso image (default 512 blocksize
    714    might cause problems):
    715 # dd if=/dev/cd0c of=file.iso bs=2048
    716 
    717 Virtualbox
    718 
    719    Allow a share on the host:
    720 # VBoxManage sharedfolder add "GuestName" --name "share" --hostpath "C:\hostshare
    721 "
    722 
    723    Mount share on guest (linux, FreeBSD)
    724 # sudo mount -t vboxsf share /home/vboxshare # -o uid=1000,gid=1000 (as appropria
    725 te)
    726 share /home/colin/share vboxsf defaults,uid=colin 0 0 # fstab entry
    727 
    728 OSX
    729 
    730 # diskutil list                      # List the partitions of a disk
    731 # diskutil unmountDisk /dev/disk1    # Unmount an entire disk (all volumes)
    732 # chflags hidden ~/Documents/folder  # Hide folder (reverse with unhidden)
    733 
    734 Add swap on-the-fly
    735 
    736    Suppose you need more swap (right now), say a 2GB file /swap2gb (Linux
    737    only).
    738 # dd if=/dev/zero of=/swap2gb bs=1024k count=2000
    739 # mkswap /swap2gb                    # create the swap area
    740 # swapon /swap2gb                    # activate the swap. It now in use
    741 # swapoff /swap2gb                   # when done deactivate the swap
    742 # rm /swap2gb
    743 
    744 Mount an SMB share
    745 
    746    Suppose we want to access the SMB share myshare on the computer
    747    smbserver, the address as typed on a Windows PC is \\smbserver\myshare\.
    748    We mount on /mnt/smbshare. Warning> cifs wants an IP or DNS name, not a
    749    Windows name.
    750 
    751 Linux/OSX
    752 
    753 # smbclient -U user -I 192.168.16.229 -L //smbshare/    # List the shares
    754 # mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare
    755 # mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mnt
    756 /share
    757 
    758    Mount Samba share through ssh tunnel
    759 # ssh -C -f -N -p 20022 -L 445:127.0.0.1:445 me@server  # connect on 20022, tunne
    760 l 445
    761 # mount -t smbfs //colin@localhost/colin ~/mnt
    762 # mount_smbfs //colin:mypassword@127.0.0.1/private /Volumes/private # I use this
    763 on OSX + ssh
    764 
    765    Additionally with the package mount.cifs it is possible to store the
    766    credentials in a file, for example /home/user/.smb:
    767 username=winuser
    768 password=winpwd
    769 
    770    And mount as follow:
    771 # mount -t cifs -o credentials=/home/user/.smb //192.168.16.229/myshare /mnt/smbs
    772 hare
    773 
    774 FreeBSD
    775 
    776    Use -I to give the IP (or DNS name); smbserver is the Windows name.
    777 # smbutil view -I 192.168.16.229 //winuser@smbserver    # List the shares
    778 # mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare
    779 
    780 Mount an image
    781 
    782 # hdiutil mount image.iso                               # OS X
    783 
    784 Linux loop-back
    785 
    786 # mount -t iso9660 -o loop file.iso /mnt                # Mount a CD image
    787 # mount -t ext3 -o loop file.img /mnt                   # Mount an image with ext
    788 3 fs
    789 
    790 FreeBSD
    791 
    792    With memory device (do # kldload md.ko if necessary):
    793 # mdconfig -a -t vnode -f file.iso -u 0
    794 # mount -t cd9660 /dev/md0 /mnt
    795 # umount /mnt; mdconfig -d -u 0                         # Cleanup the md device
    796 
    797    Or with virtual node:
    798 # vnconfig /dev/vn0c file.iso; mount -t cd9660 /dev/vn0c /mnt
    799 # umount /mnt; vnconfig -u /dev/vn0c                    # Cleanup the vn device
    800 
    801 Solaris and FreeBSD
    802 
    803    with loop-back file interface or lofi:
    804 # lofiadm -a file.iso
    805 # mount -F hsfs -o ro /dev/lofi/1 /mnt
    806 # umount /mnt; lofiadm -d /dev/lofi/1                   # Cleanup the lofi device
    807 
    808 Create and burn an ISO image
    809 
    810    This will copy the cd or DVD sector for sector. Without conv=notrunc,
    811    the image will be smaller if there is less content on the cd. See below
    812    and the dd examples.
    813 # dd if=/dev/hdc of=/tmp/mycd.iso bs=2048 conv=notrunc
    814 
    815    Use mkisofs to create a CD/DVD image from files in a directory. To
    816    overcome the file names restrictions: -r enables the Rock Ridge
    817    extensions common to UNIX systems, -J enables Joliet extensions used by
    818    Microsoft systems. -L allows ISO9660 filenames to begin with a period.
    819 # mkisofs -J -L -r -V TITLE -o imagefile.iso /path/to/dir
    820 # hdiutil makehybrid -iso -joliet -o dir.iso dir/       # OS X
    821 
    822    On FreeBSD, mkisofs is found in the ports in sysutils/cdrtools.
    823 
    824 Burn a CD/DVD ISO image
    825 
    826 FreeBSD
    827 
    828    FreeBSD does not enable DMA on ATAPI drives by default. DMA is enabled
    829    with the sysctl command and the arguments below, or with
    830    /boot/loader.conf with the following entries:
    831 hw.ata.ata_dma="1"
    832 hw.ata.atapi_dma="1"
    833 
    834    Use burncd with an ATAPI device (burncd is part of the base system) and
    835    cdrecord (in sysutils/cdrtools) with a SCSI drive.
    836 # burncd -f /dev/acd0 data imagefile.iso fixate      # For ATAPI drive
    837 # cdrecord -scanbus                  # To find the burner device (like 1,0,0)
    838 # cdrecord dev=1,0,0 imagefile.iso
    839 
    840 Linux
    841 
    842    Also use cdrecord with Linux as described above. Additionally it is
    843    possible to use the native ATAPI interface which is found with:
    844 # cdrecord dev=ATAPI -scanbus
    845 
    846    And burn the CD/DVD as above.
    847 
    848 dvd+rw-tools
    849 
    850    The dvd+rw-tools package (FreeBSD: ports/sysutils/dvd+rw-tools) can do
    851    it all and includes growisofs to burn CDs or DVDs. The examples refer to
    852    the dvd device as /dev/dvd which could be a symlink to /dev/scd0
    853    (typical scsi on Linux) or /dev/cd0 (typical FreeBSD) or /dev/rcd0c
    854    (typical NetBSD/OpenBSD character SCSI) or /dev/rdsk/c0t1d0s2 (Solaris
    855    example of a character SCSI/ATAPI CD-ROM device). There is a nice
    856    documentation with examples on the FreeBSD handbook chapter
    857    18.7http://www.freebsd.org/handbook/creating-dvds.html.
    858                        # -dvd-compat closes the disk
    859 # growisofs -dvd-compat -Z /dev/dvd=imagefile.iso     # Burn existing iso image
    860 # growisofs -dvd-compat -Z /dev/dvd -J -R /p/to/data  # Burn directly
    861 
    862 Convert a Nero .nrg file to .iso
    863 
    864    Nero simply adds a 300Kb header to a normal iso image. This can be
    865    trimmed with dd.
    866 # dd bs=1k if=imagefile.nrg of=imagefile.iso skip=300
    867 
    868 Convert a bin/cue image to .iso
    869 
    870    The little bchunk programhttp://freshmeat.net/projects/bchunk/ can do
    871    this. It is in the FreeBSD ports in sysutils/bchunk.
    872 # bchunk imagefile.bin imagefile.cue imagefile.iso
    873 
    874 Create a file based image
    875 
    876    For example a partition of 1GB using the file /usr/vdisk.img. Here we
    877    use the vnode 0, but it could also be 1.
    878 
    879 FreeBSD
    880 
    881 # dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M
    882 # mdconfig -a -t vnode -f /usr/vdisk.img -u 0         # Creates device /dev/md1
    883 # bsdlabel -w /dev/md0
    884 # newfs /dev/md0c
    885 # mount /dev/md0c /mnt
    886 # umount /mnt; mdconfig -d -u 0; rm /usr/vdisk.img    # Cleanup the md device
    887 
    888    The file based image can be automatically mounted during boot with an
    889    entry in /etc/rc.conf and /etc/fstab. Test your setup with #
    890    /etc/rc.d/mdconfig start (first delete the md0 device with # mdconfig -d
    891    -u 0).
    892    Note however that this automatic setup will only work if the file image
    893    is NOT on the root partition. The reason is that the /etc/rc.d/mdconfig
    894    script is executed very early during boot and the root partition is
    895    still read-only. Images located outside the root partition will be
    896    mounted later with the script /etc/rc.d/mdconfig2.
    897    /boot/loader.conf:
    898 md_load="YES"
    899 
    900    /etc/rc.conf:
    901 # mdconfig_md0="-t vnode -f /usr/vdisk.img"          # /usr is not on the root pa
    902 rtition
    903 
    904    /etc/fstab: (The 0 0 at the end is important, it tell fsck to ignore
    905    this device, as is does not exist yet)
    906 /dev/md0                /usr/vdisk      ufs     rw              0       0
    907 
    908    It is also possible to increase the size of the image afterward, say for
    909    example 300 MB larger.
    910 # umount /mnt; mdconfig -d -u 0
    911 # dd if=/dev/zero bs=1m count=300 >> /usr/vdisk.img
    912 # mdconfig -a -t vnode -f /usr/vdisk.img -u 0
    913 # growfs /dev/md0
    914 # mount /dev/md0c /mnt                                # File partition is now 300
    915  MB larger
    916 
    917 Linux
    918 
    919 # dd if=/dev/zero of=/usr/vdisk.img bs=1024k count=1024
    920 # mkfs.ext3 /usr/vdisk.img
    921 # mount -o loop /usr/vdisk.img /mnt
    922 # umount /mnt; rm /usr/vdisk.img                      # Cleanup
    923 
    924 Linux with losetup
    925 
    926    /dev/zero is much faster than urandom, but less secure for encryption.
    927 # dd if=/dev/urandom of=/usr/vdisk.img bs=1024k count=1024
    928 # losetup /dev/loop0 /usr/vdisk.img                   # Creates and associates /d
    929 ev/loop0
    930 # mkfs.ext3 /dev/loop0
    931 # mount /dev/loop0 /mnt
    932 # losetup -a                                          # Check used loops
    933 # umount /mnt
    934 # losetup -d /dev/loop0                               # Detach
    935 # rm /usr/vdisk.img
    936 
    937 Create a memory file system
    938 
    939    A memory based file system is very fast for heavy IO application. How to
    940    create a 64 MB partition mounted on /memdisk:
    941 
    942 FreeBSD
    943 
    944 # mount_mfs -o rw -s 64M md /memdisk
    945 # umount /memdisk; mdconfig -d -u 0                   # Cleanup the md device
    946 md     /memdisk     mfs     rw,-s64M    0   0         # /etc/fstab entry
    947 
    948 Linux
    949 
    950 # mount -t tmpfs -osize=64m tmpfs /memdisk
    951 
    952 Disk performance
    953 
    954    Read and write a 1 GB file on partition ad4s3c (/home)
    955 # time dd if=/dev/ad4s3c of=/dev/null bs=1024k count=1000
    956 # time dd if=/dev/zero bs=1024k count=1000 of=/home/1Gb.file
    957 # hdparm -tT /dev/hda      # Linux only
    958 
    959 Network
    960 
    961    Routing | Additional IP | Change MAC | Ports | Firewall | IP Forward |
    962    NAT | DNS | DHCP | Traffic | QoS | NIS | Netcat
    963 
    964 Debugging (See also Traffic analysis)
    965 
    966 Linux
    967 
    968 # ethtool eth0              # Show the ethernet status (replaces mii-diag)
    969 # ethtool -s eth0 speed 100 duplex full # Force 100Mbit Full duplex
    970 # ethtool -s eth0 autoneg off # Disable auto negotiation
    971 # ethtool -p eth1           # Blink the ethernet led - very useful when supported
    972 # ip link show              # Display all interfaces on Linux (similar to ifconfi
    973 g)
    974 # ip link set eth0 up       # Bring device up (or down). Same as "ifconfig eth0 u
    975 p"
    976 # ip addr show              # Display all IP addresses on Linux (similar to ifcon
    977 fig)
    978 # ip neigh show             # Similar to arp -a
    979 
    980 Other OSes
    981 
    982 # ifconfig fxp0             # Check the "media" field on FreeBSD
    983 # arp -a                    # Check the router (or host) ARP entry (all OS)
    984 # ping cb.vu                # The first thing to try...
    985 # traceroute cb.vu          # Print the route path to destination
    986 # ifconfig fxp0 media 100baseTX mediaopt full-duplex # 100Mbit full duplex (FreeB
    987 SD)
    988 # netstat -s                # System-wide statistics for each network protocol
    989 
    990    Additional commands which are not always installed per default but easy
    991    to find:
    992 # arping 192.168.16.254     # Ping on ethernet layer
    993 # tcptraceroute -f 5 cb.vu  # uses tcp instead of icmp to trace through firewalls
    994 
    995 Routing
    996 
    997 Print routing table
    998 
    999 # route -n                  # Linux or use "ip route"
   1000 # netstat -rn               # Linux, BSD and UNIX
   1001 # route print               # Windows
   1002 
   1003 Add and delete a route
   1004 
   1005 FreeBSD
   1006 
   1007 # route add 212.117.0.0/16 192.168.1.1
   1008 # route delete 212.117.0.0/16
   1009 # route add default 192.168.1.1
   1010 
   1011    Add the route permanently in /etc/rc.conf
   1012 static_routes="myroute"
   1013 route_myroute="-net 212.117.0.0/16 192.168.1.1"
   1014 
   1015 OS X
   1016 
   1017 # sudo route -n add 192.168.0.0/27 192.168.0.62         # add a route
   1018 # netstat -nr                                           # routing table
   1019 
   1020 Linux
   1021 
   1022 # route add -net 192.168.20.0 netmask 255.255.255.0 gw 192.168.16.254
   1023 # ip route add 192.168.20.0/24 via 192.168.16.254       # same as above with ip r
   1024 oute
   1025 # route add -net 192.168.20.0 netmask 255.255.255.0 dev eth0
   1026 # route add default gw 192.168.51.254
   1027 # ip route add default via 192.168.51.254 dev eth0      # same as above with ip r
   1028 oute
   1029 # route delete -net 192.168.20.0 netmask 255.255.255.0
   1030 
   1031 Solaris
   1032 
   1033 # route add -net 192.168.20.0 -netmask 255.255.255.0 192.168.16.254
   1034 # route add default 192.168.51.254 1                    # 1 = hops to the next ga
   1035 teway
   1036 # route change default 192.168.50.254 1
   1037 
   1038    Permanent entries are set in entry in /etc/defaultrouter.
   1039 
   1040 Windows
   1041 
   1042 # Route add 192.168.50.0 mask 255.255.255.0 192.168.51.253
   1043 # Route add 0.0.0.0 mask 0.0.0.0 192.168.51.254
   1044 
   1045    Use add -p to make the route persistent.
   1046 
   1047 Configure additional IP addresses
   1048 
   1049 Linux
   1050 
   1051 # ifconfig eth0 192.168.50.254 netmask 255.255.255.0       # First IP
   1052 # ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0     # Second IP
   1053 # ip addr add 192.168.50.254/24 dev eth0                   # Equivalent ip comman
   1054 ds
   1055 # ip link set dev eth0 up                                  # Activate eth0 networ
   1056 k interface
   1057 # ip addr add 192.168.51.254/24 dev eth0 label eth0:1
   1058 # ip link ls dev eth0                                      # Get info on eth0
   1059 # ip addr del 1.2.3.4/32 dev eth0                          # Remove an IP
   1060 # ip addr flush dev eth0                                   # Remove all addresses
   1061 
   1062 FreeBSD
   1063 
   1064 # ifconfig fxp0 inet 192.168.50.254/24                     # First IP
   1065 # ifconfig fxp0 alias 192.168.51.254 netmask 255.255.255.0 # Second IP
   1066 # ifconfig fxp0 -alias 192.168.51.254                      # Remove second IP ali
   1067 as
   1068 
   1069    Permanent entries in /etc/rc.conf
   1070 ifconfig_fxp0="inet 192.168.50.254  netmask 255.255.255.0"
   1071 ifconfig_fxp0_alias0="192.168.51.254 netmask 255.255.255.0"
   1072 
   1073 OS X
   1074 
   1075 # sudo ifconfig en3 10.10.10.201/24                        # First IP
   1076 # ifconfig en3 delete 10.10.10.201                         # Delete IP
   1077 # sudo ifconfig en1 down ; sudo ifconfig en1 up
   1078 # ipconfig getifaddr en1                                   # current IP address
   1079 
   1080 Solaris
   1081 
   1082    Check the settings with ifconfig -a
   1083 # ifconfig hme0 plumb                                      # Enable the network c
   1084 ard
   1085 # ifconfig hme0 192.168.50.254 netmask 255.255.255.0 up    # First IP
   1086 # ifconfig hme0:1 192.168.51.254 netmask 255.255.255.0 up  # Second IP
   1087 
   1088 Change MAC address
   1089 
   1090    Normally you have to bring the interface down before the change. Don't
   1091    tell me why you want to change the MAC address...
   1092 # ifconfig eth0 down
   1093 # ifconfig eth0 hw ether 00:01:02:03:04:05      # Linux
   1094 # ifconfig fxp0 link 00:01:02:03:04:05          # FreeBSD
   1095 # ifconfig hme0 ether 00:01:02:03:04:05         # Solaris
   1096 # sudo ifconfig en0 ether 00:01:02:03:04:05     # OS X Tiger, Snow Leopard LAN*
   1097 # sudo ifconfig en0 lladdr 00:01:02:03:04:05    # OS X Leopard
   1098 
   1099    *Typical wireless interface is en1 and needs do disassociate from any
   1100    network first (osxdaily howto).
   1101 # echo "alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Ver
   1102 sions/Current/Resources/airport'"\
   1103 >> ~/.bash_profile         # or symlink to /usr/sbin
   1104 # airport -z               # Disassociate from wireless networks
   1105 # airport -I               # Get info from wireless network
   1106 
   1107    Many tools exist for Windows. For example
   1108    etherchangehttp://ntsecurity.nu/toolbox/etherchange. Or look for "Mac
   1109    Makeup", "smac".
   1110 
   1111 Ports in use
   1112 
   1113    Listening open ports:
   1114 # netstat -an | grep LISTEN
   1115 # lsof -i                  # Linux list all Internet connections
   1116 # socklist                 # Linux display list of open sockets
   1117 # sockstat -4              # FreeBSD application listing
   1118 # netstat -anp --udp --tcp | grep LISTEN        # Linux
   1119 # netstat -tup             # List active connections to/from system (Linux)
   1120 # netstat -tupl            # List listening ports from system (Linux)
   1121 # netstat -ano             # Windows
   1122 
   1123 Firewall
   1124 
   1125    Check if a firewall is running (typical configuration only):
   1126 
   1127 Linux
   1128 
   1129 # iptables -L -n -v                  # For status
   1130 Open the iptables firewall
   1131 # iptables -P INPUT       ACCEPT     # Open everything
   1132 # iptables -P FORWARD     ACCEPT
   1133 # iptables -P OUTPUT      ACCEPT
   1134 # iptables -Z                        # Zero the packet and byte counters in all c
   1135 hains
   1136 # iptables -F                        # Flush all chains
   1137 # iptables -X                        # Delete all chains
   1138 
   1139 FreeBSD
   1140 
   1141 # ipfw show                          # For status
   1142 # ipfw list 65535 # if answer is "65535 deny ip from any to any" the fw is disabl
   1143 ed
   1144 # sysctl net.inet.ip.fw.enable=0     # Disable
   1145 # sysctl net.inet.ip.fw.enable=1     # Enable
   1146 
   1147 IP Forward for routing
   1148 
   1149 Linux
   1150 
   1151    Check and then enable IP forward with:
   1152 # cat /proc/sys/net/ipv4/ip_forward  # Check IP forward 0=off, 1=on
   1153 # echo 1 > /proc/sys/net/ipv4/ip_forward
   1154 
   1155    or edit /etc/sysctl.conf with:
   1156 net.ipv4.ip_forward = 1
   1157 
   1158 FreeBSD
   1159 
   1160    Check and enable with:
   1161 # sysctl net.inet.ip.forwarding      # Check IP forward 0=off, 1=on
   1162 # sysctl net.inet.ip.forwarding=1
   1163 # sysctl net.inet.ip.fastforwarding=1   # For dedicated router or firewall
   1164 Permanent with entry in /etc/rc.conf:
   1165 gateway_enable="YES"                 # Set to YES if this host will be a gateway.
   1166 
   1167 Solaris
   1168 
   1169 # ndd -set /dev/ip ip_forwarding 1   # Set IP forward 0=off, 1=on
   1170 
   1171 NAT Network Address Translation
   1172 
   1173 Linux
   1174 
   1175 # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE  # to activate NAT
   1176 # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 20022 -j DNAT \
   1177 --to 192.168.16.44:22           # Port forward 20022 to internal IP port ssh
   1178 # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 993:995 -j DNAT \
   1179 --to 192.168.16.254:993-995     # Port forward of range 993-995
   1180 # ip route flush cache
   1181 # iptables -L -t nat            # Check NAT status
   1182 
   1183    Delete the port forward with -D instead of -A. The program
   1184    netstat-nathttp://tweegy.nl/projects/netstat-nat is very useful to track
   1185    connections (it uses /proc/net/ip_conntrack or /proc/net/nf_conntrack).
   1186 # netstat-nat -n                # show all connections with IPs
   1187 
   1188 FreeBSD
   1189 
   1190 # natd -s -m -u -dynamic -f /etc/natd.conf -n fxp0
   1191 Or edit /etc/rc.conf with:
   1192 firewall_enable="YES"           # Set to YES to enable firewall functionality
   1193 firewall_type="open"            # Firewall type (see /etc/rc.firewall)
   1194 natd_enable="YES"               # Enable natd (if firewall_enable == YES).
   1195 natd_interface="tun0"           # Public interface or IP address to use.
   1196 natd_flags="-s -m -u -dynamic -f /etc/natd.conf"
   1197 
   1198    Port forward with:
   1199 # cat /etc/natd.conf
   1200 same_ports yes
   1201 use_sockets yes
   1202 unregistered_only
   1203 # redirect_port tcp insideIP:2300-2399 3300-3399  # port range
   1204 redirect_port udp 192.168.51.103:7777 7777
   1205 
   1206 DNS
   1207 
   1208    On Unix the DNS entries are valid for all interfaces and are stored in
   1209    /etc/resolv.conf. The domain to which the host belongs is also stored in
   1210    this file. A minimal configuration is:
   1211 nameserver 78.31.70.238
   1212 search sleepyowl.net intern.lab
   1213 domain sleepyowl.net
   1214 
   1215    Check the system domain name with:
   1216 # hostname -d                        # Same as dnsdomainname
   1217 
   1218 Windows
   1219 
   1220    On Windows the DNS are configured per interface. To display the
   1221    configured DNS and to flush the DNS cache use:
   1222 # ipconfig /?                        # Display help
   1223 # ipconfig /all                      # See all information including DNS
   1224 
   1225 Flush DNS
   1226 
   1227    Flush the OS DNS cache, some application using their own cache (e.g.
   1228    Firefox) and will be unaffected.
   1229 # /etc/init.d/nscd restart           # Restart nscd if used - Linux/BSD/Solaris
   1230 # lookupd -flushcache                # OS X Tiger
   1231 # dscacheutil -flushcache            # OS X Leopard and newer
   1232 # ipconfig /flushdns                 # Windows
   1233 
   1234 Forward queries
   1235 
   1236    Dig is you friend to test the DNS settings. For example the public DNS
   1237    server 213.133.105.2 ns.second-ns.de can be used for testing. See from
   1238    which server the client receives the answer (simplified answer).
   1239 # dig sleepyowl.net
   1240 sleepyowl.net.          600     IN      A       78.31.70.238
   1241 ;; SERVER: 192.168.51.254#53(192.168.51.254)
   1242 
   1243    The router 192.168.51.254 answered and the response is the A entry. Any
   1244    entry can be queried and the DNS server can be selected with @:
   1245 # dig MX google.com
   1246 # dig @127.0.0.1 NS sun.com          # To test the local server
   1247 # dig @204.97.212.10 NS MX heise.de  # Query an external server
   1248 # dig AXFR @ns1.xname.org cb.vu      # Get the full zone (zone transfer)
   1249 
   1250    The program host is also powerful.
   1251 # host -t MX cb.vu                   # Get the mail MX entry
   1252 # host -t NS -T sun.com              # Get the NS record over a TCP connection
   1253 # host -a sleepyowl.net              # Get everything
   1254 
   1255 Reverse queries
   1256 
   1257    Find the name belonging to an IP address (in-addr.arpa.). This can be
   1258    done with dig, host and nslookup:
   1259 # dig -x 78.31.70.238
   1260 # host 78.31.70.238
   1261 # nslookup 78.31.70.238
   1262 
   1263 /etc/hosts
   1264 
   1265    Single hosts can be configured in the file /etc/hosts instead of running
   1266    named locally to resolve the hostname queries. The format is simple, for
   1267    example:
   1268 78.31.70.238   sleepyowl.net   sleepyowl
   1269 
   1270    The priority between hosts and a dns query, that is the name resolution
   1271    order, can be configured in /etc/nsswitch.conf AND /etc/host.conf. The
   1272    file also exists on Windows, it is usually in:
   1273 C:\WINDOWS\SYSTEM32\DRIVERS\ETC
   1274 
   1275 DHCP
   1276 
   1277 Linux
   1278 
   1279    Some distributions (SuSE) use dhcpcd as client. The default interface is
   1280    eth0.
   1281 # dhcpcd -n eth0           # Trigger a renew (does not always work)
   1282 # dhcpcd -k eth0           # release and shutdown
   1283 
   1284    The lease with the full information is stored in:
   1285 /var/lib/dhcpcd/dhcpcd-eth0.info
   1286 
   1287 FreeBSD
   1288 
   1289    FreeBSD (and Debian) uses dhclient. To configure an interface (for
   1290    example bge0) run:
   1291 # dhclient bge0
   1292 
   1293    The lease with the full information is stored in:
   1294 /var/db/dhclient.leases.bge0
   1295 
   1296    Use
   1297 /etc/dhclient.conf
   1298 
   1299    to prepend options or force different options:
   1300 # cat /etc/dhclient.conf
   1301 interface "rl0" {
   1302     prepend domain-name-servers 127.0.0.1;
   1303     default domain-name "sleepyowl.net";
   1304     supersede domain-name "sleepyowl.net";
   1305 }
   1306 
   1307 Windows
   1308 
   1309    The dhcp lease can be renewed with ipconfig:
   1310 # ipconfig /renew          # renew all adapters
   1311 # ipconfig /renew LAN      # renew the adapter named "LAN"
   1312 # ipconfig /release WLAN   # release the adapter named "WLAN"
   1313 
   1314    Yes it is a good idea to rename you adapter with simple names!
   1315 
   1316 Traffic analysis
   1317 
   1318    Bmonhttp://people.suug.ch/~tgr/bmon/ is a small console bandwidth
   1319    monitor and can display the flow on different interfaces.
   1320 
   1321 Sniff with tcpdump
   1322 
   1323 # tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54\)
   1324 # tcpdump -n -i eth1 net 192.168.16.121           # select to/from a single IP
   1325 # tcpdump -n -i eth1 net 192.168.16.0/24          # select traffic to/from a netw
   1326 ork
   1327 # tcpdump -l > dump && tail -f dump               # Buffered output
   1328 # tcpdump -i rl0 -w traffic.rl0                   # Write traffic headers in bina
   1329 ry file
   1330 # tcpdump -i rl0 -s 0 -w traffic.rl0              # Write traffic + payload in bi
   1331 nary file
   1332 # tcpdump -r traffic.rl0                          # Read from file (also for ethe
   1333 real
   1334 # tcpdump port 80                                 # The two classic commands
   1335 # tcpdump host google.com
   1336 # tcpdump -i eth0 -X port \(110 or 143\)          # Check if pop or imap is secur
   1337 e
   1338 # tcpdump -n -i eth0 icmp                         # Only catch pings
   1339 # tcpdump -i eth0 -s 0 -A port 80 | grep GET      # -s 0 for full packet -A for A
   1340 SCII
   1341 
   1342    Additional important options:
   1343      * -A     Print each packets in clear text (without header)
   1344      * -X     Print packets in hex and ASCII
   1345      * -l     Make stdout line buffered
   1346      * -D     Print all interfaces available
   1347 
   1348    On Windows use windump from www.winpcap.org. Use windump -D to list the
   1349    interfaces.
   1350 
   1351 Scan with nmap
   1352 
   1353    Nmaphttp://insecure.org/nmap/ is a port scanner with OS detection, it is
   1354    usually installed on most distributions and is also available for
   1355    Windows. If you don't scan your servers, hackers do it for you...
   1356 # nmap cb.vu               # scans all reserved TCP ports on the host
   1357 # nmap -sP 192.168.16.0/24 # Find out which IP are used and by which host on 0/24
   1358 # nmap -sS -sV -O cb.vu    # Do a stealth SYN scan with version and OS detection
   1359 PORT      STATE  SERVICE             VERSION
   1360 22/tcp    open   ssh                 OpenSSH 3.8.1p1 FreeBSD-20060930 (protocol 2
   1361 .0)
   1362 25/tcp    open   smtp                Sendmail smtpd 8.13.6/8.13.6
   1363 80/tcp    open   http                Apache httpd 2.0.59 ((FreeBSD) DAV/2 PHP/4.
   1364 [...]
   1365 Running: FreeBSD 5.X
   1366 Uptime 33.120 days (since Fri Aug 31 11:41:04 2007)
   1367 
   1368    Other non standard but useful tools are hping (www.hping.org) an IP
   1369    packet assembler/analyzer and fping (fping.sourceforge.net). fping can
   1370    check multiple hosts in a round-robin fashion.
   1371 
   1372 Traffic control (QoS)
   1373 
   1374    Traffic control manages the queuing, policing, scheduling, and other
   1375    traffic parameters for a network. The following examples are simple
   1376    practical uses of the Linux and FreeBSD capabilities to better use the
   1377    available bandwidth.
   1378 
   1379 Limit upload
   1380 
   1381    DSL or cable modems have a long queue to improve the upload throughput.
   1382    However filling the queue with a fast device (e.g. ethernet) will
   1383    dramatically decrease the interactivity. It is therefore useful to limit
   1384    the device upload rate to match the physical capacity of the modem, this
   1385    should greatly improve the interactivity. Set to about 90% of the modem
   1386    maximal (cable) speed.
   1387 
   1388 Linux
   1389 
   1390    For a 512 Kbit upload modem.
   1391 # tc qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540
   1392 # tc -s qdisc ls dev eth0                         # Status
   1393 # tc qdisc del dev eth0 root                      # Delete the queue
   1394 # tc qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540
   1395 
   1396 FreeBSD
   1397 
   1398    FreeBSD uses the dummynet traffic shaper which is configured with ipfw.
   1399    Pipes are used to set limits the bandwidth in units of
   1400    [K|M]{bit/s|Byte/s}, 0 means unlimited bandwidth. Using the same pipe
   1401    number will reconfigure it. For example limit the upload bandwidth to
   1402    500 Kbit.
   1403 # kldload dummynet                                # load the module if necessary
   1404 # ipfw pipe 1 config bw 500Kbit/s                 # create a pipe with limited ba
   1405 ndwidth
   1406 # ipfw add pipe 1 ip from me to any               # divert the full upload into t
   1407 he pipe
   1408 
   1409 Quality of service
   1410 
   1411 Linux
   1412 
   1413    Priority queuing with tc to optimize VoIP. See the full example on
   1414    voip-info.org or www.howtoforge.com. Suppose VoIP uses udp on ports
   1415    10000:11024 and device eth0 (could also be ppp0 or so). The following
   1416    commands define the QoS to three queues and force the VoIP traffic to
   1417    queue 1 with QoS 0x1e (all bits set). The default traffic flows into
   1418    queue 3 and QoS Minimize-Delay flows into queue 2.
   1419 # tc qdisc add dev eth0 root handle 1: prio priomap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1
   1420  0
   1421 # tc qdisc add dev eth0 parent 1:1 handle 10: sfq
   1422 # tc qdisc add dev eth0 parent 1:2 handle 20: sfq
   1423 # tc qdisc add dev eth0 parent 1:3 handle 30: sfq
   1424 # tc filter add dev eth0 protocol ip parent 1: prio 1 u32 \
   1425   match ip dport 10000 0x3C00 flowid 1:1          # use server port range
   1426   match ip dst 123.23.0.1 flowid 1:1              # or/and use server IP
   1427 
   1428    Status and remove with
   1429 # tc -s qdisc ls dev eth0                         # queue status
   1430 # tc qdisc del dev eth0 root                      # delete all QoS
   1431 
   1432 Calculate port range and mask
   1433 
   1434    The tc filter defines the port range with port and mask which you have
   1435    to calculate. Find the 2^N ending of the port range, deduce the range
   1436    and convert to HEX. This is your mask. Example for 10000 -> 11024, the
   1437    range is 1024.
   1438 # 2^13 (8192) < 10000 < 2^14 (16384)              # ending is 2^14 = 16384
   1439 # echo "obase=16;(2^14)-1024" | bc                # mask is 0x3C00
   1440 
   1441 FreeBSD
   1442 
   1443    The max link bandwidth is 500Kbit/s and we define 3 queues with priority
   1444    100:10:1 for VoIP:ssh:all the rest.
   1445 # ipfw pipe 1 config bw 500Kbit/s
   1446 # ipfw queue 1 config pipe 1 weight 100
   1447 # ipfw queue 2 config pipe 1 weight 10
   1448 # ipfw queue 3 config pipe 1 weight 1
   1449 # ipfw add 10 queue 1 proto udp dst-port 10000-11024
   1450 # ipfw add 11 queue 1 proto udp dst-ip 123.23.0.1 # or/and use server IP
   1451 # ipfw add 20 queue 2 dsp-port ssh
   1452 # ipfw add 30 queue 3 from me to any              # all the rest
   1453 
   1454    Status and remove with
   1455 # ipfw list                                       # rules status
   1456 # ipfw pipe list                                  # pipe status
   1457 # ipfw flush                                      # deletes all rules but default
   1458 
   1459 NIS Debugging
   1460 
   1461    Some commands which should work on a well configured NIS client:
   1462 # ypwhich                  # get the connected NIS server name
   1463 # domainname               # The NIS domain name as configured
   1464 # ypcat group              # should display the group from the NIS server
   1465 # cd /var/yp && make       # Rebuild the yp database
   1466 # rpcinfo -p servername    # Report RPC services of the server
   1467 
   1468    Is ypbind running?
   1469 # ps auxww | grep ypbind
   1470 /usr/sbin/ypbind -s -m -S servername1,servername2       # FreeBSD
   1471 /usr/sbin/ypbind           # Linux
   1472 # yppoll passwd.byname
   1473 Map passwd.byname has order number 1190635041. Mon Sep 24 13:57:21 2007
   1474 The master server is servername.domain.net.
   1475 
   1476 Linux
   1477 
   1478 # cat /etc/yp.conf
   1479 ypserver servername
   1480 domain domain.net broadcast
   1481 
   1482 Netcat
   1483 
   1484    Netcathttp://netcat.sourceforge.net (nc) is better known as the "network
   1485    Swiss Army Knife", it can manipulate, create or read/write TCP/IP
   1486    connections. Here some useful examples, there are many more on the net,
   1487    for example
   1488    g-loaded.eu[...]http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-use
   1489    ful-examples and
   1490    herehttp://www.terminally-incoherent.com/blog/2007/08/07/few-useful-netc
   1491    at-tricks.
   1492    You might need to use the command netcat instead of nc. Also see the
   1493    similar command socat.
   1494 
   1495 File transfer
   1496 
   1497    Copy a large folder over a raw tcp connection. The transfer is very
   1498    quick (no protocol overhead) and you don't need to mess up with NFS or
   1499    SMB or FTP or so, simply make the file available on the server, and get
   1500    it from the client. Here 192.168.1.1 is the server IP address.
   1501 server# tar -cf - -C VIDEO_TS . | nc -l -p 4444         # Serve tar folder on por
   1502 t 4444
   1503 client# nc 192.168.1.1 4444 | tar xpf - -C VIDEO_TS     # Pull the file on port 4
   1504 444
   1505 server# cat largefile | nc -l 5678                      # Server a single file
   1506 client# nc 192.168.1.1 5678 > largefile                 # Pull the single file
   1507 server# dd if=/dev/da0 | nc -l 4444                     # Server partition image
   1508 client# nc 192.168.1.1 4444 | dd of=/dev/da0            # Pull partition to clone
   1509 client# nc 192.168.1.1 4444 | dd of=da0.img             # Pull partition to file
   1510 
   1511 Other hacks
   1512 
   1513    Specially here, you must know what you are doing.
   1514 
   1515 Remote shell
   1516 
   1517    Option -e only on the Windows version? Or use nc 1.10.
   1518 # nc -lp 4444 -e /bin/bash                        # Provide a remote shell (serve
   1519 r backdoor)
   1520 # nc -lp 4444 -e cmd.exe                          # remote shell for Windows
   1521 
   1522 Emergency web server
   1523 
   1524    Serve a single file on port 80 in a loop.
   1525 # while true; do nc -l -p 80 < unixtoolbox.xhtml; done
   1526 
   1527 Chat
   1528 
   1529    Alice and Bob can chat over a simple TCP socket. The text is transferred
   1530    with the enter key.
   1531 alice# nc -lp 4444
   1532 bob  # nc 192.168.1.1 4444
   1533 
   1534 SSH SCP
   1535 
   1536    Public key | Fingerprint | SCP | Tunneling | SSHFS
   1537    See other tricks 25 ssh cmdhttp://blog.urfix.com/25-ssh-commands-tricks/
   1538 
   1539 Public key authentication
   1540 
   1541    Connect to a host without password using public key authentication. The
   1542    idea is to append your public key to the authorized_keys2 file on the
   1543    remote host. For this example let's connect host-client to host-server,
   1544    the key is generated on the client. With cygwin you might have to create
   1545    your home directoy and the .ssh directory with # mkdir -p
   1546    /home/USER/.ssh
   1547      * Use ssh-keygen to generate a key pair. ~/.ssh/id_dsa is the private
   1548        key, ~/.ssh/id_dsa.pub is the public key.
   1549      * Copy only the public key to the server and append it to the file
   1550        ~/.ssh/authorized_keys2 on your home on the server.
   1551 
   1552 # ssh-keygen -t dsa -N ''
   1553 # cat ~/.ssh/id_dsa.pub | ssh you@host-server "cat - >> ~/.ssh/authorized_keys2"
   1554 
   1555 Using the Windows client from ssh.com
   1556 
   1557    The non commercial version of the ssh.com client can be downloaded the
   1558    main ftp site: ftp.ssh.com/pub/ssh/. Keys generated by the ssh.com
   1559    client need to be converted for the OpenSSH server. This can be done
   1560    with the ssh-keygen command.
   1561      * Create a key pair with the ssh.com client: Settings - User
   1562        Authentication - Generate New....
   1563      * I use Key type DSA; key length 2048.
   1564      * Copy the public key generated by the ssh.com client to the server
   1565        into the ~/.ssh folder.
   1566      * The keys are in C:\Documents and Settings\%USERNAME%\Application
   1567        Data\SSH\UserKeys.
   1568      * Use the ssh-keygen command on the server to convert the key:
   1569 # cd ~/.ssh
   1570 # ssh-keygen -i -f keyfilename.pub >> authorized_keys2
   1571 
   1572    Notice: We used a DSA key, RSA is also possible. The key is not
   1573    protected by a password.
   1574 
   1575 Using putty for Windows
   1576 
   1577    Puttyhttp://www.chiark.greenend.org.uk/~sgtatham/putty/download.html is
   1578    a simple and free ssh client for Windows.
   1579      * Create a key pair with the puTTYgen program.
   1580      * Save the public and private keys (for example into C:\Documents and
   1581        Settings\%USERNAME%\.ssh).
   1582      * Copy the public key to the server into the ~/.ssh folder:
   1583 # scp .ssh/puttykey.pub root@192.168.51.254:.ssh/
   1584      * Use the ssh-keygen command on the server to convert the key for
   1585        OpenSSH:
   1586 # cd ~/.ssh
   1587 # ssh-keygen -i -f puttykey.pub >> authorized_keys2
   1588 
   1589      * Point the private key location in the putty settings: Connection -
   1590        SSH - Auth
   1591 
   1592 Check fingerprint
   1593 
   1594    At the first login, ssh will ask if the unknown host with the
   1595    fingerprint has to be stored in the known hosts. To avoid a
   1596    man-in-the-middle attack the administrator of the server can send you
   1597    the server fingerprint which is then compared on the first login. Use
   1598    ssh-keygen -l to get the fingerprint (on the server):
   1599 # ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub      # For RSA key
   1600 2048 61:33:be:9b:ae:6c:36:31:fd:83:98:b7:99:2d:9f:cd /etc/ssh/ssh_host_rsa_key.pu
   1601 b
   1602 # ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub      # For DSA key (default)
   1603 2048 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee /etc/ssh/ssh_host_dsa_key.pu
   1604 b
   1605 
   1606    Now the client connecting to this server can verify that he is
   1607    connecting to the right server:
   1608 # ssh linda
   1609 The authenticity of host 'linda (192.168.16.54)' can't be established.
   1610 DSA key fingerprint is 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee.
   1611 Are you sure you want to continue connecting (yes/no)? yes
   1612 
   1613 Secure file transfer
   1614 
   1615    Some simple commands:
   1616 # scp file.txt host-two:/tmp
   1617 # scp joe@host-two:/www/*.html /www/tmp
   1618 # scp -r joe@host-two:/www /www/tmp
   1619 # scp -P 20022 cb@cb.vu:unixtoolbox.xhtml .           # connect on port 20022
   1620 
   1621    In Konqueror or Midnight Commander it is possible to access a remote
   1622    file system with the address fish://user@gate. However the
   1623    implementation is very slow.
   1624    Furthermore it is possible to mount a remote folder with sshfs a file
   1625    system client based on SCP. See fuse
   1626    sshfshttp://fuse.sourceforge.net/sshfs.html.
   1627 ssh_exchange_identification: Connection closed by remote host
   1628 
   1629    With this error try the following on the server:
   1630 echo 'SSHD: ALL' >> /etc/hosts.allow
   1631 /etc/init.d/sshd restart
   1632 
   1633 Tunneling
   1634 
   1635    SSH tunneling allows to forward or reverse forward a port over the SSH
   1636    connection, thus securing the traffic and accessing ports which would
   1637    otherwise be blocked. This only works with TCP. The general nomenclature
   1638    for forward and reverse is (see also ssh and NAT example):
   1639 # ssh -L localport:desthost:destport user@gate  # desthost as seen from the gate
   1640 # ssh -R destport:desthost:localport user@gate  # forwards your localport to dest
   1641 ination
   1642     # desthost:localport as seen from the client initiating the tunnel
   1643 # ssh -X user@gate   # To force X forwarding
   1644 
   1645    This will connect to gate and forward the local port to the host
   1646    desthost:destport. Note desthost is the destination host as seen by the
   1647    gate, so if the connection is to the gate, then desthost is localhost.
   1648    More than one port forward is possible.
   1649 
   1650 Direct forward on the gate
   1651 
   1652    Let say we want to access the CVS (port 2401) and http (port 80) which
   1653    are running on the gate. This is the simplest example, desthost is thus
   1654    localhost, and we use the port 8080 locally instead of 80 so we don't
   1655    need to be root. Once the ssh session is open, both services are
   1656    accessible on the local ports.
   1657 # ssh -L 2401:localhost:2401 -L 8080:localhost:80 user@gate
   1658 
   1659 Netbios and remote desktop forward to a second server
   1660 
   1661    Let say a Windows smb server is behind the gate and is not running ssh.
   1662    We need access to the smb share and also remote desktop to the server.
   1663 # ssh -L 139:smbserver:139 -L 3388:smbserver:3389 user@gate
   1664 
   1665    The smb share can now be accessed with \\127.0.0.1\, but only if the
   1666    local share is disabled, because the local share is listening on port
   1667    139.
   1668    It is possible to keep the local share enabled, for this we need to
   1669    create a new virtual device with a new IP address for the tunnel, the
   1670    smb share will be connected over this address. Furthermore the local RDP
   1671    is already listening on 3389, so we choose 3388. For this example let's
   1672    use a virtual IP of 10.1.1.1.
   1673      * With putty use Source port=10.1.1.1:139. It is possible to create
   1674        multiple loop devices and tunnel. On Windows 2000, only putty worked
   1675        for me. On Windows Vista also forward the port 445 in addition to
   1676        the port 139. Also on Vista the patch KB942624 prevents the port 445
   1677        to be forwarded, so I had to uninstall this path in Vista.
   1678      * With the ssh.com client, disable "Allow local connections only".
   1679        Since ssh.com will bind to all addresses, only a single share can be
   1680        connected.
   1681 
   1682    Now create the loopback interface with IP 10.1.1.1:
   1683      * # System->Control Panel->Add Hardware # Yes, Hardware is already
   1684        connected # Add a new hardware device (at bottom).
   1685      * # Install the hardware that I manually select # Network adapters #
   1686        Microsoft , Microsoft Loopback Adapter.
   1687      * Configure the IP address of the fake device to 10.1.1.1 mask
   1688        255.255.255.0, no gateway.
   1689      * advanced->WINS, Enable LMHosts Lookup; Disable NetBIOS over TCP/IP.
   1690      * # Enable Client for Microsoft Networks. # Disable File and Printer
   1691        Sharing for Microsoft Networks.
   1692 
   1693    I HAD to reboot for this to work. Now connect to the smb share with
   1694    \\10.1.1.1 and remote desktop to 10.1.1.1:3388.
   1695 
   1696 Debug
   1697 
   1698    If it is not working:
   1699      * Are the ports forwarded: netstat -an? Look at 0.0.0.0:139 or
   1700        10.1.1.1:139
   1701      * Does telnet 10.1.1.1 139 connect?
   1702      * You need the checkbox "Local ports accept connections from other
   1703        hosts".
   1704      * Is "File and Printer Sharing for Microsoft Networks" disabled on the
   1705        loopback interface?
   1706 
   1707 Connect two clients behind NAT
   1708 
   1709    Suppose two clients are behind a NAT gateway and client cliadmin has to
   1710    connect to client cliuser (the destination), both can login to the gate
   1711    with ssh and are running Linux with sshd. You don't need root access
   1712    anywhere as long as the ports on gate are above 1024. We use 2022 on
   1713    gate. Also since the gate is used locally, the option GatewayPorts is
   1714    not necessary.
   1715    On client cliuser (from destination to gate):
   1716 # ssh -R 2022:localhost:22 user@gate            # forwards client 22 to gate:2022
   1717 
   1718    On client cliadmin (from host to gate):
   1719 # ssh -L 3022:localhost:2022 admin@gate         # forwards client 3022 to gate:20
   1720 22
   1721 
   1722    Now the admin can connect directly to the client cliuser with:
   1723 # ssh -p 3022 admin@localhost                   # local:3022 -> gate:2022 -> clie
   1724 nt:22
   1725 
   1726 Connect to VNC behind NAT
   1727 
   1728    Suppose a Windows client with VNC listening on port 5900 has to be
   1729    accessed from behind NAT. On client cliwin to gate:
   1730 # ssh -R 15900:localhost:5900 user@gate
   1731 
   1732    On client cliadmin (from host to gate):
   1733 # ssh -L 5900:localhost:15900 admin@gate
   1734 
   1735    Now the admin can connect directly to the client VNC with:
   1736 # vncconnect -display :0 localhost
   1737 
   1738 Dig a multi-hop ssh tunnel
   1739 
   1740    Suppose you can not reach a server directly with ssh, but only via
   1741    multiple intermediate hosts (for example because of routing issues).
   1742    Sometimes it is still necessary to get a direct client - server
   1743    connection, for example to copy files with scp, or forward other ports
   1744    like smb or vnc. One way to do this is to chain tunnels together to
   1745    forward a port to the server along the hops. This "carrier" port only
   1746    reaches its final destination on the last connection to the server.
   1747    Suppose we want to forward the ssh port from a client to a server over
   1748    two hops. Once the tunnel is build, it is possible to connect to the
   1749    server directly from the client (and also add an other port forward).
   1750 
   1751 Create tunnel in one shell
   1752 
   1753    client -> host1 -> host2 -> server and dig tunnel 5678
   1754 client># ssh -L5678:localhost:5678 host1        # 5678 is an arbitrary port for t
   1755 he tunnel
   1756 host_1># ssh -L5678:localhost:5678 host2        # chain 5678 from host1 to host2
   1757 host_2># ssh -L5678:localhost:22 server         # end the tunnel on port 22 on th
   1758 e server
   1759 
   1760 Use tunnel with an other shell
   1761 
   1762    client -> server using tunnel 5678
   1763 # ssh -p 5678 localhost                         # connect directly from client to
   1764   server
   1765 # scp -P 5678 myfile localhost:/tmp/            # or copy a file directly using t
   1766 he tunnel
   1767 # rsync -e 'ssh -p 5678' myfile localhost:/tmp/ # or rsync a file directly to the
   1768  server
   1769 
   1770 Autoconnect and keep alive script
   1771 
   1772    I use variations of the following script to keep a machine reacheable
   1773    over a reverse ssh tunnel. The connection is automatically rebuilt if
   1774    closed. You can add multiple -L or -R tunnels on one line.
   1775 #!/bin/sh
   1776 COMMAND="ssh -N -f -g -R 3022:localhost:22 colin@cb.vu"
   1777 pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
   1778 exit 0
   1779 
   1780 1 * * * * colin /home/colin/port_forward.sh     # crontab entry (here hourly)
   1781 
   1782 sshfs
   1783 
   1784    Mount a filesystem with ssh.
   1785 # sshfs cb@cb.vu:/ /Users/barschel/cbvu -oauto_cache,reconnect,defer_permissions
   1786 \
   1787     ,noappledouble,negative_vncache,volname=cbvu
   1788 
   1789    Or via a two hops tunnel
   1790 # ssh -Y -A -t -L20022:127.0.0.1:20022 cbarsche@lbgw ssh -Y -A -t -L20022:127.0.0
   1791 .1:22 rootbgv@bgvctrl
   1792 # sshfs -p 20022 cb@cb.vu:/ /Users/barschel/cbvu -oauto_cache,reconnect,defer_per
   1793 missions \
   1794     ,noappledouble,negative_vncache,volname=cbvu
   1795 
   1796 VPN with SSH
   1797 
   1798    As of version 4.3, OpenSSH can use the tun/tap device to encrypt a
   1799    tunnel. This is very similar to other TLS based VPN solutions like
   1800    OpenVPN. One advantage with SSH is that there is no need to install and
   1801    configure additional software. Additionally the tunnel uses the SSH
   1802    authentication like pre shared keys. The drawback is that the
   1803    encapsulation is done over TCP which might result in poor performance on
   1804    a slow link. Also the tunnel is relying on a single (fragile) TCP
   1805    connection. This technique is very useful for a quick IP based VPN
   1806    setup. There is no limitation as with the single TCP port forward, all
   1807    layer 3/4 protocols like ICMP, TCP/UDP, etc. are forwarded over the VPN.
   1808    In any case, the following options are needed in the sshd_conf file:
   1809 PermitRootLogin yes
   1810 PermitTunnel yes
   1811 
   1812 Single P2P connection
   1813 
   1814    Here we are connecting two hosts, hclient and hserver with a peer to
   1815    peer tunnel. The connection is started from hclient to hserver and is
   1816    done as root. The tunnel end points are 10.0.1.1 (server) and 10.0.1.2
   1817    (client) and we create a device tun5 (this could also be an other
   1818    number). The procedure is very simple:
   1819      * Connect with SSH using the tunnel option -w
   1820      * Configure the IP addresses of the tunnel. Once on the server and
   1821        once on the client.
   1822 
   1823 Connect to the server
   1824 
   1825    Connection started on the client and commands are executed on the
   1826    server.
   1827 
   1828 Server is on Linux
   1829 
   1830 cli># ssh -w5:5 root@hserver
   1831 srv># ifconfig tun5 10.0.1.1 netmask 255.255.255.252   # Executed on the server s
   1832 hell
   1833 
   1834 Server is on FreeBSD
   1835 
   1836 cli># ssh -w5:5 root@hserver
   1837 srv># ifconfig tun5 10.0.1.1 10.0.1.2                  # Executed on the server s
   1838 hell
   1839 
   1840 Configure the client
   1841 
   1842    Commands executed on the client:
   1843 cli># ifconfig tun5 10.0.1.2 netmask 255.255.255.252   # Client is on Linux
   1844 cli># ifconfig tun5 10.0.1.2 10.0.1.1                  # Client is on FreeBSD
   1845 
   1846    The two hosts are now connected and can transparently communicate with
   1847    any layer 3/4 protocol using the tunnel IP addresses.
   1848 
   1849 Connect two networks
   1850 
   1851    In addition to the p2p setup above, it is more useful to connect two
   1852    private networks with an SSH VPN using two gates. Suppose for the
   1853    example, netA is 192.168.51.0/24 and netB 192.168.16.0/24. The procedure
   1854    is similar as above, we only need to add the routing. NAT must be
   1855    activated on the private interface only if the gates are not the same as
   1856    the default gateway of their network.
   1857    192.168.51.0/24 (netA)|gateA <-> gateB|192.168.16.0/24 (netB)
   1858      * Connect with SSH using the tunnel option -w.
   1859      * Configure the IP addresses of the tunnel. Once on the server and
   1860        once on the client.
   1861      * Add the routing for the two networks.
   1862      * If necessary, activate NAT on the private interface of the gate.
   1863 
   1864    The setup is started from gateA in netA.
   1865 
   1866 Connect from gateA to gateB
   1867 
   1868    Connection is started from gateA and commands are executed on gateB.
   1869 
   1870 gateB is on Linux
   1871 
   1872 gateA># ssh -w5:5 root@gateB
   1873 gateB># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executed on the gateB sh
   1874 ell
   1875 gateB># route add -net 192.168.51.0 netmask 255.255.255.0 dev tun5
   1876 gateB># echo 1 > /proc/sys/net/ipv4/ip_forward        # Only needed if not defaul
   1877 t gw
   1878 gateB># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
   1879 
   1880 gateB is on FreeBSD
   1881 
   1882 gateA># ssh -w5:5 root@gateB                          # Creates the tun5 devices
   1883 gateB># ifconfig tun5 10.0.1.1 10.0.1.2               # Executed on the gateB she
   1884 ll
   1885 gateB># route add 192.168.51.0/24 10.0.1.2
   1886 gateB># sysctl net.inet.ip.forwarding=1               # Only needed if not defaul
   1887 t gw
   1888 gateB># natd -s -m -u -dynamic -n fxp0                # see NAT
   1889 gateA># sysctl net.inet.ip.fw.enable=1
   1890 
   1891 Configure gateA
   1892 
   1893    Commands executed on gateA:
   1894 
   1895 gateA is on Linux
   1896 
   1897 gateA># ifconfig tun5 10.0.1.2 netmask 255.255.255.252
   1898 gateA># route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5
   1899 gateA># echo 1 > /proc/sys/net/ipv4/ip_forward
   1900 gateA># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
   1901 
   1902 gateA is on FreeBSD
   1903 
   1904 gateA># ifconfig tun5 10.0.1.2 10.0.1.1
   1905 gateA># route add 192.168.16.0/24 10.0.1.2
   1906 gateA># sysctl net.inet.ip.forwarding=1
   1907 gateA># natd -s -m -u -dynamic -n fxp0                # see NAT
   1908 gateA># sysctl net.inet.ip.fw.enable=1
   1909 
   1910    The two private networks are now transparently connected via the SSH
   1911    VPN. The IP forward and NAT settings are only necessary if the gates are
   1912    not the default gateways. In this case the clients would not know where
   1913    to forward the response, and nat must be activated.
   1914 
   1915 RSYNC
   1916 
   1917    Rsync can almost completely replace cp and scp, furthermore interrupted
   1918    transfers are efficiently restarted. A trailing slash (and the absence
   1919    thereof) has different meanings, the man page is good... Here some
   1920    examples:
   1921    Copy the directories with full content:
   1922 # rsync -a /home/colin/ /backup/colin/                # "archive" mode. e.g keep
   1923 the same
   1924 # rsync -a /var/ /var_bak/
   1925 # rsync -aR --delete-during /home/user/ /backup/      # use relative (see below)
   1926 # /opt/local/bin/rsync -azv --iconv=UTF-8-MAC,UTF-8 ~/Music/flac/ me@server:/dst/
   1927                            # convert filenames OSX UTF8 to Windows UTF8
   1928 
   1929    Same as before but over the network and with compression. Rsync uses SSH
   1930    for the transport per default and will use the ssh key if they are set.
   1931    Use ":" as with SCP. A typical remote copy:
   1932 # rsync -axSRzv /home/user/ user@server:/backup/user/ # Copy to remote
   1933 # rsync -a 'user@server:My\ Documents' My\ Documents  # Quote AND escape spaces f
   1934 or the remote shell
   1935 
   1936    Exclude any directory tmp within /home/user/ and keep the relative
   1937    folders hierarchy, that is the remote directory will have the structure
   1938    /backup/home/user/. This is typically used for backups.
   1939 # rsync -azR --exclude=tmp/ /home/user/ user@server:/backup/
   1940 
   1941    Use port 20022 for the ssh connection:
   1942 # rsync -az -e 'ssh -p 20022' /home/colin/ user@server:/backup/colin/
   1943 
   1944    Using the rsync daemon (used with "::") is much faster, but not
   1945    encrypted over ssh. The location of /backup is defined by the
   1946    configuration in /etc/rsyncd.conf. The variable RSYNC_PASSWORD can be
   1947    set to avoid the need to enter the password manually.
   1948 # rsync -axSRz /home/ ruser@hostname::rmodule/backup/
   1949 # rsync -axSRz ruser@hostname::rmodule/backup/ /home/    # To copy back
   1950 
   1951    Some important options:
   1952      * -a, --archive       archive mode; same as -rlptgoD (no -H)
   1953      * -r, --recursive       recurse into directories
   1954      * -R, --relative       use relative path names
   1955      * -H, --hard-links       preserve hard links
   1956      * -S, --sparse       handle sparse files efficiently
   1957      * -x, --one-file-system       don't cross file system boundaries
   1958      * --exclude=PATTERN       exclude files matching PATTERN
   1959      * --delete-during       receiver deletes during xfer, not before
   1960      * --delete-after       receiver deletes after transfer, not before
   1961 
   1962 Rsync on Windows
   1963 
   1964    Rsync is available for Windows through cygwin or as stand-alone packaged
   1965    in cwrsynchttp://sourceforge.net/projects/sereds. This is very
   1966    convenient for automated backups. Install one of them (not both) and add
   1967    the path to the Windows system variables: # Control Panel -> System ->
   1968    tab Advanced, button Environment Variables. Edit the "Path" system
   1969    variable and add the full path to the installed rsync, e.g. C:\Program
   1970    Files\cwRsync\bin or C:\cygwin\bin. This way the commands rsync and ssh
   1971    are available in a Windows command shell.
   1972 
   1973 Public key authentication
   1974 
   1975    Rsync is automatically tunneled over SSH and thus uses the SSH
   1976    authentication on the server. Automatic backups have to avoid a user
   1977    interaction, for this the SSH public key authentication can be used and
   1978    the rsync command will run without a password.
   1979    All the following commands are executed within a Windows console. In a
   1980    console (Start -> Run -> cmd) create and upload the key as described in
   1981    SSH, change "user" and "server" as appropriate. If the file
   1982    authorized_keys2 does not exist yet, simply copy id_dsa.pub to
   1983    authorized_keys2 and upload it.
   1984 # ssh-keygen -t dsa -N ''                   # Creates a public and a private key
   1985 # rsync user@server:.ssh/authorized_keys2 . # Copy the file locally from the serv
   1986 er
   1987 # cat id_dsa.pub >> authorized_keys2        # Or use an editor to add the key
   1988 # rsync authorized_keys2 user@server:.ssh/  # Copy the file back to the server
   1989 # del authorized_keys2                      # Remove the local copy
   1990 
   1991    Now test it with (in one line):
   1992 rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
   1993 'user@server:My\ Documents/'
   1994 
   1995 Automatic backup
   1996 
   1997    Use a batch file to automate the backup and add the file in the
   1998    scheduled tasks (Programs -> Accessories -> System Tools -> Scheduled
   1999    Tasks). For example create the file backup.bat and replace user@server.
   2000 @ECHO OFF
   2001 REM rsync the directory My Documents
   2002 SETLOCAL
   2003 SET CWRSYNCHOME=C:\PROGRAM FILES\CWRSYNC
   2004 SET CYGWIN=nontsec
   2005 SET CWOLDPATH=%PATH%
   2006 REM uncomment the next line when using cygwin
   2007 SET PATH=%CWRSYNCHOME%\BIN;%PATH%
   2008 echo Press Control-C to abort
   2009 rsync -av "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
   2010 'user@server:My\ Documents/'
   2011 pause
   2012 
   2013 SUDO
   2014 
   2015    Sudo is a standard way to give users some administrative rights without
   2016    giving out the root password. Sudo is very useful in a multi user
   2017    environment with a mix of server and workstations. Simply call the
   2018    command with sudo:
   2019 # sudo /etc/init.d/dhcpd restart            # Run the rc script as root
   2020 # sudo -u sysadmin whoami                   # Run cmd as an other user
   2021 
   2022 Configuration
   2023 
   2024    Sudo is configured in /etc/sudoers and must only be edited with visudo.
   2025    The basic syntax is (the lists are comma separated):
   2026 user hosts = (runas) commands          # In /etc/sudoers
   2027      * users one or more users or %group (like %wheel) to gain the rights
   2028      * hosts list of hosts (or ALL)
   2029      * runas list of users (or ALL) that the command rule can be run as. It
   2030        is enclosed in ( )!
   2031      * commands list of commands (or ALL) that will be run as root or as
   2032        (runas)
   2033 
   2034    Additionally those keywords can be defined as alias, they are called
   2035    User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for
   2036    larger setups. Here a sudoers example:
   2037 # cat /etc/sudoers
   2038 # Host aliases are subnets or hostnames.
   2039 Host_Alias   DMZ     = 212.118.81.40/28
   2040 Host_Alias   DESKTOP = work1, work2
   2041 
   2042 # User aliases are a list of users which can have the same rights
   2043 User_Alias   ADMINS  = colin, luca, admin
   2044 User_Alias   DEVEL   = joe, jack, julia
   2045 Runas_Alias  DBA     = oracle,pgsql
   2046 
   2047 # Command aliases define the full path of a list of commands
   2048 Cmnd_Alias   SYSTEM  = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/
   2049 init.d/
   2050 Cmnd_Alias   PW      = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root # Not root p
   2051 wd!
   2052 Cmnd_Alias   DEBUG   = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap
   2053 
   2054 # The actual rules
   2055 root,ADMINS  ALL     = (ALL) NOPASSWD: ALL    # ADMINS can do anything w/o a pass
   2056 word.
   2057 DEVEL        DESKTOP = (ALL) NOPASSWD: ALL    # Developers have full right on des
   2058 ktops
   2059 DEVEL        DMZ     = (ALL) NOPASSWD: DEBUG  # Developers can debug the DMZ serv
   2060 ers.
   2061 
   2062 # User sysadmin can mess around in the DMZ servers with some commands.
   2063 sysadmin     DMZ     = (ALL) NOPASSWD: SYSTEM,PW,DEBUG
   2064 sysadmin     ALL,!DMZ = (ALL) NOPASSWD: ALL   # Can do anything outside the DMZ.
   2065 %dba         ALL     = (DBA) ALL              # Group dba can run as database use
   2066 r.
   2067 
   2068 # anyone can mount/unmount a cd-rom on the desktop machines
   2069 ALL          DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom
   2070 
   2071 Encrypt Files
   2072 
   2073 OpenSSL
   2074 
   2075 A single file
   2076 
   2077    Encrypt and decrypt:
   2078 # openssl aes-128-cbc -salt -in file -out file.aes
   2079 # openssl aes-128-cbc -d -salt -in file.aes -out file
   2080 
   2081    Note that the file can of course be a tar archive.
   2082 
   2083 tar and encrypt a whole directory
   2084 
   2085 # tar -cf - directory | openssl aes-128-cbc -salt -out directory.tar.aes      # E
   2086 ncrypt
   2087 # openssl aes-128-cbc -d -salt -in directory.tar.aes | tar -x -f -            # D
   2088 ecrypt
   2089 
   2090 tar zip and encrypt a whole directory
   2091 
   2092 # tar -zcf - directory | openssl aes-128-cbc -salt -out directory.tar.gz.aes  # E
   2093 ncrypt
   2094 # openssl aes-128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f -        # D
   2095 ecrypt
   2096 
   2097      * Use -k mysecretpassword after aes-128-cbc to avoid the interactive
   2098        password request. However note that this is highly insecure.
   2099      * Use aes-256-cbc instead of aes-128-cbc to get even stronger
   2100        encryption. This uses also more CPU.
   2101 
   2102 GPG
   2103 
   2104    GnuPG is well known to encrypt and sign emails or any data. Furthermore
   2105    gpg and also provides an advanced key management system. This section
   2106    only covers files encryption, not email usage, signing or the
   2107    Web-Of-Trust.
   2108    The simplest encryption is with a symmetric cipher. In this case the
   2109    file is encrypted with a password and anyone who knows the password can
   2110    decrypt it, thus the keys are not needed. Gpg adds an extention ".gpg"
   2111    to the encrypted file names.
   2112 # gpg -c file                        # Encrypt file with password
   2113 # gpg file.gpg                       # Decrypt file (optionally -o otherfile)
   2114 
   2115 Using keys
   2116 
   2117    For more details see GPG Quick
   2118    Starthttp://www.madboa.com/geek/gpg-quickstart and GPG/PGP
   2119    Basicshttp://aplawrence.com/Basics/gpg.html and the gnupg
   2120    documentationhttp://gnupg.org/documentation among others.
   2121    The private and public keys are the heart of asymmetric cryptography.
   2122    What is important to remember:
   2123      * Your public key is used by others to encrypt files that only you as
   2124        the receiver can decrypt (not even the one who encrypted the file
   2125        can decrypt it). The public key is thus meant to be distributed.
   2126      * Your private key is encrypted with your passphrase and is used to
   2127        decrypt files which were encrypted with your public key. The private
   2128        key must be kept secure. Also if the key or passphrase is lost, so
   2129        are all the files encrypted with your public key.
   2130      * The key files are called keyrings as they can contain more than one
   2131        key.
   2132 
   2133    First generate a key pair. The defaults are fine, however you will have
   2134    to enter at least your full name and email and optionally a comment. The
   2135    comment is useful to create more than one key with the same name and
   2136    email. Also you should use a "passphrase", not a simple password.
   2137 # gpg --gen-key                      # This can take a long time
   2138 
   2139    The keys are stored in ~/.gnupg/ on Unix, on Windows they are typically
   2140    stored in
   2141    C:/Documents and Settings/%USERNAME%/Application Data/gnupg/.
   2142 ~/.gnupg/pubring.gpg                 # Contains your public keys and all others i
   2143 mported
   2144 ~/.gnupg/secring.gpg                 # Can contain more than one private key
   2145 
   2146    Short reminder on most used options:
   2147      * -e encrypt data
   2148      * -d decrypt data
   2149      * -r NAME encrypt for recipient NAME (or 'Full Name' or
   2150        'email@domain')
   2151      * -a create ascii armored output of a key
   2152      * -o use as output file
   2153 
   2154    The examples use 'Your Name' and 'Alice' as the keys are referred to by
   2155    the email or full name or partial name. For example I can use 'Colin' or
   2156    'c@cb.vu' for my key [Colin Barschel (cb.vu) <c@cb.vu>].
   2157 
   2158 Encrypt for personal use only
   2159 
   2160    No need to export/import any key for this. You have both already.
   2161 # gpg -e -r 'Your Name' file                  # Encrypt with your public key
   2162 # gpg -o file -d file.gpg                     # Decrypt. Use -o or it goes to std
   2163 out
   2164 
   2165 Encrypt - Decrypt with keys
   2166 
   2167    First you need to export your public key for someone else to use it. And
   2168    you need to import the public say from Alice to encrypt a file for her.
   2169    You can either handle the keys in simple ascii files or use a public key
   2170    server.
   2171    For example Alice export her public key and you import it, you can then
   2172    encrypt a file for her. That is only Alice will be able to decrypt it.
   2173 # gpg -a -o alicekey.asc --export 'Alice'     # Alice exported her key in ascii f
   2174 ile.
   2175 # gpg --send-keys --keyserver subkeys.pgp.net KEYID   # Alice put her key on a se
   2176 rver.
   2177 # gpg --import alicekey.asc                   # You import her key into your pubr
   2178 ing.
   2179 # gpg --search-keys --keyserver subkeys.pgp.net 'Alice' # or get her key from a s
   2180 erver.
   2181 
   2182    Once the keys are imported it is very easy to encrypt or decrypt a file:
   2183 # gpg -e -r 'Alice' file                      # Encrypt the file for Alice.
   2184 # gpg -d file.gpg -o file                     # Decrypt a file encrypted by Alice
   2185  for you.
   2186 
   2187 Key administration
   2188 
   2189 # gpg --list-keys                             # list public keys and see the KEYI
   2190 DS
   2191     The KEYID follows the '/' e.g. for: pub   1024D/D12B77CE the KEYID is D12B77C
   2192 E
   2193 # gpg --gen-revoke 'Your Name'                # generate revocation certificate
   2194 # gpg --list-secret-keys                      # list private keys
   2195 # gpg --delete-keys NAME                      # delete a public key from local ke
   2196 y ring
   2197 # gpg --delete-secret-key NAME                # delete a secret key from local ke
   2198 y ring
   2199 # gpg --fingerprint KEYID                     # Show the fingerprint of the key
   2200 # gpg --edit-key KEYID                        # Edit key (e.g sign or add/del ema
   2201 il)
   2202 
   2203 Encrypt Partitions
   2204 
   2205    Linux with LUKS | Linux dm-crypt only | FreeBSD GELI | FBSD pwd only |
   2206    OS X image
   2207    There are (many) other alternative methods to encrypt disks, I only show
   2208    here the methods I know and use. Keep in mind that the security is only
   2209    good as long the OS has not been tempered with. An intruder could easily
   2210    record the password from the keyboard events. Furthermore the data is
   2211    freely accessible when the partition is attached and will not prevent an
   2212    intruder to have access to it in this state.
   2213 
   2214 Linux
   2215 
   2216    Those instructions use the Linux dm-crypt (device-mapper) facility
   2217    available on the 2.6 kernel. In this example, lets encrypt the partition
   2218    /dev/sdc1, it could be however any other partition or disk, or USB or a
   2219    file based partition created with losetup. In this case we would use
   2220    /dev/loop0. See file image partition. The device mapper uses labels to
   2221    identify a partition. We use sdc1 in this example, but it could be any
   2222    string.
   2223 
   2224 dm-crypt with LUKS
   2225 
   2226    LUKS with dm-crypt has better encryption and makes it possible to have
   2227    multiple passphrase for the same partition or to change the password
   2228    easily. To test if LUKS is available, simply type # cryptsetup --help,
   2229    if nothing about LUKS shows up, use the instructions below Without LUKS.
   2230    First create a partition if necessary: fdisk /dev/sdc.
   2231 
   2232 Create encrypted partition
   2233 
   2234 # dd if=/dev/urandom of=/dev/sdc1          # Optional. For paranoids only (takes
   2235 days)
   2236 # cryptsetup -y luksFormat /dev/sdc1       # This destroys any data on sdc1
   2237 # cryptsetup luksOpen /dev/sdc1 sdc1
   2238 # mkfs.ext3 /dev/mapper/sdc1               # create ext3 file system
   2239 # mount -t ext3 /dev/mapper/sdc1 /mnt
   2240 # umount /mnt
   2241 # cryptsetup luksClose sdc1                # Detach the encrypted partition
   2242 
   2243 Attach
   2244 
   2245 # cryptsetup luksOpen /dev/sdc1 sdc1
   2246 # mount -t ext3 /dev/mapper/sdc1 /mnt
   2247 
   2248 Detach
   2249 
   2250 # umount /mnt
   2251 # cryptsetup luksClose sdc1
   2252 
   2253 dm-crypt without LUKS
   2254 
   2255 # cryptsetup -y create sdc1 /dev/sdc1      # or any other partition like /dev/loo
   2256 p0
   2257 # dmsetup ls                               # check it, will display: sdc1 (254, 0
   2258 )
   2259 # mkfs.ext3 /dev/mapper/sdc1               # This is done only the first time!
   2260 # mount -t ext3 /dev/mapper/sdc1 /mnt
   2261 # umount /mnt/
   2262 # cryptsetup remove sdc1                   # Detach the encrypted partition
   2263 
   2264    Do exactly the same (without the mkfs part!) to re-attach the partition.
   2265    If the password is not correct, the mount command will fail. In this
   2266    case simply remove the map sdc1 (cryptsetup remove sdc1) and create it
   2267    again.
   2268 
   2269 FreeBSD
   2270 
   2271    The two popular FreeBSD disk encryption modules are gbde and geli. I now
   2272    use geli because it is faster and also uses the crypto device for
   2273    hardware acceleration. See The FreeBSD handbook Chapter
   2274    18.6http://www.freebsd.org/handbook/disks-encrypting.html for all the
   2275    details. The geli module must be loaded or compiled into the kernel:
   2276 options GEOM_ELI
   2277 device crypto                                       # or as module:
   2278 # echo 'geom_eli_load="YES"' >> /boot/loader.conf   # or do: kldload geom_eli
   2279 
   2280 Use password and key
   2281 
   2282    I use those settings for a typical disk encryption, it uses a passphrase
   2283    AND a key to encrypt the master key. That is you need both the password
   2284    and the generated key /root/ad1.key to attach the partition. The master
   2285    key is stored inside the partition and is not visible. See below for
   2286    typical USB or file based image.
   2287 
   2288 Create encrypted partition
   2289 
   2290 # dd if=/dev/random of=/root/ad1.key bs=64 count=1  # this key encrypts the mater
   2291  key
   2292 # geli init -s 4096 -K /root/ad1.key /dev/ad1       # -s 8192 is also OK for disk
   2293 s
   2294 # geli attach -k /root/ad1.key /dev/ad1             # DO make a backup of /root/a
   2295 d1.key
   2296 # dd if=/dev/random of=/dev/ad1.eli bs=1m           # Optional and takes a long t
   2297 ime
   2298 # newfs /dev/ad1.eli                                # Create file system
   2299 # mount /dev/ad1.eli /mnt
   2300 
   2301 Attach
   2302 
   2303 # geli attach -k /root/ad1.key /dev/ad1
   2304 # fsck -ny -t ffs /dev/ad1.eli                      # In doubt check the file sys
   2305 tem
   2306 # mount /dev/ad1.eli /mnt
   2307 
   2308 Detach
   2309 
   2310    The detach procedure is done automatically on shutdown.
   2311 # umount /mnt
   2312 # geli detach /dev/ad1.eli
   2313 
   2314 /etc/fstab
   2315 
   2316    The encrypted partition can be configured to be mounted with /etc/fstab.
   2317    The password will be prompted when booting. The following settings are
   2318    required for this example:
   2319 # grep geli /etc/rc.conf
   2320 geli_devices="ad1"
   2321 geli_ad1_flags="-k /root/ad1.key"
   2322 # grep geli /etc/fstab
   2323 /dev/ad1.eli         /home/private              ufs             rw      0       0
   2324 
   2325 Use password only
   2326 
   2327    It is more convenient to encrypt a USB stick or file based image with a
   2328    passphrase only and no key. In this case it is not necessary to carry
   2329    the additional key file around. The procedure is very much the same as
   2330    above, simply without the key file. Let's encrypt a file based image
   2331    /cryptedfile of 1 GB.
   2332 # dd if=/dev/zero of=/cryptedfile bs=1M count=1000  # 1 GB file
   2333 # mdconfig -at vnode -f /cryptedfile
   2334 # geli init /dev/md0                                # encrypts with password only
   2335 # geli attach /dev/md0
   2336 # newfs -U -m 0 /dev/md0.eli
   2337 # mount /dev/md0.eli /mnt
   2338 # umount /dev/md0.eli
   2339 # geli detach md0.eli
   2340 
   2341    It is now possible to mount this image on an other system with the
   2342    password only.
   2343 # mdconfig -at vnode -f /cryptedfile
   2344 # geli attach /dev/md0
   2345 # mount /dev/md0.eli /mnt
   2346 
   2347 OS X Encrypted Disk Image
   2348 
   2349    Don't know by command line only. See OS X Encrypted Disk
   2350    Imagehttps://wiki.thayer.dartmouth.edu/display/computing/Creating+a+Mac+
   2351    OS+X+Encrypted+Disk+Image and Apple
   2352    supporthttp://support.apple.com/kb/ht1578
   2353 
   2354 SSL Certificates
   2355 
   2356    So called SSL/TLS certificates are cryptographic public key certificates
   2357    and are composed of a public and a private key. The certificates are
   2358    used to authenticate the endpoints and encrypt the data. They are used
   2359    for example on a web server (https) or mail server (imaps).
   2360 
   2361 Procedure
   2362 
   2363      * We need a certificate authority to sign our certificate. This step
   2364        is usually provided by a vendor like Thawte, Verisign, etc., however
   2365        we can also create our own.
   2366      * Create a certificate signing request. This request is like an
   2367        unsigned certificate (the public part) and already contains all
   2368        necessary information. The certificate request is normally sent to
   2369        the authority vendor for signing. This step also creates the private
   2370        key on the local machine.
   2371      * Sign the certificate with the certificate authority.
   2372      * If necessary join the certificate and the key in a single file to be
   2373        used by the application (web server, mail server etc.).
   2374 
   2375 Configure OpenSSL
   2376 
   2377    We use /usr/local/certs as directory for this example check or edit
   2378    /etc/ssl/openssl.cnf accordingly to your settings so you know where the
   2379    files will be created. Here are the relevant part of openssl.cnf:
   2380 [ CA_default ]
   2381 dir             = /usr/local/certs/CA       # Where everything is kept
   2382 certs           = $dir/certs                # Where the issued certs are kept
   2383 crl_dir         = $dir/crl                  # Where the issued crl are kept
   2384 database        = $dir/index.txt            # database index file.
   2385 
   2386    Make sure the directories exist or create them
   2387 # mkdir -p /usr/local/certs/CA
   2388 # cd /usr/local/certs/CA
   2389 # mkdir certs crl newcerts private
   2390 # echo "01" > serial                        # Only if serial does not exist
   2391 # touch index.txt
   2392 
   2393    If you intend to get a signed certificate from a vendor, you only need a
   2394    certificate signing request (CSR). This CSR will then be signed by the
   2395    vendor for a limited time (e.g. 1 year).
   2396 
   2397 Create a certificate authority
   2398 
   2399    If you do not have a certificate authority from a vendor, you'll have to
   2400    create your own. This step is not necessary if one intend to use a
   2401    vendor to sign the request. To make a certificate authority (CA):
   2402 # openssl req -new -x509 -days 730 -config /etc/ssl/openssl.cnf \
   2403 -keyout CA/private/cakey.pem -out CA/cacert.pem
   2404 
   2405 Create a certificate signing request
   2406 
   2407    To make a new certificate (for mail server or web server for example),
   2408    first create a request certificate with its private key. If your
   2409    application do not support encrypted private key (for example UW-IMAP
   2410    does not), then disable encryption with -nodes.
   2411 # openssl req -new -keyout newkey.pem -out newreq.pem \
   2412 -config /etc/ssl/openssl.cnf
   2413 # openssl req -nodes -new -keyout newkey.pem -out newreq.pem \
   2414 -config /etc/ssl/openssl.cnf                # No encryption for the key
   2415 
   2416    Keep this created CSR (newreq.pem) as it can be signed again at the next
   2417    renewal, the signature onlt will limit the validity of the certificate.
   2418    This process also created the private key newkey.pem.
   2419 
   2420 Sign the certificate
   2421 
   2422    The certificate request has to be signed by the CA to be valid, this
   2423    step is usually done by the vendor. Note: replace "servername" with the
   2424    name of your server in the next commands.
   2425 # cat newreq.pem newkey.pem > new.pem
   2426 # openssl ca -policy policy_anything -out servernamecert.pem \
   2427 -config /etc/ssl/openssl.cnf -infiles new.pem
   2428 # mv newkey.pem servernamekey.pem
   2429 
   2430    Now servernamekey.pem is the private key and servernamecert.pem is the
   2431    server certificate.
   2432 
   2433 Create united certificate
   2434 
   2435    The IMAP server wants to have both private key and server certificate in
   2436    the same file. And in general, this is also easier to handle, but the
   2437    file has to be kept securely!. Apache also can deal with it well. Create
   2438    a file servername.pem containing both the certificate and key.
   2439      * Open the private key (servernamekey.pem) with a text editor and copy
   2440        the private key into the "servername.pem" file.
   2441      * Do the same with the server certificate (servernamecert.pem).
   2442 
   2443    The final servername.pem file should look like this:
   2444 -----BEGIN RSA PRIVATE KEY-----
   2445 MIICXQIBAAKBgQDutWy+o/XZ/[...]qK5LqQgT3c9dU6fcR+WuSs6aejdEDDqBRQ
   2446 -----END RSA PRIVATE KEY-----
   2447 -----BEGIN CERTIFICATE-----
   2448 MIIERzCCA7CgAwIBAgIBBDANB[...]iG9w0BAQQFADCBxTELMAkGA1UEBhMCREUx
   2449 -----END CERTIFICATE-----
   2450 
   2451    What we have now in the directory /usr/local/certs/:
   2452      * CA/private/cakey.pem (CA server private key)
   2453      * CA/cacert.pem (CA server public key)
   2454      * certs/servernamekey.pem (server private key)
   2455      * certs/servernamecert.pem (server signed certificate)
   2456      * certs/servername.pem (server certificate with private key)
   2457 
   2458    Keep the private key secure!
   2459 
   2460 View certificate information
   2461 
   2462    To view the certificate information simply do:
   2463 # openssl x509 -text -in servernamecert.pem      # View the certificate info
   2464 # openssl req -noout -text -in server.csr        # View the request info
   2465 # openssl s_client -connect cb.vu:443            # Check a web server certificate
   2466 
   2467 CVS
   2468 
   2469    Server setup | CVS test | SSH tunneling | CVS usage
   2470 
   2471 Server setup
   2472 
   2473 Initiate the CVS
   2474 
   2475    Decide where the main repository will rest and create a root cvs. For
   2476    example /usr/local/cvs (as root):
   2477 # mkdir -p /usr/local/cvs
   2478 # setenv CVSROOT /usr/local/cvs      # Set CVSROOT to the new location (local)
   2479 # cvs init                           # Creates all internal CVS config files
   2480 # cd /root
   2481 # cvs checkout CVSROOT               # Checkout the config files to modify them
   2482 # cd CVSROOT
   2483 edit config ( fine as it is)
   2484 # cvs commit config
   2485 cat >> writers                       # Create a writers file (optionally also rea
   2486 ders)
   2487 colin
   2488 ^D                                   # Use [Control][D] to quit the edit
   2489 # cvs add writers                    # Add the file writers into the repository
   2490 # cvs edit checkoutlist
   2491 # cat >> checkoutlist
   2492 writers
   2493 ^D                                   # Use [Control][D] to quit the edit
   2494 # cvs commit                         # Commit all the configuration changes
   2495 
   2496    Add a readers file if you want to differentiate read and write
   2497    permissions Note: Do not (ever) edit files directly into the main cvs,
   2498    but rather checkout the file, modify it and check it in. We did this
   2499    with the file writers to define the write access.
   2500    There are three popular ways to access the CVS at this point. The first
   2501    two don't need any further configuration. See the examples on CVSROOT
   2502    below for how to use them:
   2503      * Direct local access to the file system. The user(s) need sufficient
   2504        file permission to access the CS directly and there is no further
   2505        authentication in addition to the OS login. However this is only
   2506        useful if the repository is local.
   2507      * Remote access with ssh with the ext protocol. Any use with an ssh
   2508        shell account and read/write permissions on the CVS server can
   2509        access the CVS directly with ext over ssh without any additional
   2510        tunnel. There is no server process running on the CVS for this to
   2511        work. The ssh login does the authentication.
   2512      * Remote access with pserver (default port: 2401/tcp). This is the
   2513        preferred use for larger user base as the users are authenticated by
   2514        the CVS pserver with a dedicated password database, there is
   2515        therefore no need for local users accounts. This setup is explained
   2516        below.
   2517 
   2518 Network setup with inetd
   2519 
   2520    The CVS can be run locally only if a network access is not needed. For a
   2521    remote access, the daemon inetd can start the pserver with the following
   2522    line in /etc/inetd.conf (/etc/xinetd.d/cvs on SuSE):
   2523 cvspserver      stream  tcp  nowait  cvs  /usr/bin/cvs  cvs \
   2524 --allow-root=/usr/local/cvs pserver
   2525 
   2526    It is a good idea to block the cvs port from the Internet with the
   2527    firewall and use an ssh tunnel to access the repository remotely.
   2528 
   2529 Separate authentication
   2530 
   2531    It is possible to have cvs users which are not part of the OS (no local
   2532    users). This is actually probably wanted too from the security point of
   2533    view. Simply add a file named passwd (in the CVSROOT directory)
   2534    containing the users login and password in the crypt format. This is can
   2535    be done with the apache htpasswd tool.
   2536    Note: This passwd file is the only file which has to be edited directly
   2537    in the CVSROOT directory. Also it won't be checked out. More info with
   2538    htpasswd --help
   2539 # htpasswd -cb passwd user1 password1  # -c creates the file
   2540 # htpasswd -b passwd user2 password2
   2541 
   2542    Now add :cvs at the end of each line to tell the cvs server to change
   2543    the user to cvs (or whatever your cvs server is running under). It looks
   2544    like this:
   2545 # cat passwd
   2546 user1:xsFjhU22u8Fuo:cvs
   2547 user2:vnefJOsnnvToM:cvs
   2548 
   2549 Test it
   2550 
   2551    Test the login as normal user (for example here me)
   2552 # cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs login
   2553 Logging in to :pserver:colin@192.168.50.254:2401/usr/local/cvs
   2554 CVS password:
   2555 
   2556 
   2557 CVSROOT variable
   2558 
   2559    This is an environment variable used to specify the location of the
   2560    repository we're doing operations on. For local use, it can be just set
   2561    to the directory of the repository. For use over the network, the
   2562    transport protocol must be specified. Set the CVSROOT variable with
   2563    setenv CVSROOT string on a csh, tcsh shell, or with export
   2564    CVSROOT=string on a sh, bash shell.
   2565 # setenv CVSROOT :pserver:<username>@<host>:/cvsdirectory
   2566 For example:
   2567 # setenv CVSROOT /usr/local/cvs                               # Used locally only
   2568 # setenv CVSROOT :local:/usr/local/cvs                        # Same as above
   2569 # setenv CVSROOT :ext:user@cvsserver:/usr/local/cvs           # Direct access wit
   2570 h SSH
   2571 # setenv CVS_RSH ssh                                          # for the ext acces
   2572 s
   2573 # setenv CVSROOT :pserver:user@cvsserver.254:/usr/local/cvs   # network with pser
   2574 ver
   2575 
   2576    When the login succeeded one can import a new project into the
   2577    repository: cd into your project root directory
   2578 cvs import <module name> <vendor tag> <initial tag>
   2579 cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs import MyProject MyCompany ST
   2580 ART
   2581 
   2582    Where MyProject is the name of the new project in the repository (used
   2583    later to checkout). Cvs will import the current directory content into
   2584    the new project.
   2585    To checkout:
   2586 # cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs checkout MyProject
   2587 or
   2588 # setenv CVSROOT :pserver:colin@192.168.50.254:/usr/local/cvs
   2589 # cvs checkout MyProject
   2590 
   2591 SSH tunneling for CVS
   2592 
   2593    We need 2 shells for this. On the first shell we connect to the cvs
   2594    server with ssh and port-forward the cvs connection. On the second shell
   2595    we use the cvs normally as if it where running locally.
   2596    on shell 1:
   2597 # ssh -L2401:localhost:2401 colin@cvs_server   # Connect directly to the CVS serv
   2598 er. Or:
   2599 # ssh -L2401:cvs_server:2401 colin@gateway     # Use a gateway to reach the CVS
   2600 
   2601    on shell 2:
   2602 # setenv CVSROOT :pserver:colin@localhost:/usr/local/cvs
   2603 # cvs login
   2604 Logging in to :pserver:colin@localhost:2401/usr/local/cvs
   2605 CVS password:
   2606 # cvs checkout MyProject/src
   2607 
   2608 CVS commands and usage
   2609 
   2610 Import
   2611 
   2612    The import command is used to add a whole directory, it must be run from
   2613    within the directory to be imported. Say the directory /devel/ contains
   2614    all files and subdirectories to be imported. The directory name on the
   2615    CVS (the module) will be called "myapp".
   2616 # cvs import [options] directory-name vendor-tag release-tag
   2617 # cd /devel                          # Must be inside the project to import it
   2618 # cvs import myapp Company R1_0      # Release tag can be anything in one word
   2619 
   2620    After a while a new directory "/devel/tools/" was added and it has to be
   2621    imported too.
   2622 # cd /devel/tools
   2623 # cvs import myapp/tools Company R1_0
   2624 
   2625 Checkout update add commit
   2626 
   2627 # cvs co myapp/tools                 # Will only checkout the directory tools
   2628 # cvs co -r R1_1 myapp               # Checkout myapp at release R1_1 (is sticky)
   2629 # cvs -q -d update -P                # A typical CVS update
   2630 # cvs update -A                      # Reset any sticky tag (or date, option)
   2631 # cvs add newfile                    # Add a new file
   2632 # cvs add -kb newfile                # Add a new binary file
   2633 # cvs commit file1 file2             # Commit the two files only
   2634 # cvs commit -m "message"            # Commit all changes done with a message
   2635 
   2636 Create a patch
   2637 
   2638    It is best to create and apply a patch from the working development
   2639    directory related to the project, or from within the source directory.
   2640 # cd /devel/project
   2641 # diff -Naur olddir newdir > patchfile # Create a patch from a directory or a fil
   2642 e
   2643 # diff -Naur oldfile newfile > patchfile
   2644 
   2645 Apply a patch
   2646 
   2647    Sometimes it is necessary to strip a directory level from the patch,
   2648    depending how it was created. In case of difficulties, simply look at
   2649    the first lines of the patch and try -p0, -p1 or -p2.
   2650 # cd /devel/project
   2651 # patch --dry-run -p0 < patchfile    # Test the path without applying it
   2652 # patch -p0 < patchfile
   2653 # patch -p1 < patchfile              # strip off the 1st level from the path
   2654 
   2655 SVN
   2656 
   2657    Server setup | SVN+SSH | SVN over http | SVN usage
   2658    Subversion (SVN)http://subversion.tigris.org/ is a version control
   2659    system designed to be the successor of CVS (Concurrent Versions System).
   2660    The concept is similar to CVS, but many shortcomings where improved. See
   2661    also the SVN bookhttp://svnbook.red-bean.com/en/1.4/.
   2662 
   2663 Server setup
   2664 
   2665    The initiation of the repository is fairly simple (here for example
   2666    /home/svn/ must exist):
   2667 # svnadmin create --fs-type fsfs /home/svn/project1
   2668 
   2669    Now the access to the repository is made possible with:
   2670      * file:// Direct file system access with the svn client with. This
   2671        requires local permissions on the file system.
   2672      * svn:// or svn+ssh:// Remote access with the svnserve server (also
   2673        over SSH). This requires local permissions on the file system
   2674        (default port: 2690/tcp).
   2675      * http:// Remote access with webdav using apache. No local users are
   2676        necessary for this method.
   2677 
   2678    Using the local file system, it is now possible to import and then check
   2679    out an existing project. Unlike with CVS it is not necessary to cd into
   2680    the project directory, simply give the full path:
   2681 # svn import /project1/ file:///home/svn/project1/trunk -m 'Initial import'
   2682 # svn checkout file:///home/svn/project1
   2683 
   2684    The new directory "trunk" is only a convention, this is not required.
   2685 
   2686 Remote access with ssh
   2687 
   2688    No special setup is required to access the repository via ssh, simply
   2689    replace file:// with svn+ssh/hostname. For example:
   2690 # svn checkout svn+ssh://hostname/home/svn/project1
   2691 
   2692    As with the local file access, every user needs an ssh access to the
   2693    server (with a local account) and also read/write access. This method
   2694    might be suitable for a small group. All users could belong to a
   2695    subversion group which owns the repository, for example:
   2696 # groupadd subversion
   2697 # groupmod -A user1 subversion
   2698 # chown -R root:subversion /home/svn
   2699 # chmod -R 770 /home/svn
   2700 
   2701 Remote access with http (apache)
   2702 
   2703    Remote access over http (https) is the only good solution for a larger
   2704    user group. This method uses the apache authentication, not the local
   2705    accounts. This is a typical but small apache configuration:
   2706 LoadModule dav_module         modules/mod_dav.so
   2707 LoadModule dav_svn_module     modules/mod_dav_svn.so
   2708 LoadModule authz_svn_module   modules/mod_authz_svn.so    # Only for access contr
   2709 ol
   2710 
   2711 <Location /svn>
   2712   DAV svn
   2713   # any "/svn/foo" URL will map to a repository /home/svn/foo
   2714   SVNParentPath /home/svn
   2715   AuthType Basic
   2716   AuthName "Subversion repository"
   2717   AuthzSVNAccessFile /etc/apache2/svn.acl
   2718   AuthUserFile /etc/apache2/svn-passwd
   2719   Require valid-user
   2720 </Location>
   2721 
   2722    The apache server needs full access to the repository:
   2723 # chown -R www:www /home/svn
   2724 
   2725    Create a user with htpasswd2:
   2726 # htpasswd -c /etc/svn-passwd user1  # -c creates the file
   2727 
   2728 Access control svn.acl example
   2729 
   2730 # Default it read access. "* =" would be default no access
   2731 [/]
   2732 * = r
   2733 [groups]
   2734 project1-developers = joe, jack, jane
   2735 # Give write access to the developers
   2736 [project1:]
   2737 @project1-developers = rw
   2738 
   2739 SVN commands and usage
   2740 
   2741    See also the Subversion Quick Reference
   2742    Cardhttp://www.cs.put.poznan.pl/csobaniec/Papers/svn-refcard.pdf.
   2743    Tortoise SVNhttp://tortoisesvn.tigris.org is a nice Windows interface.
   2744 
   2745 Import
   2746 
   2747    A new project, that is a directory with some files, is imported into the
   2748    repository with the import command. Import is also used to add a
   2749    directory with its content to an existing project.
   2750 # svn help import                                # Get help for any command
   2751     # Add a new directory (with content) into the src dir on project1
   2752 # svn import /project1/newdir http://host.url/svn/project1/trunk/src -m 'add newd
   2753 ir'
   2754 
   2755 Typical SVN commands
   2756 
   2757 # svn co http://host.url/svn/project1/trunk      # Checkout the most recent versi
   2758 on
   2759     # Tags and branches are created by copying
   2760 # svn mkdir http://host.url/svn/project1/tags/   # Create the tags directory
   2761 # svn copy -m "Tag rc1 rel." http://host.url/svn/project1/trunk \
   2762                              http://host.url/svn/project1/tags/1.0rc1
   2763 # svn status [--verbose]                         # Check files status into workin
   2764 g dir
   2765 # svn add src/file.h src/file.cpp                # Add two files
   2766 # svn commit -m 'Added new class file'           # Commit the changes with a mess
   2767 age
   2768 # svn ls http://host.url/svn/project1/tags/      # List all tags
   2769 # svn move foo.c bar.c                           # Move (rename) files
   2770 # svn delete some_old_file                       # Delete files
   2771 
   2772 Useful Commands
   2773 
   2774    less | vi | mail | tar | zip | dd | screen | find | Miscellaneous
   2775 
   2776 less
   2777 
   2778    The less command displays a text document on the console. It is present
   2779    on most installation.
   2780 # less unixtoolbox.xhtml
   2781 
   2782    Some important commands are (^N stands for [control]-[N]):
   2783      * h H       good help on display
   2784      * f ^F ^V SPACE       Forward one window (or N lines).
   2785      * b ^B ESC-v       Backward one window (or N lines).
   2786      * F       Forward forever; like "tail -f".
   2787      * /pattern       Search forward for (N-th) matching line.
   2788      * ?pattern       Search backward for (N-th) matching line.
   2789      * n       Repeat previous search (for N-th occurrence).
   2790      * N       Repeat previous search in reverse direction.
   2791      * q       quit
   2792 
   2793 vi
   2794 
   2795    Vi is present on ANY Linux/Unix installation (not gentoo?) and it is
   2796    therefore useful to know some basic commands. There are two modes:
   2797    command mode and insertion mode. The commands mode is accessed with
   2798    [ESC], the insertion mode with i. Use : help if you are lost.
   2799    The editors nano and pico are usually available too and are easier
   2800    (IMHO) to use.
   2801 
   2802 Quit
   2803 
   2804      * :w newfilename       save the file to newfilename
   2805      * :wq or :x       save and quit
   2806      * :q!       quit without saving
   2807 
   2808 Search and move
   2809 
   2810      * /string       Search forward for string
   2811      * ?string       Search back for string
   2812      * n       Search for next instance of string
   2813      * N       Search for previous instance of string
   2814      * {       Move a paragraph back
   2815      * }       Move a paragraph forward
   2816      * 1G       Move to the first line of the file
   2817      * nG       Move to the n th line of the file
   2818      * G       Move to the last line of the file
   2819      * :%s/OLD/NEW/g       Search and replace every occurrence
   2820 
   2821 Delete copy paste text
   2822 
   2823      * dd (dw)       Cut current line (word)
   2824      * D       Cut to the end of the line
   2825      * x       Delete (cut) character
   2826      * yy (yw)       Copy line (word) after cursor
   2827      * P       Paste after cursor
   2828      * u       Undo last modification
   2829      * U       Undo all changes to current line
   2830 
   2831 mail
   2832 
   2833    The mail command is a basic application to read and send email, it is
   2834    usually installed. To send an email simply type "mail user@domain". The
   2835    first line is the subject, then the mail content. Terminate and send the
   2836    email with a single dot (.) in a new line. Example:
   2837 # mail c@cb.vu
   2838 Subject: Your text is full of typos
   2839 "For a moment, nothing happened. Then, after a second or so,
   2840 nothing continued to happen."
   2841 .
   2842 EOT
   2843 #
   2844 
   2845    This is also working with a pipe:
   2846 # echo "This is the mail body" | mail c@cb.vu
   2847 
   2848    This is also a simple way to test the mail server.
   2849 
   2850 tar
   2851 
   2852    The command tar (tape archive) creates and extracts archives of file and
   2853    directories. The archive .tar is uncompressed, a compressed archive has
   2854    the extension .tgz or .tar.gz (zip) or .tbz (bzip2). Do not use absolute
   2855    path when creating an archive, you probably want to unpack it somewhere
   2856    else. Some typical commands are:
   2857 
   2858 Create
   2859 
   2860 # cd /
   2861 # tar -cf home.tar home/        # archive the whole /home directory (c for create
   2862 )
   2863 # tar -czf home.tgz home/       # same with zip compression
   2864 # tar -cjf home.tbz home/       # same with bzip2 compression
   2865 
   2866    Only include one (or two) directories from a tree, but keep the relative
   2867    structure. For example archive /usr/local/etc and /usr/local/www and the
   2868    first directory in the archive should be local/.
   2869 # tar -C /usr -czf local.tgz local/etc local/www
   2870 # tar -C /usr -xzf local.tgz    # To untar the local dir into /usr
   2871 # cd /usr; tar -xzf local.tgz   # Is the same as above
   2872 
   2873 Extract
   2874 
   2875 # tar -tzf home.tgz             # look inside the archive without extracting (lis
   2876 t)
   2877 # tar -xf home.tar              # extract the archive here (x for extract)
   2878 # tar -xzf home.tgz             # same with zip compression (-xjf for bzip2 compr
   2879 ession)
   2880                                 # remove leading path gallery2 and extract into g
   2881 allery
   2882 # tar --strip-components 1 -zxvf gallery2.tgz -C gallery/
   2883 # tar -xjf home.tbz home/colin/file.txt    # Restore a single file
   2884 # tar -xOf home.tbz home/colin/file.txt    # Print file to stdout (no extraction)
   2885 
   2886 More advanced
   2887 
   2888 # tar c dir/ | gzip | ssh user@remote 'dd of=dir.tgz' # arch dir/ and store remot
   2889 ely.
   2890 # tar cvf - `find . -print` > backup.tar              # arch the current director
   2891 y.
   2892 # tar -cf - -C /etc . | tar xpf - -C /backup/etc      # Copy directories
   2893 # tar -cf - -C /etc . | ssh user@remote tar xpf - -C /backup/etc      # Remote co
   2894 py.
   2895 # tar -czf home.tgz --exclude '*.o' --exclude 'tmp/' home/
   2896 
   2897 zip/unzip
   2898 
   2899    Zip files can be easier to share with Windows.
   2900 # zip -r fileName.zip /path/to/dir                    # zip dir into file fileNam
   2901 e.zip
   2902 # unzip fileName.zip                                  # uncompress zip file
   2903 # unzip -l fileName.zip                               # list files inside archive
   2904 # unzip -c fileName.zip fileinside.txt                # print one file to stdout
   2905 (no extraction)
   2906 # unzip fileName.zip fileinside.txt                   # extract one file only
   2907 
   2908 dd
   2909 
   2910    The program dd (disk dump or destroy disk or see the meaning of dd) is
   2911    used to copy partitions and disks and for other copy tricks. Typical
   2912    usage:
   2913 # dd if=<source> of=<target> bs=<byte size> conv=<conversion>
   2914 # kill -INFO PID                                      # View dd progress (FreeBSD
   2915 , OSX)
   2916 
   2917    Important conv options:
   2918      * notrunc       do not truncate the output file, all zeros will be
   2919        written as zeros.
   2920      * noerror       continue after read errors (e.g. bad blocks)
   2921      * sync       pad every input block with Nulls to ibs-size
   2922 
   2923    The default byte size is 512 (one block). The MBR, where the partition
   2924    table is located, is on the first block, the first 63 blocks of a disk
   2925    are empty. Larger byte sizes are faster to copy but require also more
   2926    memory.
   2927 
   2928 Backup and restore
   2929 
   2930 # dd if=/dev/hda of=/dev/hdc bs=16065b                # Copy disk to disk (same s
   2931 ize)
   2932 # dd if=/dev/sda7 of=/home/root.img bs=4096 conv=notrunc,noerror # Backup /
   2933 # dd if=/home/root.img of=/dev/sda7 bs=4096 conv=notrunc,noerror # Restore /
   2934 # dd bs=1M if=/dev/ad4s3e | gzip -c > ad4s3e.gz                  # Zip the backup
   2935 # gunzip -dc ad4s3e.gz | dd of=/dev/ad0s3e bs=1M                 # Restore the zi
   2936 p
   2937 # dd bs=1M if=/dev/ad4s3e | gzip | ssh eedcoba@fry 'dd of=ad4s3e.gz' # also remot
   2938 e
   2939 # gunzip -dc ad4s3e.gz | ssh eedcoba@host 'dd of=/dev/ad0s3e bs=1M'
   2940 # dd if=/dev/ad0 of=/dev/ad2 skip=1 seek=1 bs=4k conv=noerror    # Skip MBR
   2941     # This is necessary if the destination (ad2) is smaller.
   2942 # dd if=/vm/FreeBSD-8.2-RELEASE-amd64-memstick.img of=/dev/disk1 bs=10240 conv=sy
   2943 nc
   2944     # Copy FreeBSD image to USB memory stick
   2945 
   2946 Recover
   2947 
   2948    The command dd will read every single block of the partition. In case of
   2949    problems it is better to use the option conv=sync,noerror so dd will
   2950    skip the bad block and write zeros at the destination. Accordingly it is
   2951    important to set the block size equal or smaller than the disk block
   2952    size. A 1k size seems safe, set it with bs=1k. If a disk has bad sectors
   2953    and the data should be recovered from a partition, create an image file
   2954    with dd, mount the image and copy the content to a new disk. With the
   2955    option noerror, dd will skip the bad sectors and write zeros instead,
   2956    thus only the data contained in the bad sectors will be lost.
   2957 # dd if=/dev/hda of=/dev/null bs=1m                   # Check for bad blocks
   2958 # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc | gzip | ssh \ # Send to remote
   2959 root@fry 'dd of=hda1.gz bs=1k'
   2960 # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc of=hda1.img    # Store into an
   2961 image
   2962 # mount -o loop /hda1.img /mnt                        # Mount the image
   2963 # rsync -ax /mnt/ /newdisk/                           # Copy on a new disk
   2964 # dd if=/dev/hda of=/dev/hda                          # Refresh the magnetic stat
   2965 e
   2966   # The above is useful to refresh a disk. It is perfectly safe, but must be unmo
   2967 unted.
   2968 
   2969 Delete
   2970 
   2971 # dd if=/dev/zero of=/dev/hdc                         # Delete full disk
   2972 # dd if=/dev/urandom of=/dev/hdc                      # Delete full disk better
   2973 # kill -USR1 PID                                      # View dd progress (Linux)
   2974 # kill -INFO PID                                      # View dd progress (FreeBSD
   2975 )
   2976 
   2977 MBR tricks
   2978 
   2979    The MBR contains the boot loader and the partition table and is 512
   2980    bytes small. The first 446 are for the boot loader, the bytes 446 to 512
   2981    are for the partition table.
   2982 # dd if=/dev/sda of=/mbr_sda.bak bs=512 count=1       # Backup the full MBR
   2983 # dd if=/dev/zero of=/dev/sda bs=512 count=1          # Delete MBR and partition
   2984 table
   2985 # dd if=/mbr_sda.bak of=/dev/sda bs=512 count=1       # Restore the full MBR
   2986 # dd if=/mbr_sda.bak of=/dev/sda bs=446 count=1       # Restore only the boot loa
   2987 der
   2988 # dd if=/mbr_sda.bak of=/dev/sda bs=1 count=64 skip=446 seek=446 # Restore partit
   2989 ion table
   2990 
   2991 screen
   2992 
   2993    Screen (a must have) has two main functionalities:
   2994      * Run multiple terminal session within a single terminal.
   2995      * A started program is decoupled from the real terminal and can thus
   2996        run in the background. The real terminal can be closed and
   2997        reattached later.
   2998 
   2999 Short start example
   3000 
   3001    start screen with:
   3002 # screen
   3003 
   3004    Within the screen session we can start a long lasting program (like
   3005    top).
   3006 # top
   3007 
   3008    Now detach with Ctrl-a Ctrl-d. Reattach the terminal with:
   3009 # screen -R -D
   3010 
   3011    In detail this means: If a session is running, then reattach. If
   3012    necessary detach and logout remotely first. If it was not running create
   3013    it and notify the user. Or:
   3014 # screen -x
   3015 
   3016    Attach to a running screen in a multi display mode. The console is thus
   3017    shared among multiple users. Very useful for team work/debug!
   3018 
   3019 Screen commands (within screen)
   3020 
   3021    All screen commands start with Ctrl-a.
   3022      * Ctrl-a ? help and summary of functions
   3023      * Ctrl-a c create an new window (terminal)
   3024      * Ctrl-a Ctrl-n and Ctrl-a Ctrl-p to switch to the next or previous
   3025        window in the list, by number.
   3026      * Ctrl-a Ctrl-N where N is a number from 0 to 9, to switch to the
   3027        corresponding window.
   3028      * Ctrl-a " to get a navigable list of running windows
   3029      * Ctrl-a a to clear a missed Ctrl-a
   3030      * Ctrl-a Ctrl-d to disconnect and leave the session running in the
   3031        background
   3032      * Ctrl-a x lock the screen terminal with a password
   3033      * Ctrl-a [ enter into scrollback mode, exit with esc.
   3034        Use echo "defscrollback 5000" > ~/.screenrc to increase buffer
   3035        (default is 100)
   3036 
   3037      * C-u Scrolls a half page up
   3038      * C-b Scroll a full page up
   3039      * C-d Scroll a half page down
   3040      * C-f Scroll a full page down
   3041      * / Search forward
   3042      * ? Search backward
   3043 
   3044    Configuration in ~/.screenrc:
   3045 defscrollback 100000                 # increase scrollback buffer (default is 100
   3046 )
   3047 termcapinfo xterm* ti@:te@           # avoid alternate text buffer to allow scrol
   3048 ling
   3049 
   3050    The screen session is terminated when the program within the running
   3051    terminal is closed and you logout from the terminal.
   3052 
   3053 Find
   3054 
   3055    Some important options:
   3056      * -x (on BSD) -xdev (on Linux)       Stay on the same file system (dev
   3057        in fstab).
   3058      * -exec cmd {} \;       Execute the command and replace {} with the
   3059        full path
   3060      * -iname       Like -name but is case insensitive
   3061      * -ls       Display information about the file (like ls -la)
   3062      * -size n       n is +-n (k M G T P)
   3063      * -cmin n       File's status was last changed n minutes ago.
   3064 
   3065 # find . -type f ! -perm -444        # Find files not readable by all
   3066 # find . -type d ! -perm -111        # Find dirs not accessible by all
   3067 # find /home/user/ -cmin 10 -print   # Files created or modified in the last 10 m
   3068 in.
   3069 # find . -name '*.[ch]' | xargs grep -E 'expr' # Search 'expr' in this dir and be
   3070 low.
   3071 # find / -name "*.core" | xargs rm   # Find core dumps and delete them (also try
   3072 core.*)
   3073 # find / -name "*.core" -print -exec rm {} \;  # Other syntax
   3074       # Find images and create an archive, iname is not case sensitive. -r for ap
   3075 pend
   3076 # find . \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar {
   3077 } \;
   3078 # find . -type f -name "*.txt" ! -name README.txt -print  # Exclude README.txt fi
   3079 les
   3080 # find /var/ -size +10M -exec ls -lh {} \;     # Find large files > 10 MB
   3081 # find /var/ -size +10M -ls           # This is simpler
   3082 # find . -size +10M -size -50M -print
   3083 # find /usr/ports/ -name work -type d -print -exec rm -rf {} \;  # Clean the port
   3084 s
   3085       # Find files with SUID; those file are vulnerable and must be kept secure
   3086 # find / -type f -user root -perm -4000 -exec ls -l {} \;
   3087 # find flac/ -iname *.flac -print -size +500k -exec /Applications/Fluke.app/Conte
   3088 nts/MacOS/Fluke {} \;
   3089                                       # I use above to add flac files to iTunes o
   3090 n OSX
   3091 
   3092    Be careful with xarg or exec as it might or might not honor quotings and
   3093    can return wrong results when files or directories contain spaces. In
   3094    doubt use "-print0 | xargs -0" instead of "| xargs". The option -print0
   3095    must be the last in the find command. See this nice mini tutorial for
   3096    findhttp://www.hccfl.edu/pollock/Unix/FindCmd.htm.
   3097 # find . -type f | xargs ls -l       # Will not work with spaces in names
   3098 # find . -type f -print0 | xargs -0 ls -l  # Will work with spaces in names
   3099 # find . -type f -exec ls -l '{}' \; # Or use quotes '{}' with -exec
   3100 
   3101    Duplicate directory tree:
   3102 # find . -type d -exec mkdir -p /tmp/new_dest/{} \;
   3103 
   3104 Miscellaneous
   3105 
   3106 # which command                      # Show full path name of command
   3107 # time command                       # See how long a command takes to execute
   3108 # time cat                           # Use time as stopwatch. Ctrl-c to stop
   3109 # set | grep $USER                   # List the current environment
   3110 # cal -3                             # Display a three month calendar
   3111 # date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
   3112 # date 10022155                      # Set date and time
   3113 # whatis grep                        # Display a short info on the command or wor
   3114 d
   3115 # whereis java                       # Search path and standard directories for w
   3116 ord
   3117 # setenv varname value               # Set env. variable varname to value (csh/tc
   3118 sh)
   3119 # export varname="value"             # set env. variable varname to value (sh/ksh
   3120 /bash)
   3121 # pwd                                # Print working directory
   3122 # mkdir -p /path/to/dir              # no error if existing, make parent dirs as
   3123 needed
   3124 # mkdir -p project/{bin,src,obj,doc/{html,man,pdf},debug/some/more/dirs}
   3125 # rmdir /path/to/dir                 # Remove directory
   3126 # rm -rf /path/to/dir                # Remove directory and its content (force)
   3127 # rm -- -badchar.txt                 # Remove file whitch starts with a dash (-)
   3128 # cp -la /dir1 /dir2                 # Archive and hard link files instead of cop
   3129 y
   3130 # cp -lpR /dir1 /dir2                # Same for FreeBSD
   3131 # cp unixtoolbox.xhtml{,.bak}        # Short way to copy the file with a new exte
   3132 nsion
   3133 # mv /dir1 /dir2                     # Rename a directory
   3134 # ls -1                              # list one file per line
   3135 # history | tail -50                 # Display the last 50 used commands
   3136 # cd -                               # cd to previous ($OLDPWD) directory
   3137 # /bin/ls| grep -v .py | xargs rm -r # pipe file names to rm with xargs
   3138 
   3139    Check file hashes with openssl. This is a nice alternative to the
   3140    commands md5sum or sha1sum (FreeBSD uses md5 and sha1) which are not
   3141    always installed.
   3142 # openssl md5 file.tar.gz            # Generate an md5 checksum from file
   3143 # openssl sha1 file.tar.gz           # Generate an sha1 checksum from file
   3144 # openssl rmd160 file.tar.gz         # Generate a RIPEMD-160 checksum from file
   3145 
   3146 Install Software
   3147 
   3148    Usually the package manager uses the proxy variable for http/ftp
   3149    requests. In .bashrc:
   3150 export http_proxy=http://proxy_server:3128
   3151 export ftp_proxy=http://proxy_server:3128
   3152 
   3153 List installed packages
   3154 
   3155 # rpm -qa                            # List installed packages (RH, SuSE, RPM bas
   3156 ed)
   3157 # dpkg -l                            # Debian, Ubuntu
   3158 # pkg_info                           # FreeBSD list all installed packages
   3159 # pkg_info -W smbd                   # FreeBSD show which package smbd belongs to
   3160 # pkginfo                            # Solaris
   3161 
   3162    More on RPM:
   3163 # rpm -ql package-name               # list the files for INSTALLED package
   3164 # rpm -qlp package.rpm               # list the files inside package
   3165 
   3166 Add/remove software
   3167 
   3168    Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat.
   3169 # rpm -i pkgname.rpm                 # install the package (RH, SuSE, RPM based)
   3170 # rpm -e pkgname                     # Remove package
   3171 
   3172 SuSE zypper (see doc and cheet sheet)http://en.opensuse.org/SDB:Zypper_usage
   3173 
   3174 # zypper refresh                     # Refresh repositorie
   3175 # zypper install vim                 # Install the package vim
   3176 # zypper remove vim                  # Remove the package vim
   3177 # zypper search vim                  # Search packages with vim
   3178 # zypper update vim                  # Search packages with vim
   3179 
   3180 Debian
   3181 
   3182 # apt-get update                     # First update the package lists
   3183 # apt-get install emacs              # Install the package emacs
   3184 # dpkg --remove emacs                # Remove the package emacs
   3185 # dpkg -S file                       # find what package a file belongs to
   3186 
   3187 Gentoo
   3188 
   3189    Gentoo uses emerge as the heart of its "Portage" package management
   3190    system.
   3191 # emerge --sync                      # First sync the local portage tree
   3192 # emerge -u packagename              # Install or upgrade a package
   3193 # emerge -C packagename              # Remove the package
   3194 # revdep-rebuild                     # Repair dependencies
   3195 
   3196 Solaris
   3197 
   3198    The <cdrom> path is usually /cdrom/cdrom0.
   3199 # pkgadd -d <cdrom>/Solaris_9/Product SUNWgtar
   3200 # pkgadd -d SUNWgtar                 # Add downloaded package (bunzip2 first)
   3201 # pkgrm SUNWgtar                     # Remove the package
   3202 
   3203 FreeBSD
   3204 
   3205 # pkg_add -r rsync                   # Fetch and install rsync.
   3206 # pkg_delete /var/db/pkg/rsync-xx    # Delete the rsync package
   3207 
   3208    Set where the packages are fetched from with the PACKAGESITE variable.
   3209    For example:
   3210 # export PACKAGESITE=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages/Latest
   3211 /
   3212 # or ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-6-stable/Latest/
   3213 
   3214 FreeBSD portshttp://www.freebsd.org/handbook/ports.html
   3215 
   3216    The port tree /usr/ports/ is a collection of software ready to compile
   3217    and install (see man ports). The ports are updated with the program
   3218    portsnap.
   3219 # portsnap fetch extract             # Create the tree when running the first tim
   3220 e
   3221 # portsnap fetch update              # Update the port tree
   3222 # cd /usr/ports/net/rsync/           # Select the package to install
   3223 # make install distclean             # Install and cleanup (also see man ports)
   3224 # make package                       # Make a binary package of this port
   3225 # pkgdb -F                           # Fix the package registry database
   3226 # portsclean -C -DD                  # Clean workdir and distdir (part of portupg
   3227 rade)
   3228 
   3229 OS X MacPortshttp://guide.macports.org/ (use sudo for all commands)
   3230 
   3231 # port selfupdate                    # Update the port tree (safe)
   3232 # port installed                     # List installed ports
   3233 # port deps apache2                  # List dependencies for this port
   3234 # port search pgrep                  # Search for string
   3235 # port install proctools             # Install this package
   3236 # port variants ghostscript          # List variants of this port
   3237 # port -v install ghostscript +no_x11# -no_x11 for negative value
   3238 # port clean --all ghostscript       # Clean workdir of port
   3239 # port upgrade ghostscript           # Upgrade this port
   3240 # port uninstall ghostscript         # Uninstall this port
   3241 # port -f uninstall installed        # Uninstall everything
   3242 
   3243 Library path
   3244 
   3245    Due to complex dependencies and runtime linking, programs are difficult
   3246    to copy to an other system or distribution. However for small programs
   3247    with little dependencies, the missing libraries can be copied over. The
   3248    runtime libraries (and the missing one) are checked with ldd and managed
   3249    with ldconfig.
   3250 # ldd /usr/bin/rsync                 # List all needed runtime libraries
   3251 # otool -L /usr/bin/rsync            # OS X equivalent to ldd
   3252 # ldconfig -n /path/to/libs/         # Add a path to the shared libraries directo
   3253 ries
   3254 # ldconfig -m /path/to/libs/         # FreeBSD
   3255 # LD_LIBRARY_PATH                    # The variable set the link library path
   3256 
   3257 Convert Media
   3258 
   3259    Sometimes one simply need to convert a video, audio file or document to
   3260    another format.
   3261 
   3262 Text encoding
   3263 
   3264    Text encoding can get totally wrong, specially when the language
   3265    requires special characters like àäç. The command iconv can convert from
   3266    one encoding to an other.
   3267 # iconv -f <from_encoding> -t <to_encoding> <input_file>
   3268 # iconv -f ISO8859-1 -t UTF-8 -o file.input > file_utf8
   3269 # iconv -l                           # List known coded character sets
   3270 
   3271    Without the -f option, iconv will use the local char-set, which is
   3272    usually fine if the document displays well.
   3273    Convert filenames from one encoding to another (not file content). Works
   3274    also if only some files are already utf8
   3275 # convmv -r -f utf8 --nfd -t utf8 --nfc /dir/* --notest
   3276 
   3277 Unix - DOS newlines
   3278 
   3279    Convert DOS (CR/LF) to Unix (LF) newlines and back within a Unix shell.
   3280    See also dos2unix and unix2dos if you have them.
   3281 # sed 's/.$//' dosfile.txt > unixfile.txt                  # DOS to UNIX
   3282 # awk '{sub(/\r$/,"");print}' dosfile.txt > unixfile.txt   # DOS to UNIX
   3283 # awk '{sub(/$/,"\r");print}' unixfile.txt > dosfile.txt   # UNIX to DOS
   3284 
   3285    Convert Unix to DOS newlines within a Windows environment. Use sed or
   3286    awk from mingw or cygwin.
   3287 # sed -n p unixfile.txt > dosfile.txt
   3288 # awk 1 unixfile.txt > dosfile.txt   # UNIX to DOS (with a cygwin shell)
   3289 
   3290    Remove ^M mac newline and replace with unix new line. To get a ^M use
   3291    CTL-V then CTL-M
   3292 # tr '^M' '\n' < macfile.txt
   3293 
   3294 PDF images and concatenate PDF files
   3295 
   3296    Convert a PDF document with gs (GhostScript) to jpeg (or png) images for
   3297    each page. Also much shorter with convert and mogrify (from ImageMagick
   3298    or GraphicsMagick).
   3299 # gs -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=
   3300 4 \
   3301  -dMaxStripSize=8192 -sOutputFile=unixtoolbox_%d.jpg unixtoolbox.pdf
   3302 # convert unixtoolbox.pdf unixtoolbox-%03d.png
   3303 # convert *.jpeg images.pdf          # Create a simple PDF with all pictures
   3304 # convert image000* -resample 120x120 -compress JPEG -quality 80 images.pdf
   3305 # mogrify -format png *.ppm          # convert all ppm images to png format
   3306 
   3307    Ghostscript can also concatenate multiple pdf files into a single one.
   3308    This only works well if the PDF files are "well behaved".
   3309 # gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=all.pdf \
   3310 file1.pdf file2.pdf ...              # On Windows use '#' instead of '='
   3311 
   3312    Create PDF file from images
   3313 # convert 20140416-DSCF1915.jpg 20140416-DSCF1920.jpg all.pdf
   3314 convert 20140416-DSCF1915.jpg 20140416-DSCF1920.jpg -resize 1240x1753 -units Pixe
   3315 lsPerInch \
   3316 -density 150x150 all.pdf             # force A4
   3317 
   3318    Extract images from pdf document using pdfimages from poppler or
   3319    xpdfhttp://foolabs.com/xpdf/download.html
   3320 # pdfimages document.pdf dst/        # extract all images and put in dst
   3321 # yum install poppler-utils          # install poppler-utils if needed. or:
   3322 # apt-get install poppler-utils
   3323 
   3324 Convert video
   3325 
   3326    Compress the Canon digicam video with an mpeg4 codec and repair the
   3327    crappy sound.
   3328 # mencoder -o videoout.avi -oac mp3lame -ovc lavc -srate 11025 \
   3329 -channels 1 -af-adv force=1 -lameopts preset=medium -lavcopts \
   3330 vcodec=msmpeg4v2:vbitrate=600 -mc 0 vidoein.AVI
   3331 
   3332    See sox for sound processing.
   3333 
   3334 Copy an audio cd
   3335 
   3336    The program cdparanoiahttp://xiph.org/paranoia/ can save the audio
   3337    tracks (FreeBSD port in audio/cdparanoia/), oggenc can encode in Ogg
   3338    Vorbis format, lame converts to mp3.
   3339 # cdparanoia -B                      # Copy the tracks to wav files in current di
   3340 r
   3341 # lame -b 256 in.wav out.mp3         # Encode in mp3 256 kb/s
   3342 # for i in *.wav; do lame -b 256 $i `basename $i .wav`.mp3; done
   3343 # oggenc in.wav -b 256 out.ogg       # Encode in Ogg Vorbis 256 kb/s
   3344 
   3345 Printing
   3346 
   3347 Print with lpr
   3348 
   3349 # lpr unixtoolbox.ps                 # Print on default printer
   3350 # export PRINTER=hp4600              # Change the default printer
   3351 # lpr -Php4500 #2 unixtoolbox.ps     # Use printer hp4500 and print 2 copies
   3352 # lpr -o Duplex=DuplexNoTumble ...   # Print duplex along the long side
   3353 # lpr -o PageSize=A4,Duplex=DuplexNoTumble ...
   3354 
   3355 # lpq                                # Check the queue on default printer
   3356 # lpq -l -Php4500                    # Queue on printer hp4500 with verbose
   3357 # lprm -                             # Remove all users jobs on default printer
   3358 # lprm -Php4500 3186                 # Remove job 3186. Find job nbr with lpq
   3359 # lpc status                         # List all available printers
   3360 # lpc status hp4500                  # Check if printer is online and queue lengt
   3361 h
   3362 
   3363    Some devices are not postscript and will print garbage when fed with a
   3364    pdf file. This might be solved with:
   3365 # gs -dSAFER -dNOPAUSE -sDEVICE=deskjet -sOutputFile=\|lpr file.pdf
   3366 
   3367    Print to a PDF file even if the application does not support it. Use gs
   3368    on the print command instead of lpr.
   3369 # gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=/path/fil
   3370 e.pdf
   3371 
   3372 Databases
   3373 
   3374 PostgreSQL
   3375 
   3376 Change root or a username password
   3377 
   3378 # psql -d template1 -U pgsql
   3379 > alter user pgsql with password 'pgsql_password';  # Use username instead of "pg
   3380 sql"
   3381 
   3382 Create user and database
   3383 
   3384    The commands createuser, dropuser, createdb and dropdb are convenient
   3385    shortcuts equivalent to the SQL commands. The new user is bob with
   3386    database bobdb ; use as root with pgsql the database super user:
   3387 # createuser -U pgsql -P bob         # -P will ask for password
   3388 # createdb -U pgsql -O bob bobdb     # new bobdb is owned by bob
   3389 # dropdb bobdb                       # Delete database bobdb
   3390 # dropuser bob                       # Delete user bob
   3391 
   3392    The general database authentication mechanism is configured in
   3393    pg_hba.conf
   3394 
   3395 Grant remote access
   3396 
   3397    The file $PGSQL_DATA_D/postgresql.conf specifies the address to bind to.
   3398    Typically listen_addresses = '*' for Postgres 8.x.
   3399    The file $PGSQL_DATA_D/pg_hba.conf defines the access control. Examples:
   3400 # TYPE  DATABASE    USER        IP-ADDRESS        IP-MASK          METHOD
   3401 host    bobdb       bob        212.117.81.42     255.255.255.255   password
   3402 host    all         all        0.0.0.0/0                           password
   3403 
   3404 Backup and restore
   3405 
   3406    The backups and restore are done with the user pgsql or postgres. Backup
   3407    and restore a single database:
   3408 # pg_dump --clean dbname > dbname_sql.dump
   3409 # psql dbname < dbname_sql.dump
   3410 
   3411    Backup and restore all databases (including users):
   3412 # pg_dumpall --clean > full.dump
   3413 # psql -f full.dump postgres
   3414 
   3415    In this case the restore is started with the database postgres which is
   3416    better when reloading an empty cluster.
   3417 
   3418 MySQL
   3419 
   3420 Change mysql root or username password
   3421 
   3422 Method 1
   3423 
   3424 # /etc/init.d/mysql stop
   3425 or
   3426 # killall mysqld
   3427 # mysqld --skip-grant-tables
   3428 # mysqladmin -u root password 'newpasswd'
   3429 # /etc/init.d/mysql start
   3430 
   3431 Method 2
   3432 
   3433 # mysql -u root mysql
   3434 mysql> UPDATE USER SET PASSWORD=PASSWORD("newpassword") where user='root';
   3435 mysql> FLUSH PRIVILEGES;                           # Use username instead of "roo
   3436 t"
   3437 mysql> quit
   3438 
   3439 Create user and database (see MySQL
   3440 dochttp://dev.mysql.com/doc/refman/5.1/en/adding-users.html)
   3441 
   3442 # mysql -u root mysql
   3443 mysql> CREATE USER 'bob'@'localhost' IDENTIFIED BY 'pwd'; # create only a user
   3444 mysql> CREATE DATABASE bobdb;
   3445 mysql> GRANT ALL ON *.* TO 'bob'@'%' IDENTIFIED BY 'pwd'; # Use localhost instead
   3446  of %
   3447                                                    # to restrict the network acce
   3448 ss
   3449 mysql> DROP DATABASE bobdb;                        # Delete database
   3450 mysql> DROP USER bob;                              # Delete user
   3451 mysql> DELETE FROM mysql.user WHERE user='bob and host='hostname'; # Alt. command
   3452 mysql> FLUSH PRIVILEGES;
   3453 
   3454 Grant remote access
   3455 
   3456    Remote access is typically permitted for a database, and not all
   3457    databases. The file /etc/my.cnf contains the IP address to bind to. (On
   3458    FreeBSD my.cnf not created per fedault, copy one .cnf file from
   3459    /usr/local/share/mysql to /usr/local/etc/my.cnf) Typically comment the
   3460    line bind-address = out.
   3461 # mysql -u root mysql
   3462 mysql> GRANT ALL ON bobdb.* TO bob@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
   3463 mysql> REVOKE GRANT OPTION ON foo.* FROM bar@'xxx.xxx.xxx.xxx';
   3464 mysql> FLUSH PRIVILEGES;                  # Use 'hostname' or also '%' for full a
   3465 ccess
   3466 
   3467 Backup and restore
   3468 
   3469    Backup and restore a single database:
   3470 # mysqldump -u root -psecret --add-drop-database dbname > dbname_sql.dump
   3471 # mysql -u root -psecret -D dbname < dbname_sql.dump
   3472 
   3473    Backup and restore all databases:
   3474 # mysqldump -u root -psecret --add-drop-database --all-databases > full.dump
   3475 # mysql -u root -psecret < full.dump
   3476 
   3477    Here is "secret" the mysql root password, there is no space after -p.
   3478    When the -p option is used alone (w/o password), the password is asked
   3479    at the command prompt.
   3480 
   3481 SQLite
   3482 
   3483    SQLitehttp://www.sqlite.org is a small powerful self-contained,
   3484    serverless, zero-configuration SQL database.
   3485 
   3486 Dump and restore
   3487 
   3488    It can be useful to dump and restore an SQLite database. For example you
   3489    can edit the dump file to change a column attribute or type and then
   3490    restore the database. This is easier than messing with SQL commands. Use
   3491    the command sqlite3 for a 3.x database.
   3492 # sqlite database.db .dump > dump.sql              # dump
   3493 # sqlite database.db < dump.sql                    # restore
   3494 
   3495 Convert 2.x to 3.x database
   3496 
   3497 sqlite database_v2.db .dump | sqlite3 database_v3.db
   3498 
   3499 Disk Quota
   3500 
   3501    A disk quota allows to limit the amount of disk space and/or the number
   3502    of files a user or (or member of group) can use. The quotas are
   3503    allocated on a per-file system basis and are enforced by the kernel.
   3504 
   3505 Linux setup
   3506 
   3507    The quota tools package usually needs to be installed, it contains the
   3508    command line tools.
   3509    Activate the user quota in the fstab and remount the partition. If the
   3510    partition is busy, either all locked files must be closed, or the system
   3511    must be rebooted. Add usrquota to the fstab mount options, for example:
   3512 /dev/sda2     /home    reiserfs     rw,acl,user_xattr,usrquota 1 1
   3513 # mount -o remount /home
   3514 # mount                              # Check if usrquota is active, otherwise reb
   3515 oot
   3516 
   3517    Initialize the quota.user file with quotacheck.
   3518 # quotacheck -vum /home
   3519 # chmod 644 /home/aquota.user        # To let the users check their own quota
   3520 
   3521    Activate the quota either with the provided script (e.g.
   3522    /etc/init.d/quotad on SuSE) or with quotaon:
   3523 quotaon -vu /home
   3524 
   3525    Check that the quota is active with:
   3526 quota -v
   3527 
   3528 FreeBSD setup
   3529 
   3530    The quota tools are part of the base system, however the kernel needs
   3531    the option quota. If it is not there, add it and recompile the kernel.
   3532 options QUOTA
   3533 
   3534    As with Linux, add the quota to the fstab options (userquota, not
   3535    usrquota):
   3536 /dev/ad0s1d    /home    ufs     rw,noatime,userquota    2  2
   3537 # mount /home                        # To remount the partition
   3538 
   3539    Enable disk quotas in /etc/rc.conf and start the quota.
   3540 # grep quotas /etc/rc.conf
   3541 enable_quotas="YES"                  # turn on quotas on startup (or NO).
   3542 check_quotas="YES"                   # Check quotas on startup (or NO).
   3543 # /etc/rc.d/quota start
   3544 
   3545 Assign quota limits
   3546 
   3547    The quotas are not limited per default (set to 0). The limits are set
   3548    with edquota for single users. A quota can be also duplicated to many
   3549    users. The file structure is different between the quota
   3550    implementations, but the principle is the same: the values of blocks and
   3551    inodes can be limited. Only change the values of soft and hard. If not
   3552    specified, the blocks are 1k. The grace period is set with edquota -t.
   3553    For example:
   3554 # edquota -u colin
   3555 
   3556 Linux
   3557 
   3558 Disk quotas for user colin (uid 1007):
   3559   Filesystem         blocks       soft       hard     inodes     soft     hard
   3560   /dev/sda8            108       1000       2000          1        0        0
   3561 
   3562 FreeBSD
   3563 
   3564 Quotas for user colin:
   3565 /home: kbytes in use: 504184, limits (soft = 700000, hard = 800000)
   3566    inodes in use: 1792, limits (soft = 0, hard = 0)
   3567 
   3568 For many users
   3569 
   3570    The command edquota -p is used to duplicate a quota to other users. For
   3571    example to duplicate a reference quota to all users:
   3572 # edquota -p refuser `awk -F: '$3 > 499 {print $1}' /etc/passwd`
   3573 # edquota -p refuser user1 user2     # Duplicate to 2 users
   3574 
   3575 Checks
   3576 
   3577    Users can check their quota by simply typing quota (the file quota.user
   3578    must be readable). Root can check all quotas.
   3579 # quota -u colin                     # Check quota for a user
   3580 # repquota /home                     # Full report for the partition for all user
   3581 s
   3582 
   3583 Shells
   3584 
   3585    Most Linux distributions use the bash shell while the BSDs use tcsh, the
   3586    bourne shell is only used for scripts. Filters are very useful and can
   3587    be piped:
   3588      * grep   Pattern matching
   3589      * sed   Search and Replace strings or characters
   3590      * cut   Print specific columns from a marker
   3591      * sort   Sort alphabetically or numerically
   3592      * uniq   Remove duplicate lines from a file
   3593 
   3594    For example used all at once:
   3595 # ifconfig | sed 's/  / /g' | cut -d" " -f1 | uniq | grep -E "[a-z0-9]+" | sort -
   3596 r
   3597 # ifconfig | sed '/.*inet addr:/!d;s///;s/ .*//'|sort -t. -k1,1n -k2,2n -k3,3n -k
   3598 4,4n
   3599 
   3600    The first character in the sed pattern is a tab. To write a tab on the
   3601    console, use ctrl-v ctrl-tab.
   3602 
   3603 bash
   3604 
   3605    Redirects and pipes for bash and sh:
   3606 # cmd 1> file                         # Redirect stdout to file.
   3607 # cmd 2> file                         # Redirect stderr to file.
   3608 # cmd 1>> file                        # Redirect and append stdout to file.
   3609 # cmd &> file                         # Redirect both stdout and stderr to file.
   3610 # cmd >file 2>&1                      # Redirects stderr to stdout and then to fi
   3611 le.
   3612 # cmd1 | cmd2                         # pipe stdout to cmd2
   3613 # cmd1 2>&1 | cmd2                    # pipe stdout and stderr to cmd2
   3614 
   3615    Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile).
   3616    The following entries are useful, reload with ". .bashrc". With cygwin
   3617    use ~/.bash_profile; with rxvt past with shift + left-click.
   3618 # in .bashrc
   3619 bind '"\e[A"':history-search-backward # Use up and down arrow to search
   3620 bind '"\e[B"':history-search-forward  # the history. Invaluable!
   3621 set -o emacs                          # Set emacs mode in bash (see below)
   3622 set bell-style visible                # Do not beep, inverse colors
   3623     # Set a nice prompt like [user@host]/path/todir>
   3624 PS1="\[\033[1;30m\][\[\033[1;34m\]\u\[\033[1;30m\]"
   3625 PS1="$PS1@\[\033[0;33m\]\h\[\033[1;30m\]]\[\033[0;37m\]"
   3626 PS1="$PS1\w\[\033[1;30m\]>\[\033[0m\]"
   3627 
   3628 # To check the currently active aliases, simply type alias
   3629 alias  ls='ls -aF'                    # Append indicator (one of */=>@|)
   3630 alias  ll='ls -aFls'                  # Listing
   3631 alias  la='ls -all'
   3632 alias ..='cd ..'
   3633 alias ...='cd ../..'
   3634 export HISTFILESIZE=5000              # Larger history
   3635 export CLICOLOR=1                     # Use colors (if possible)
   3636 export LSCOLORS=ExGxFxdxCxDxDxBxBxExEx
   3637 
   3638 tcsh
   3639 
   3640    Redirects and pipes for tcsh and csh (simple > and >> are the same as
   3641    sh):
   3642 # cmd >& file                         # Redirect both stdout and stderr to file.
   3643 # cmd >>& file                        # Append both stdout and stderr to file.
   3644 # cmd1 | cmd2                         # pipe stdout to cmd2
   3645 # cmd1 |& cmd2                        # pipe stdout and stderr to cmd2
   3646 
   3647    The settings for csh/tcsh are set in ~/.cshrc, reload with "source
   3648    .cshrc". Examples:
   3649 # in .cshrc
   3650 alias  ls      'ls -aF'
   3651 alias  ll      'ls -aFls'
   3652 alias  la      'ls -all'
   3653 alias  ..      'cd ..'
   3654 alias  ...     'cd ../..'
   3655 set   prompt    = "%B%n%b@%B%m%b%/> " # like user@host/path/todir>
   3656 set   history   =  5000
   3657 set   savehist  = ( 6000 merge )
   3658 set   autolist                        # Report possible completions with tab
   3659 set   visiblebell                     # Do not beep, inverse colors
   3660 
   3661 # Bindkey and colors
   3662 bindkey -e     Select Emacs bindings  # Use emacs keys to edit the command prompt
   3663 bindkey -k up history-search-backward # Use up and down arrow to search
   3664 bindkey -k down history-search-forward
   3665 setenv CLICOLOR 1                     # Use colors (if possible)
   3666 setenv LSCOLORS ExGxFxdxCxDxDxBxBxExEx
   3667 
   3668    The emacs mode enables to use the emacs keys shortcuts to modify the
   3669    command prompt line. This is extremely useful (not only for emacs
   3670    users). The most used commands are:
   3671      * C-a       Move cursor to beginning of line
   3672      * C-e       Move cursor to end of line
   3673      * M-b       Move cursor back one word
   3674      * M-f       Move cursor forward one word
   3675      * M-d       Cut the next word
   3676      * C-w       Cut the last word
   3677      * C-u       Cut everything before the cursor
   3678      * C-k       Cut everything after the cursor (rest of the line)
   3679      * C-y       Paste the last thing to be cut (simply paste)
   3680      * C-_       Undo
   3681 
   3682    Note: C- = hold control, M- = hold meta (which is usually the alt or
   3683    escape key).
   3684 
   3685 Scripting
   3686 
   3687    Basics | Script example | awk | sed | Regular Expressions | useful
   3688    commands
   3689    The Bourne shell (/bin/sh) is present on all Unix installations and
   3690    scripts written in this language are (quite) portable; man 1 sh is a
   3691    good reference.
   3692 
   3693 Basics
   3694 
   3695 Variables and arguments
   3696 
   3697    Assign with variable=value and get content with $variable
   3698 MESSAGE="Hello World"                        # Assign a string
   3699 PI=3.1415                                    # Assign a decimal number
   3700 N=8
   3701 TWON=`expr $N * 2`                           # Arithmetic expression (only intege
   3702 rs)
   3703 TWON=$(($N * 2))                             # Other syntax
   3704 TWOPI=`echo "$PI * 2" | bc -l`               # Use bc for floating point operatio
   3705 ns
   3706 ZERO=`echo "c($PI/4)-sqrt(2)/2" | bc -l`
   3707 
   3708    The command line arguments are
   3709 $0, $1, $2, ...                              # $0 is the command itself
   3710 $#                                           # The number of arguments
   3711 $*                                           # All arguments (also $@)
   3712 
   3713 Special Variables
   3714 
   3715 $$                                           # The current process ID
   3716 $?                                           # exit status of last command
   3717   command
   3718   if [ $? != 0 ]; then
   3719     echo "command failed"
   3720   fi
   3721 mypath=`pwd`
   3722 mypath=${mypath}/file.txt
   3723 echo ${mypath##*/}                           # Display the filename only
   3724 echo ${mypath%%.*}                           # Full path without extention
   3725 foo=/tmp/my.dir/filename.tar.gz
   3726 path = ${foo%/*}                             # Full path without extention
   3727 var2=${var:=string}                          # Use var if set, otherwise use stri
   3728 ng
   3729                                              # assign string to var and then to v
   3730 ar2.
   3731 size=$(stat -c%s "$file")                    # get file size in bourne script
   3732 filesize=${size:=-1}
   3733 
   3734 Constructs
   3735 
   3736 for file in `ls`
   3737 do
   3738     echo $file
   3739 done
   3740 
   3741 count=0
   3742 while [ $count -lt 5 ]; do
   3743     echo $count
   3744     sleep 1
   3745     count=$(($count + 1))
   3746 done
   3747 
   3748 myfunction() {
   3749     find . -type f -name "*.$1" -print       # $1 is first argument of the functi
   3750 on
   3751 }
   3752 myfunction "txt"
   3753 
   3754 Generate a file
   3755 
   3756 MYHOME=/home/colin
   3757 cat > testhome.sh << _EOF
   3758 # All of this goes into the file testhome.sh
   3759 if [ -d "$MYHOME" ] ; then
   3760     echo $MYHOME exists
   3761 else
   3762     echo $MYHOME does not exist
   3763 fi
   3764 _EOF
   3765 sh testhome.sh
   3766 
   3767 Bourne script example
   3768 
   3769    As a small example, the script used to create a PDF booklet from this
   3770    xhtml document:
   3771 #!/bin/sh
   3772 # This script creates a book in pdf format ready to print on a duplex printer
   3773 if [ $# -ne 1 ]; then                        # Check the argument
   3774   echo 1>&2 "Usage: $0 HtmlFile"
   3775   exit 1                                     # non zero exit if error
   3776 fi
   3777 
   3778 file=$1                                      # Assign the filename
   3779 fname=${file%.*}                             # Get the name of the file only
   3780 fext=${file#*.}                              # Get the extension of the file
   3781 
   3782 prince $file -o $fname.pdf                   # from www.princexml.com
   3783 pdftops -paper A4 -noshrink $fname.pdf $fname.ps # create postscript booklet
   3784 cat $fname.ps |psbook|psnup -Pa4 -2 |pstops -b "2:0,1U(21cm,29.7cm)" > $fname.boo
   3785 k.ps
   3786 
   3787 ps2pdf13 -sPAPERSIZE=a4 -sAutoRotatePages=None $fname.book.ps $fname.book.pdf
   3788                                              # use #a4 and #None on Windows!
   3789 exit 0                                       # exit 0 means successful
   3790 
   3791 Some awk commands
   3792 
   3793    Awk is useful for field stripping, like cut in a more powerful way.
   3794    Search this document for other examples. See for example gnulamp.com and
   3795    one-liners for awk for some nice examples.
   3796 awk '{ print $2, $1 }' file                  # Print and inverse first two column
   3797 s
   3798 awk '{printf("%5d : %s\n", NR,$0)}' file     # Add line number left aligned
   3799 awk '{print FNR "\t" $0}' files              # Add line number right aligned
   3800 awk NF test.txt                              # remove blank lines (same as grep '
   3801 .')
   3802 awk 'length > 80'                            # print line longer than 80 char)
   3803 
   3804 Some sed commands
   3805 
   3806    Here is the one liner gold
   3807    minehttp://student.northpark.edu/pemente/sed/sed1line.txt. And a good
   3808    introduction and tutorial to sedhttp://www.grymoire.com/Unix/Sed.html.
   3809 sed 's/string1/string2/g'                    # Replace string1 with string2
   3810 sed -i 's/wroong/wrong/g' *.txt              # Replace a recurring word with g
   3811 sed 's/\(.*\)1/\12/g'                        # Modify anystring1 to anystring2
   3812 sed '/<p>/,/<\/p>/d' t.xhtml                 # Delete lines that start with <p>
   3813                                              # and end with </p>
   3814 sed '/ *#/d; /^ *$/d'                        # Remove comments and blank lines
   3815 sed 's/[ \t]*$//'                            # Remove trailing spaces (use tab as
   3816  \t)
   3817 sed 's/^[ \t]*//;s/[ \t]*$//'                # Remove leading and trailing spaces
   3818 sed 's/[^*]/[&]/'                            # Enclose first char with [] top->[t
   3819 ]op
   3820 sed = file | sed 'N;s/\n/\t/' > file.num     # Number lines on a file
   3821 
   3822 Regular Expressions
   3823 
   3824    Some basic regular expression useful for sed too. See Basic Regex
   3825    Syntaxhttp://www.regular-expressions.info/reference.html for a good
   3826    primer.
   3827 [\^$.|?*+()                          # special characters any other will match th
   3828 emselves
   3829 \                                    # escapes special characters and treat as li
   3830 teral
   3831 *                                    # repeat the previous item zero or more time
   3832 s
   3833 .                                    # single character except line break charact
   3834 ers
   3835 .*                                   # match zero or more characters
   3836 ^                                    # match at the start of a line/string
   3837 $                                    # match at the end of a line/string
   3838 .$                                   # match a single character at the end of lin
   3839 e/string
   3840 ^ $                                  # match line with a single space
   3841 ^[A-Z]                               # match any line beginning with any char fro
   3842 m A to Z
   3843 
   3844 Some useful commands
   3845 
   3846    The following commands are useful to include in a script or as one
   3847    liners.
   3848 sort -t. -k1,1n -k2,2n -k3,3n -k4,4n         # Sort IPv4 ip addresses
   3849 echo 'Test' | tr '[:lower:]' '[:upper:]'     # Case conversion
   3850 echo foo.bar | cut -d . -f 1                 # Returns foo
   3851 PID=$(ps | grep script.sh | grep bin | awk '{print $1}')    # PID of a running sc
   3852 ript
   3853 PID=$(ps axww | grep [p]ing | awk '{print $1}')             # PID of ping (w/o gr
   3854 ep pid)
   3855 IP=$(ifconfig $INTERFACE | sed '/.*inet addr:/!d;s///;s/ .*//')   # Linux
   3856 IP=$(ifconfig $INTERFACE | sed '/.*inet /!d;s///;s/ .*//')        # FreeBSD
   3857 if [ `diff file1 file2 | wc -l` != 0 ]; then [...] fi       # File changed?
   3858 cat /etc/master.passwd | grep -v root | grep -v \*: | awk -F":" \ # Create http p
   3859 asswd
   3860 '{ printf("%s:%s\n", $1, $2) }' > /usr/local/etc/apache2/passwd
   3861 
   3862 testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \    # Check user in passw
   3863 d
   3864 root | grep -v \*: | awk -F":" '{ printf("%s\n", $1) }' | grep ^user$)
   3865 :(){ :|:& };:                                # bash fork bomb. Will kill your mac
   3866 hine
   3867 tail +2 file > file2                         # remove the first line from file
   3868 
   3869    I use this little trick to change the file extension for many files at
   3870    once. For example from .cxx to .cpp. Test it first without the | sh at
   3871    the end. You can also do this with the command rename if installed. Or
   3872    with bash builtins.
   3873 # ls *.cxx | awk -F. '{print "mv "$0" "$1".cpp"}' | sh
   3874 # ls *.c | sed "s/.*/cp & &.$(date "+%Y%m%d")/" | sh # e.g. copy *.c to *.c.20080
   3875 401
   3876 # rename .cxx .cpp *.cxx                             # Rename all .cxx to cpp
   3877 # for i in *.cxx; do mv $i ${i%%.cxx}.cpp; done      # with bash builtins
   3878 
   3879 Programming
   3880 
   3881 C basics
   3882 
   3883 strcpy(newstr,str)                        /* copy str to newstr */
   3884 expr1 ? expr2 : expr3                     /* if (expr1) expr2 else expr3 */
   3885 x = (y > z) ? y : z;                      /* if (y > z) x = y; else x = z; */
   3886 int a[]={0,1,2};                          /* Initialized array (or a[3]={0,1,2};
   3887 */
   3888 int a[2][3]={{1,2,3},{4,5,6}};            /* Array of array of ints */
   3889 int i = 12345;                            /* Convert in i to char str */
   3890 char str[10];
   3891 sprintf(str, "%d", i);
   3892 
   3893 C example
   3894 
   3895    A minimal c program simple.c:
   3896 #include <stdio.h>
   3897 main() {
   3898     int number=42;
   3899     printf("The answer is %i\n", number);
   3900 }
   3901 
   3902    Compile with:
   3903 # gcc simple.c -o simple
   3904 # ./simple
   3905 The answer is 42
   3906 
   3907 C++ basics
   3908 
   3909 *pointer                                  // Object pointed to by pointer
   3910 &obj                                      // Address of object obj
   3911 obj.x                                     // Member x of class obj (object obj)
   3912 pobj->x                                   // Member x of class pointed to by pobj
   3913                                           // (*pobj).x and pobj->x are the same
   3914 
   3915 C++ example
   3916 
   3917    As a slightly more realistic program in C++: a class in its own header
   3918    (IPv4.h) and implementation (IPv4.cpp) and a program which uses the
   3919    class functionality. The class converts an IP address in integer format
   3920    to the known quad format.
   3921 
   3922 IPv4 class
   3923 
   3924 IPv4.h:
   3925 
   3926 #ifndef IPV4_H
   3927 #define IPV4_H
   3928 #include <string>
   3929 
   3930 namespace GenericUtils {                          // create a namespace
   3931 class IPv4 {                                      // class definition
   3932 public:
   3933     IPv4(); ~IPv4();
   3934     std::string IPint_to_IPquad(unsigned long ip);// member interface
   3935 };
   3936 } //namespace GenericUtils
   3937 #endif // IPV4_H
   3938 
   3939 IPv4.cpp:
   3940 
   3941 #include "IPv4.h"
   3942 #include <string>
   3943 #include <sstream>
   3944 using namespace std;                              // use the namespaces
   3945 using namespace GenericUtils;
   3946 
   3947 IPv4::IPv4() {}                                   // default constructor/destruct
   3948 or
   3949 IPv4::~IPv4() {}
   3950 string IPv4::IPint_to_IPquad(unsigned long ip) {  // member implementation
   3951     ostringstream ipstr;                          // use a stringstream
   3952     ipstr << ((ip &0xff000000) >> 24)             // Bitwise right shift
   3953           << "." << ((ip &0x00ff0000) >> 16)
   3954           << "." << ((ip &0x0000ff00) >> 8)
   3955           << "." << ((ip &0x000000ff));
   3956     return ipstr.str();
   3957 }
   3958 
   3959 The program simplecpp.cpp
   3960 
   3961 #include "IPv4.h"
   3962 #include <iostream>
   3963 #include <string>
   3964 using namespace std;
   3965 int main (int argc, char* argv[]) {
   3966     string ipstr;                                 // define variables
   3967     unsigned long ipint = 1347861486;             // The IP in integer form
   3968     GenericUtils::IPv4 iputils;                   // create an object of the clas
   3969 s
   3970     ipstr = iputils.IPint_to_IPquad(ipint);       // call the class member
   3971     cout << ipint << " = " << ipstr << endl;      // print the result
   3972 
   3973     return 0;
   3974 }
   3975 
   3976    Compile and execute with:
   3977 # g++ -c IPv4.cpp simplecpp.cpp                # Compile in objects
   3978 # g++ IPv4.o simplecpp.o -o simplecpp.exe      # Link the objects to final execut
   3979 able
   3980 # ./simplecpp.exe
   3981 1347861486 = 80.86.187.238
   3982 
   3983    Use ldd to check which libraries are used by the executable and where
   3984    they are located. Also used to check if a shared library is missing or
   3985    if the executable is static.
   3986 # ldd /sbin/ifconfig                           # list dynamic object dependencies
   3987 # ar rcs staticlib.a *.o                       # create static archive
   3988 # ar t staticlib.a                             # print the objects list from the
   3989 archive
   3990 # ar x /usr/lib/libc.a version.o               # extract an object file from the
   3991 archive
   3992 # nm version.o                                 # show function members provided b
   3993 y object
   3994 
   3995 Simple Makefile
   3996 
   3997    The minimal Makefile for the multi-source program is shown below. The
   3998    lines with instructions must begin with a tab! The back slash "\" can be
   3999    used to cut long lines.
   4000 CC = g++
   4001 CFLAGS = -O
   4002 OBJS = IPv4.o simplecpp.o
   4003 
   4004 simplecpp: ${OBJS}
   4005         ${CC} -o simplecpp ${CFLAGS} ${OBJS}
   4006 clean:
   4007         rm -f ${TARGET} ${OBJS}
   4008 
   4009 Online Help
   4010 
   4011 Documentation
   4012 
   4013    Linux Documentation      en.tldp.org
   4014    Linux Man Pages          www.linuxmanpages.com
   4015    Linux commands directory www.oreillynet.com/linux/cmd
   4016    Linux doc man howtos     linux.die.net
   4017    FreeBSD Handbook         www.freebsd.org/handbook
   4018    FreeBSD Man Pages        www.freebsd.org/cgi/man.cgi
   4019    FreeBSD user wiki        www.freebsdwiki.net
   4020    Solaris Man Pages        docs.sun.com/app/docs/coll/40.10
   4021 
   4022 Other Unix/Linux references
   4023 
   4024    Rosetta Stone for Unix bhami.com/rosetta.html (a Unix command
   4025    translator)
   4026    Unix guide cross reference unixguide.net/unixguide.shtml
   4027    Linux commands line list www.linuxcmd.org
   4028    Short Linux reference www.pixelbeat.org/cmdline.html
   4029    Little command line goodies www.shell-fu.org
   4030 
   4031    That's all folks!
   4032 
   4033    This document: "Unix Toolbox revision 14.4" is licensed under a Creative
   4034    Commons Licence [Attribution - Share Alike]. © Colin Barschel 2007-2012.
   4035    Some rights reserved.