Difference between revisions of "John's Linux page"

From ProgClub
Jump to: navigation, search
Line 310: Line 310:
  
 
  # zfs send data/example | pv | cat > /dev/null
 
  # zfs send data/example | pv | cat > /dev/null
 +
 +
== Using Smartctl, Smartd and Hddtemp on Debian ==
 +
 +
For notes on using smartctl see [https://www.lisenet.com/2014/using-smartctl-smartd-and-hddtemp-on-debian/ Using Smartctl, Smartd and Hddtemp on Debian].
  
 
= Monitoring disk I/O =
 
= Monitoring disk I/O =

Revision as of 20:45, 13 May 2019

Hi there, I'm John. I just wanted a page where I could document various Linux things that I bump into. This is that page. Thank you ProgClub. :)

Note: I have some other disorganised notes on UNIX, which include a few tips for MacOS. I also have some tips for OS X.

System

Determining which Debian/Ubuntu release your are running

$ lsb_release -r

Or for more information:

$ lsb_release

Determining which Unix you are running

$ uname

Or,

$ uname -a

Configuring system swappiness

Swappiness is a number between 0 and 100 that regulates how much the system uses the swap file. I like setting this value to 0 to keep my apps as responsive as possible. Create a file /etc/sysctl.d/local.conf and add this line:

vm.swappiness = 0

If you want to set the value for the current session only:

echo 0 > /proc/sys/vm/swappiness

Hardware information

For information about the hardware attached to your system, check out:

# lshw

And for CPUs:

# lscpu

And for PCI devices:

# lspci

And for DMI info:

# dmidecode

Or the grand daddy of them all:

# hwinfo

There's also inxi, e.g.:

$ inxi -b

System:    Host: tact Kernel: 4.9.0-4-amd64 x86_64 (64 bit) Desktop: KDE Plasma 5.8.6
           Distro: Debian GNU/Linux 9 (stretch)
Machine:   Device: desktop Mobo: ASUSTeK model: STRIX Z270F GAMING v: Rev 1.xx
           UEFI [Legacy]: American Megatrends v: 0906 date: 03/22/2017
CPU:       Quad core Intel Core i7-7700K (-HT-MCP-) speed/max: 799/4600 MHz
Graphics:  Card: Intel Device 5912
           Display Server: X.Org 1.19.2 drivers: modesetting (unloaded: fbdev,vesa)
           Resolution: 1920x1080@60.00hz, 1920x1080@60.00hz
           GLX Renderer: Mesa DRI Intel Kabylake GT2 GLX Version: 3.0 Mesa 13.0.6
Network:   Card: Intel Ethernet Connection (2) I219-V driver: e1000e
Drives:    HDD Total Size: 13026.6GB (42.0% used)
RAID:      Devices: 1: /dev/md1 2: /dev/md0
Info:      Processes: 355 Uptime: 11 days Memory: 21198.3/32043.3MB Client: Shell (bash) inxi: 2.3.5

Environment

Configuring vim as your editor

Sometimes all you need is:

$ export EDITOR=/usr/bin/vim

Which works for svn, for example. Add it to your ~/.profile file to have it set for all login sessions.

Other times you need to run

# update-alternatives --config editor

And then select vim from the list. This is what you do to configure your visudo editor.

Configuring your locale

$ sudo /usr/sbin/locale-gen en_AU.UTF-8
$ sudo /usr/sbin/update-locale LANG=en_AU.UTF-8

User and group management

Adding a user

To add a new user on a linux system:

# useradd username
# passwd username

To have the home directory created from '/etc/skel' use the 'adduser' script instead:

# adduser username

Adding a user to a group

To add an existing user to an existing group:

# gpasswd -a username group

e.g. to add user 'jj5' to the 'sudo' group:

# gpasswd -a jj5 sudo

Alternatively you can use adduser, passing the username and group:

# adduser username group

e.g. to add user 'sclaughl' to the 'staff' group:

# adduser sclaughl staff

Disabling a user account

You can disable a user account with:

# passwd -l user

Note: that's a lower-case L, not a one.

Enabling a disabled user account

To can re-enable a locked user account with:

# passwd -u user

Finding which user you are logged in as

To determine which user you are running as enter the command:

$ whoami

Finding which groups you are a member of

To find which groups you are a member of:

$ groups

or

$ groups username

Where 'username' is the username of the user you are querying, e.g.:

$ groups jj5

Finding who else is logged in to the system

To see who else is logged in,

$ who

Running a command as a particular user

To run "svn update" as the user www-data:

$ sudo su -c "svn update" www-data

Memory management

Checking available memory

To report memory statistics in megabytes:

$ free -m

Video/display management

Viewing EDID data for attached monitor

To view EDID data for an attached monitor (requires the edid-decode package):

$ cd /sys/class/drm
$ ls
$ cd card0-HDMI-A-1
$ edid-decode edid

Process management

Using 'top' for dynamic resource usage reporting

To run top:

$ top

See 15 Practical Linux Top Command Examples for some hints on usage.

To see usage for a specific user run e.g.:

$ top -u jj5

To see full command-line press 'c'.

When you're in 'top' you can:

  • press '1' (one) to toggle CPU aggregation
  • press < and > to change the sort column

Changing memory reporting in 'top'

To run top:

$ top

Press 'E' to switch between top memory units (KiB, MiB, GiB, etc.)

Press 'e' to switch between bottom memory units (KiB, MiB, GiB, etc.)

Press 'M' to sort by memory utilisation.

Press 'm' to switch between various display modes.

Disk management

Listing disk drives

# fdisk -l

(That's an L for "list")

Checking available disk space

$ df -h

Getting disk information

# lsblk

And

# cat /proc/partitions

Or the Grand Daddy of them all:

# lshw -class disk

(Requires the lshw package.)

Getting partition UUID and file-system type

# blkid

Checking for SSD vs magnetic disk

# cat /sys/block/sda/queue/rotational

Will be 0 for SSD and 1 for magnetic.

Monitoring a ZFS server

So some commands I run to keep an eye on my new ZFS servers:

# top
# iotop
# nethogs
# watch free -h
# watch slabtop -o
# slabtop
# watch cat /proc/meminfo
# perf top
# watch "df -h | grep -v -e tmpfs -e udev -e by-uuid"
# watch zpool iostat -v
# zpool iostat -v 2
# watch 'zpool list; echo; zfs list'
# watch zfs get compressratio -o all
# watch cat /proc/spl/kstat/zfs/arcstats

If you have a scrub or resilvering in progress you can report on progress with:

# watch zpool status -v

You can poke about in internals, e.g.:

# cat /proc/spl/kstat/zfs/arcstats
root@orac:/sys/module/zfs/parameters# tail *

You can report on property values with e.g.:

# zfs get all data

If you want to get funky:

# cd /tmp
# perf record -ag #(Ctrl+C after ~15 seconds)
# perf report --stdio

You can search for ZFS files like e.g. this:

root@orac:/# find / -name '*zfs*' -or -name '*zpool*'

Measure data throughput

Use the 'pv' command from the 'pv' package, e.g.:

# cat /dev/sda | pv | cat > /dev/null

Or for ZFS:

# zfs send data/example | pv | cat > /dev/null

Using Smartctl, Smartd and Hddtemp on Debian

For notes on using smartctl see Using Smartctl, Smartd and Hddtemp on Debian.

Monitoring disk I/O

There's an app for that! iotop.

Using iotop, top for disks

# iotop -oPa

File management

Listing only directories

$ ls -l | egrep '^d'

Listing only files

$ ls -l | egrep -v '^d'

Listing hidden files

$ ls -al .[!.]*

Creating a symbolic link

$ ln -s /path/to/target link-name

Creating a hard-link

$ ln /path/to/target file-name

Changing the owner of a file

$ chown user:group <files>

E.g.

$ chown jj5:staff README
$ chown root:root *

To apply recursively into sub-directories use -R,

$ chown -R root:root /etc/*

Changing file permissions

Object codes
User Group Other
u g o
Permission codes
Read Write Exectue
r w x
4 2 1
Numeric codes
0 None
1 Execute
2 Write
3 Write, Execute
4 Read
5 Read, Execute
6 Read, Write
7 Read, Write, Execute

See Numeric Mode in Action.

$ chmod <user numeric code><group numeric code><other numeric code> <files>
$ chmod <object codes>+|-<permission codes> <files>

E.g.

$ chmod 600 my-private-file
$ chmod go-rwx my-private-file
$ chmod u+rw my-private-file
$ chmod +x my-script

Updating config files

If you get given a new config file called new.conf and you want to integrate it with your old config file old.conf then:

$ cp old.conf updated.conf
$ merge -A updated.conf new.conf old.conf

Then go through and edit updated.conf resolving all the merge errors, picking and choosing what to update and what to keep. When you're done copy updated.conf to old.conf so it becomes the new config file.

The merge program is a part of the RCS package. If you don't have it:

$ sudo apt-get install rcs

Listing open files

Use lsof to list open files. E.g.:

# lsof

See man lsof for options.

List permissions on a whole directory path

E.g.:

$ namei -om /home/jj5/workspace

Outputs:

f: /home/jj5/workspace/
 drwxr-xr-x root root /
 drwxr-xr-x root root home
 drwxr-xr-x jj5  jj5  jj5
 drwxr-xr-x jj5  jj5  workspace

Counting non-blank lines in a file

E.g.:

$ cat foo.c | sed '/^\s*$/d' | wc -l

Cloning one directory to another with rsync

E.g.:

rsync --acls --xattrs --stats --human-readable --recursive --del --force --times --links --hard-links --executability --numeric-ids --owner --group --perms --sparse --compress-level=0 /data/source/ hostname:/data/target/

Symbolic-link management

== Data used by sym-linked files:

This will de-reference the sym-links in the current directory and tell you how much data the files pointed to by the sym-links are using:

jj5@tact:/data/backup/unity/latest$ du -hD * | sort -h

File searching

Finding a file with a particular name

$ find -iname "*some-part-of-the-file-name*"

Will start searching from the current directory, so maybe

$ cd /

first. For a case-sensitive search:

$ find -name "*eXaCT CaSE*"

Finding a file with particular content

To search in /etc/ for a file with particular content:

$ grep -R "search-string" /etc/*

To search the current directory for *.cs files containing the word "Up":

$ find . -name '*.cs' -exec grep --color=auto -H Up {} \;

Finding a list of files with particular content

E.g. to find all the files with the word 'creativity':

$ grep -R creativity . | sed 's/:/ /' | awk '{ print $1 }' | sort | uniq

Using the locate command to find files

$ locate part-of-filename

E.g.

$ locate texvc

Updating locate command's database

# updatedb

Job control

Stopping a running process

Press Ctrl+Z to stop a running process.

Listing current jobs and their status

$ jobs

Resuming a stopped job in the backgroud

To resume a stopped process in the background

$ bg %1

where '1' is the job number reported by bash when you pressed Ctrl+Z (or ran 'jobs').

Resuming a stopped job in the foreground

To resume a stopped process in the foreground

$ fg %1

where '1' is the job number reported by bash when you pressed Ctrl+Z (or ran 'jobs').

Killing a stopped job

To kill a job

$ kill %1

where '1' is the job number reported by bash when you pressed Ctrl+Z (or ran 'jobs').

Periodically run a program and watch its output

$ watch /your/command

Debian/Ubuntu package management

Also see Where "is" it? on the Debian Wiki.

configuring debconf

# dpkg-reconfigure debconf 

Set priority to low to get asked detailed questions.

Showing list of installed packages

# dpkg --get-selections

Searching for installed package

# dpkg --get-selections | grep package-name

or

# aptitude search package-name

Showing which files are installed as part of a package

# dpkg -L package-name

Installing a package

# apt-get install package-name

Uninstalling a package

# apt-get remove package-name

Showing system architecture

$ dpkg --print-architecture

Showing which package a file belongs to

$ which echo
/bin/echo
$ dpkg -S /bin/echo
coreutils: /bin/echo
$ dpkg -l | grep coreutils
ii  coreutils                         6.10-6                   The GNU core utilities

Showing package information

$ apt-cache showpkg coreutils

Or for even more information:

$ apt-cache show coreutils

List all installed packages with package version info

dpkg-query -l

Reporting which version of a package is installed

$ dpkg -l | grep package-name

E.g.:

root@hope:~/letsencrypt# dpkg -l | grep augeas
ii  augeas-lenses                   0.7.0-1ubuntu1                 Set of lenses needed by libaugeas0 to parse 
ii  libaugeas0                      0.7.0-1ubuntu1                 The augeas configuration editing library and

Comprehensive upgrade

Try the following:

# apt-get update
# apt-get dist-upgrade
# apt-get autoremove
# apt-get remove $(deborphan)
# update-flashplugin-nonfree --install

Searching all available packages

$ apt-cache search . | sort -d | less

Networking

net-tools vs iproute2

The older 'net-tools' package has been replaced with 'iproute2' e.g. in stretch.

legacy net-tools commands iproute2 replacement commands
arp ip n (ip neighbor)
ifconfig ip a (ip addr), ip link, ip -s (ip -stats)
iptunnel ip tunnel
iwconfig iw
nameif ip link, ifrename
netstat ss, ip route (for netstat-r), ip -s link (for netstat -i), ip maddr (for netstat-g)
route ip r (ip route)

Restart networking

For servers:

# service networking restart

For desktops:

# service network-manager restart

Pinging with particular packet size

$ ping -M do -s <packet size in bytes> <host>

E.g.

$ ping -M do -s 1400 charity.progclub.org

Setting MSS for a particular IP address on a particular interface

# ip route add <host> dev <interface> advmss <packet size>

E.g.

# ip route add 10.0.0.1 dev eth0 advmss 1400

Dropping configured MMS for a particular IP address

# ip route flush <host>

E.g.

# ip route flush 10.0.0.1

Listing open ports and socket information

Including which process is listening on which port.

# netstat -tulpn

Or use the 'ss' command:

# ss -s
# ss -l
# ss -pl
# ss -o state established '( dport = :smtp or sport = :smtp )'

Listing open IPv4 connections

# lsof -Pnl +M -i4

You might need to install the lsof package:

# apt-get install lsof

Query for DNS MX record

$ nslookup
> server 127.0.0.1
> set q=mx
> mail.blackbrick.com

Query for DNS SOA record

$ dig @ns2.staticmagic.net -t SOA staticmagic.net

Using nmap to list open ports on remote host

To check the 1,000 most common ports:

# nmap server.example.com

Or for a specific port range (e.g. 101 to 102):

# nmap -p 101-102 server.example.com

Or for all ports (1 to 65,535):

# nmap -p- server.example.com

Network monitoring

See here for details. Basically:

  1. Overall bandwidth: nload, bmon, slurm, bwm-ng, cbm, speedometer, netload
  2. Overall bandwidth (batch style output): vnstat, ifstat, dstat, collectl
  3. Bandwidth per socket connection: iftop, iptraf, tcptrack, pktstat, netwatch, trafshow
  4. Bandwidth per process: nethogs

nload

You can watch network traffic in real-time with nload:

# nload -u M

Reporting network (NIC) speed

From here:

# dmesg | grep eth0
# mii-tool -v eth0
# ethtool eth0

Note: use ifconfig to get device name.

Path MTU discovery

To do a Path MTU Discovery, from the iputils-tracepath package:

# tracepath host.example.com

Listing available Ethernet devices

To see a list of NICs available on the host:

$ cat /proc/net/dev

Also

$ ip link

Links

IPTables

Applying firewall rules

For configuration info see this article.

$ sudo vim /etc/iptables.test.rules
$ sudo /sbin/iptables -F
$ sudo /sbin/iptables-restore < /etc/iptables.test.rules
$ sudo iptables -L
$ sudo -s
# iptables-save > /etc/iptables.up.rules
# exit

ufw

Denying hosts with ufw

See denying hosts with ufw.

Bind9

Viewing Bind9 querylog

$ sudo rndc querylog
$ tail -f /var/log/syslog

IPSec

Disabling IPSec

# setkey -FP

OpenSSL

Debugging IMAPS with OpenSSL

# openssl s_client -connect localhost:993
> a1 LOGIN username@host password
> a2 LOGOUT

Debugging HTTPS with OpenSSL

$ openssl s_client -connect www.example.com:443
GET /example.html HTTP/1.1
host: www.example.com

Links

Pluggable Authentication Modules (PAM)

Links

SSH

Configuring SSH key login

On the client machine generate a key-pair (if necessary, check for existing ~/.ssh/id_rsa.pub):

$ ssh-keygen -t rsa

Copy the public key from the client to the server:

$ scp ~/.ssh/id_rsa.pub user@example.org:

Configure the authorized keys on the server:

$ ssh user@example.org
$ mkdir ~/.ssh
$ chmod go-w .ssh
$ cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
$ chmod 600 ~/.ssh/authorized_keys
$ rm ~/id_rsa.pub

Tunneling over SSH

For example, connecting a remote MySQL server to the localhost:

$ ssh -L 3306:localhost:3306 jselliot@ssh.progsoc.org

If the machine you want to connect to is not the localhost of the machine you're ssh'ing to,

 $ ssh -L 3306:muspell.progsoc.uts.edu.au:3306 ssh.progsoc.uts.edu.au

The -L stanza is localport:remotehost:remoteport where localport is a port on your machine, forwarded to remoteport on remotehost.

Tunneling over SSH with PuTTY

See Connecting to the MySQL database remotely (via an SSH Tunnel)

  • run putty.exe
  • Connection -> SSH -> Tunnels
    • Port forwarding: source port to 3306
    • destination: 127.0.0.1:3306
    • check Local
    • click Add

Enabling verbose SSH logging

To see what's going on with your ssh connections,

$ ssh -v user@host

Or

$ ssh -vv user@host

Unlocking SSH key for session

jj5@orac:~/.config/autostart$ cat ssh-add.desktop 
[Desktop Entry]
Type=Application
Name=ssh-add
Comment=Adds my private key to my session.
Exec=/usr/bin/konsole -e 'ssh-add /home/$USER/.ssh/id_rsa'

Links

Standard IO

cat EOF

$ cat > output <<EOF
> text
> EOF
$ cat output
text

Script

Creating a session log with script

$ script -t 2> timing

The session log is in the file 'typescript' and the timing data is in 'timing'.

Replaying a scripted session

$ scriptreplay timing

Uses the default file 'typescript' and the 'timing' file as specified.

Screen

Creating a new screen or reconnecting to a detached screen

$ screen -R

Detaching a screen

$ screen -D

Reconnecting to screen

$ screen -D
$ screen -R

I have a script in ~/bin/reconnect like so,

#!/bin/bash
screen -D
screen -R

This will detach your last screen, and reconnect it on the current terminal.

Scrolling in screen

See How to scroll in GNU Screen. Basically press Ctrl+A ESC then use Page Up and Page Down. Press ESC again to exit copy mode. As usual you can use Ctrl+[ in place of ESC.

Vim

First, why Vim?

Read Why, oh WHY, do those #?@! nutheads use vi?

Visual modes

Use 'v' for visual mode, 'V' for visual line mode and Ctrl+V for visual block mode.

Configuring spaces instead of tabs

I use two spaces instead of tabs. To configure, edit your .vimrc file:

$ vim ~/.vimrc

and include the following lines:

set tabstop=2
set shiftwidth=2
set expandtab

Configuring syntax highlighting

See here.

Use:

:syntax on

to turn on syntax highlighting.

Use:

:syntax off

to turn off syntax highlighting.

To always use syntax highlighting:

$ vim ~/.vimrc

and add:

syntax on

To get a list of supported colour schemes open vim and type:

:colorscheme[space][Ctrl+D]

To always use a particular colorscheme edit ~/.vimrc and add (for example):

colorscheme desert

Inserting a TAB character when expandtab is on

The problem here is that you have configured vim to insert spaces, but for a particular file (e.g. a Makefile) you need to insert a character.

Press Ctrl+V TAB to insert a literal tab character.

Or you can disable tab expansion altogether with:

:set expandtab!

Changing 2 space indent to 4 space indent (e.g. for python files)

:%s/^\s*/&&/g

For more information see here.

Recording and replaying a macro

To record a macro press 'q' and then a number between 1 and 9. E.g. press "q1". The macro is now recording. When you've finished issuing your commands press 'q' again to finish recording. To replay a macro press '@' followed by the number of the macro. That is, if you pressed "q1" to record the macro, press "@1" to replay the macro. To replay the last macro again press "@@".

Deleting to end of line

d$

Deleting to beginning of line

d^

Finding text

To search forward for "text":

/text

To search backward for "text":

?text

To repeat the last search in a forward direction press 'n', or to search again backwards press 'N'.

Finding and replacing text

To replace the first instance of "search" on the current line with "destroy":

:s/search/destroy/

To replace all instances of "search" on the current line with "destroy":

:s/search/destroy/g

To replace all instances of "search" on lines 13 to 37 with "destroy":

:13,37 s/search/destroy/g

To replace all instances of "search" in the entire file with "destroy":

:%s/search/destroy/g

Changing DOS/Windows line-endings (CRLF) to Unix line-endings

To set the line-ending to Unix line endings run the command:

:setlocal ff=unix

More information on managing file formats available here.

Disabling auto-indent etc. to paste from clipboard

To disable smart indenting when you're going to paste in text:

:set paste

To turn it off again:

:set nopaste

There's more info in this article: Toggle auto-indenting for code paste

Positioning windows

Use -o for horizontal split, e.g.:

vim -o a.txt b.txt

Use -O for vertical split, e.g.:

vim -o a.txt b.txt

Use ^W to navigate windows then use directional keys h, j, k, l, etc.

Use ^W and < or > to resize windows.

To indent a block of text in Vim

Use the > command. E.g. to indent five lines:

5 > >

Press . (dot) to keep indenting.

Or inside a block (e.g. curly brace, HTML/XML element, etc.) you can put your cursor in the element on on the curly brace and then:

> %

See here for more.

Open a file in a new window/tab

To open a file on the left hand side:

:vert new filename.ext

Note: ':vnew filename.ext' and ':vsp filename.ext' also work.

To open a file at the top:

:new filename.ext

See here for more.

Explore files in Vim

Enter:

:Explore

Switch between Vim tabs

Use gt and gT.

Switch between Vim windows

To toggle between open windows use:

Ctrl+W W

To move in a direction use:

Ctrl+W h/j/k/l

See here for more.

Insert block comment in Vim

See here for line-commenting.

So it's:

  1. Ctrl+V (Note: not Shift+V!)
  2. Up/Down to select rows
  3. Shift+I
  4. Enter your text, e.g. '#' or '//'
  5. Ctrl+[ (or 'Esc')

Navigate to matching tag

To navigate to the matching beginning or end tag use '%'.

You can also use e.g. '[{' to match the previous '{', or e.g. '])' to match the next ')'.

Auto-format HTML tags

Stolen from here.

  1. first join all the lines - ggVGgJ
  2. Now break tags to new lines - :%s/>\s*</>\r</g
  3. Now set filetype - :set ft=html (you can do this before too)
  4. Now Indent - ggVG=

Links

Write

Talking to other users on the system

write is a unix command for talking to other users on the system. To use write:

1. SSH to <username>@<hostname> and login with your username and password.

2. Issue the following command to find out who is logged onto the system:

$ who

3. Issue the following command to talk to a specific user:

$ write <username>

4. Enter the message you'd like to send the user, followed by Ctrl+C to send. Press Ctrl+D to cancel.

Date

Reporting the time on the server

$ date

Reporting UTC time

$ date --utc

Getting the date in yyyy-MM-dd-hhmmss format

$ date="`date +%F-%H%M%S`"

Getting the year in four digits

$ year="`date +%Y`"

Getting the month in two digits

$ month="`date +%m`"

Getting the day of the month in two digits

$ day="`date +%d`"

Getting yesterday's date

$ date --date='1 day ago' +%Y-%m-%d

Converting Unix time (seconds since epoch)

For timestamp '1501370200':

$ date -d @1501370200 +%F-%H%M%S

Running timedatectl from systemd

There's a new command bundled with systmed:

# timedatectl

It reports on (and controls) how the system time is configured.

MySQL

Run mysql without authentication/authorisation

# service mysql stop
# mysqld_safe --skip-grant-tables &

Then you can connect without a password, e.g.:

# mysql -u root mysql

To stop the unauthenticated service:

# mysqladmin shutdown

Then restart a normal service:

# service mysql start

Logging all database queries

# vim /etc/mysql/my.cnf

In the [mysqld] section add:

log=/tmp/mysql.log

Then:

# service mysql restart

Watch the log with:

# tail -f /tmp/mysql.log

Dumping a MySQL database

You can dump the database into a file using:

$ mysqldump -h hostname -u user --password=password databasename > filename

Loading a MySQL database from a dump file

You can create a database using:

$ echo create database databasename | mysql -h hostname -u user -p

You can restore a database using:

$ mysql -h hostname -u user --password=password databasename < filename

Creating a MySQL user

# mysql -h localhost -u root --password=<password>
mysql> create user 'username'@'localhost' identified by '<password>';

Granting all MySQL user permissions

# mysql -h localhost -u root --password=<password>
mysql> grant all privileges on dbname.* to user@host;

Select domain name from email address

SELECT SUBSTR( email, INSTR( email, '@' ) + 1 )

Check if MySQL connection is encrypted with TLS/SSL

Check the SSL version in use:

show status like 'Ssl_version';

Or check the cipher in use:

show status like 'Ssl_cipher';

Apache

Maintaining .htaccess passwords

To add or modify the password for a user:

$ htpasswd /etc/apache2/passwd username

Configuring PHP session timeout in .htaccess

For a session timeout of 9 hours:

php_value session.cookie_lifetime 32400
php_value session.gc_maxlifetime 32400

Disabling PHP magic quotes in .htaccess

php_flag magic_quotes_gpc Off

Requiring HTTP Auth in .htaccess

AuthType Basic
AuthName "Speak Friend And Enter"
AuthUserFile /home/jj5/.htpasswd
Require valid-user

Restarting Apache

The hard way

$ sudo /etc/init.d/apache2 restart

The graceful way (avoids dropping active connections)

$ sudo apache2ctl graceful

Allowing directory browsing

To show directory index pages, in the apache config file:

<Directory /var/www/data>
  Options Indexes
</Directory>

C

Locating memset function

The memset function is in <string.h> as described in this article Using memset(), memcpy(), and memmove() in C

Links

PHP

Including a file relative to the including file

require_once( dirname( __FILE__ ) . '/relative/path/to.php' );

Enabling error reporting

error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', 'On' );

Setting an error handler

set_error_handler( "error_handler", E_ALL | E_STRICT );
function error_handler( $error_code, $error_message, $error_file, $error_line, $error_context ) {
  // ...
}

Disable HTML content in var_dump

ini_set( 'html_errors', 'off' );

BASH scripting

For a primer on bash scripting see TFM: Erotic Fantasy: /bin/sh Programming.

Telling a script to run in bash

The first line of the file should be:

#!/bin/bash

Checking if a command-line argument was passed in

if [ -n "$1" ]; then
  echo "Missing parameter 1.";
  exit 1;
fi

Checking if a command-line argument was not passed in

if [ "$1" = "" ]; then
  echo "Missing parameter 1.";
  exit 1;
fi

Or:

if [ -z "$1" ]; then
  echo "Missing parameter 1.";
  exit 1;
fi

Checking command exit status

cd /my/path
if [ "$?" -ne "0" ]; then
  echo "Cannot change dir.";
  exit 1;
fi

Checking if a file does/doesn't exist

Check if file exists:

if [ -f "/my/file" ]; then
  cat /my/file
fi

Check if file doesn't exist:

if [ ! -f "/my/file" ]; then
  touch /my/file
fi

Checking if a directory does/doesn't exist

Check if directory exists:

if [ -d "/my/dir" ]; then
  rmdir /my/dir
fi

Check if directory doesn't exist:

if [ ! -d "/my/dir" ]; then
  mkdir /my/dir
fi

Deleting old backups

To keep only the latest five backups:

find . -maxdepth 1 -type f -printf '%T@ %p\0' | sort -r -z -n | awk 'BEGIN { RS="\0"; ORS="\0"; FS="" } NR > 5 { sub("^[0-9]*(.[0-9]*)? ", ""); print }' | xargs -0 rm -f

This script stolen from stackoverflow.

Requires GNU find for -printf, GNU sort for -z, GNU awk for "\0" and GNU xargs for -0, but handles files with embedded newlines or spaces.

Changing into the script's directory

cd "`dirname $0`"

Getting the absolute path of a relative path

readlink -f ./some/path

Creating a temp directory

dir=`mktemp -d` && cd $dir

Reading secret input from stdin

You can read a secret, such as a password, like this:

echo -n "Enter passphrase: "
stty -echo
read passphrase;
stty echo
echo ""

After running the above the secret will be in the $passphrase environment variable.

String replacements in bash

See the string manipulation doco. Basically, to replace first occurrence:

result=${var/find/replace}

To replace all occurrences:

result=${var//find/replace}

A practical example, get an ISO date and turn it into a path:

date="$(date +%Y-%m-%d)"
work_dir=${date//-//}

Sending a HEREDOC to a file

cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
        This line is indented.
EOF

Bash case/switch statement

See using case statements, e.g.:

case $space in
[1-6]*)
  Message="All is quiet."
  ;;
[7-8]*)
  Message="Start thinking about cleaning out some stuff.  There's a partition that is $space % full."
  ;;
9[1-8])
  Message="Better hurry with that new disk...  One partition is $space % full."
  ;;
99)
  Message="I'm drowning here!  There's a partition at $space %!"
  ;;
*)
  Message="I seem to be running with an nonexistent amount of disk space..."
  ;;
esac

Using dotglob shopt to match dot-files

To enable dot-file matching in globs, set the dotglob shell option:

$ shopt -s dotglob

Sed

Find and replace with sed

To update the current file use '-i'. E.g.:

sed -i 's/search-text/replace-text/' file

Awk

Listing IP addresses in an Apache web log

awk '/GET \/path\/for\/url/ { print $1 }' /var/log/apache2/access.log | sort | uniq

Printing space-separated field

echo 'no no yes no' | awk '{print $3}'

Printing delimited field

echo 'no:no:yes:no' | awk -F ':' '{print $3}'

Subversion

Setting svn:externals from the command-line

See here.

To set an svn:externals from the command-line:

svn propset svn:externals 'rdfind-php https://www.progclub.org/svn/pcrepo/rdfind.php/branches/0.1' .
svn ci -m 'Adding svn:externals for rdfind-php...'
svn up

Or to use a file:

svn propset svn:externals -F svn.externals .

Setting svn:ignore from the command line

See here.

$ svn propset svn:ignore [file|folder] [path]

Or use a file and apply recursively:

$ svn propset svn:ignore -RF ./svn-ignore-list.txt .

Git

Showing status of working copy

git status

Showing repo history

git log

Showing remote repositories (including 'origin')

git remote -v

Handy git aliases

Save these to your ~/.gitconfig file.

For a nicer view of history than standard 'git log' -- colourful, one-line-per commit, etc:

 graph = !git log --all --graph --color --abbrev-commit --pretty=oneline

To show only the files that have changed, rather than the full line-by-line content:

 dif   = !git diff --name-status

IRC

Instructing ChanServ to op an admin

/msg ChanServ op #channel user

E.g.

/msg ChanServ op #gnurc jj5

Sub 'op' for 'deop' to remove op privilege.

C++

C++ books

Books I want

Books I own

Books I'm not reading

Books I've read

C++ blogs/articles

C++ performance tips

  • ++c can be faster than c++.
  • use const for everything that you possibly can.
  • use 'inline' when you need to define a function in a header. Typically only do that if it's small and the increase in code size from inlining is worth the cost to avoid the cost of a function call. For anything except trivially small functions you'll probably need to profile to know if it's worth it.
  • don't use registers.
  • const rarely affects performance.
  • debunking a number of C++ myths that won't die.
  • std::sort<> is typically faster than qsort() because it can avoid indirection at runtime.
  • if you've got parallelisation going on, you may be able to just replace a std::for_each with a parallel equivalent.
  • read about performance cost of RTTI (Run Time Type Information) and how to disable it
  • don't use dynamic_cast because it is slow (typeid is faster but still relies on RTTI)
  • prefer unique_ptr to shared_ptr when possible. unique_ptr has less overhead.
  • Which is better, static or dynamic linking?
  • Integer vs Floating-Point performance

systemd

systemd is an init system used in most Linux distributions to bootstrap the user space and manage all processes subsequently.

Following a service log

e.g. for bind9:

# journalctl -f -u bind9

or for everything:

# journalctl -f

System status

To see spawned services hierarchy:

# systemctl status

Or for a specific service e.g.:

# systemctl status networking

SaltStack

Running a command on specified minions

salt 'host' cmd.run 'update-locale'

Running a command on all minions

salt '*' cmd.run 'update-locale'

Listing active jobs

salt-run jobs.active

Listing available grains

salt 'example' grains.items

Listing available pillar

salt 'example' pillar.items

Reporting a grain value

e.g. for the 'mem_total' grain:

salt '*' grains.item mem_total

KDE

Running user login script (X11/XOrg/XWindows)

A way to run user login scripts which works for KDE Plasma (and apparently other X.Org Server X Window System environments) is to create a *.desktop file in ~/.config/autostart/. For example I have a ~/.config/autostart/ssh-add.desktop file with the following contents to register my SSH key in the SSH Agent:

[Desktop Entry]
Type=Application
Name=ssh-add
Comment=Adds my private key to my session.
Exec=/usr/bin/konsole -e 'ssh-add /home/$USER/.ssh/id_rsa'