November 19

Linux: Postgresql

Check PostgreSQL version:
psql –version

Log into PostgreSQL. Login as default user i.e. postgres with password password_of_your_ubuntu_system:
sudo -u postgres psql

Create a new user for PostgreSQL and assign a password to it. Since it is not considered a good practice to persist your data in PostgreSQL through the default user i.e. postgres, we will create a new user and assign a password to it. It can be done by 2 possible ways:

First way:
sudo -u postgres createuser –interactive

Here, you would be asked name of the role/user, if you want to assign superuser privileges to the new user or not; and if not whether the user be allowed to create databases and new roles.
After creating the user, login to PostgreSQL console via the default user i.e. postgres and then alter the password for the user via following command (assuming the new user/role you created is lihas):

ALTER USER lihas WITH PASSWORD ‘lihas’;

Note: In case the name of your user contains capital letters, wrap the username into double quotes while performing all user related operations like:

ALTER USER “LiHaS” WITH PASSWORD ‘lihas’;

Second way:
Log into PostgreSQL console via the default user ie ‘postgres’ and then create the user:

CREATE USER lihas WITH PASSWORD ‘lihas’; –Assuming the new user/role we want to create is lihas

ALTER USER lihas WITH CREATEDB; –user lihas con create databases

ALTER USER lihas WITH CREATEUSER; –user lihas con create new users/roles

Note: According to the convention, whenever a new user is created; a database with the same name as the new username must be created and this database shall not be used to store data. You may create the database by following command 10 below.

List all users in PostgreSQL:
\du

Switch to a user:
SET ROLE user_name;

Check current user:
SELECT CURRENT_USER;

Delete a user/role:
DROP USER user_name;

List all databases:
\l

Create database:
CREATE DATABASE lihas_db;

By default, the owner of any database you create is postgres, if you want your database to belong to a specific user, switch to that user (see above) and then create the database.

Enter a database. Enter inside database via the default user:

\c database_name

…or…

\connect database_name

Enter inside the database with a specific user:

\c database_name user_name

If the above command does not work (Peer authentication failed), simply change the database first and then switch to the user (see command 6 above).

Note: You may also log in directly into a database with a certain user from the terminal by following command (with password as password_of_your_ubuntu_system).

sudo -u role_name psql db_name

But for this command to work, role_name must be a valid Linux user name. You may add a user to Linux by following :

sudo adduser role_name;

Drop database:

DROP DATABASE db_name;

List all tables:
\d

Describe schema of a table:
\d table_name

Exit out of PostgreSQL:
\q

Category: Linux | Comments Off on Linux: Postgresql
November 19

Linux: Docker cheat sheet

Docker images

list:
docker images

run image:
docker run full/image/name:version

docker commit changes:
docker commit container-id full/image/name:version

removing images (linked containers need removed first)
docker rmi image-id

save container:
docker export container-id > imagename.tar

load an container:
cat imagename.tar | docker import – full/image/name:version

save image:
docker save full/image/name:version > imagename.tar

load an image:
sudo docker load < imagename.tar

━━━━━━━━━━━━━━━━━━
Docker containers

list:
docker ps -a

execute something within a container:
docker exec -it container-id /bin/bash

run detached:
docker run -d

docker run -it imagename /bin/bash (interacively start bash)

stop a container:
docker stop container-id

removing container
docker rm container-id

Detaching from a container and leave it running
Ctrl+p, Ctrl+q will now turn interactive mode into daemon mode.

Attach to a container
docker attach container-id

Connect inside a container
docker exec -it container-id /bin/bash

Automatically remove a container on exit
docker run –rm -it imagename /bin/bash

━━━━━━━━━━━━━━━━━━
Example Commands Explained

docker run -d -p 5901:5901 -v /etc/machine-id:/etc/machine-id fedora/firefox:version3

docker run -d(detaches the images bringing you back to the host machines command prompt after the container starts) -p(attaches the host ports to the image ports) -v(mounts the local machine ID to the container machine ID) runs a new container off of the image.

docker ps -a

docker ps(list containers and their information including the ID) -a(all)

docker exec -it a42c2a44b79f /bin/bash

docker exec(execute a command in a container) -i(interactive – Keep STDIN open even if not attached) -t(tty – Allocate a pseudo-TTY or a pty) container-id

docker stop a42c2a44b79f

docker stop(Stop the container. The container will be forced stoppeed within 10 seconds unless a delay is specified) container-id

docker rm a42c2a44b79f

docker rm(remove a container) container-id

Category: Linux | Comments Off on Linux: Docker cheat sheet
November 19

Linux: tmux shortcuts & cheatsheet

start new:

tmux

start new with session name:

tmux new -s myname

attach:

tmux a  #  (or at, or attach)

attach to named:

tmux a -t myname

list sessions:

tmux ls

kill session:

tmux kill-session -t myname

Kill all the tmux sessions:

tmux ls | grep : | cut -d. -f1 | awk '{print substr($1, 0, length($1)-1)}' | xargs kill

In tmux, hit the prefix ctrl+b (my modified prefix is ctrl+a) and then:
Sessions

:new<CR>  new session
s  list sessions
$  name session

Windows (tabs)

c  create window
w  list windows
n  next window
p  previous window
f  find window
,  name window
&  kill window

Panes (splits)

%  vertical split
"  horizontal split

o  swap panes
q  show pane numbers
x  kill pane
+  break pane into window (e.g. to select text by mouse to copy)
-  restore pane from window
⍽  space - toggle between layouts
<prefix> q (Show pane numbers, when the numbers show up type the key to goto that pane)
<prefix> { (Move the current pane left)
<prefix> } (Move the current pane right)
<prefix> z toggle pane zoom

Sync Panes

You can do this by switching to the appropriate window, typing your Tmux prefix (commonly Ctrl-B or Ctrl-A) and then a colon to bring up a Tmux command line, and typing:

:setw synchronize-panes

You can optionally add on or off to specify which state you want; otherwise the option is simply toggled. This option is specific to one window, so it won’t change the way your other sessions or windows operate. When you’re done, toggle it off again by repeating the command. tip source
Resizing Panes

You can also resize panes if you don’t like the layout defaults. I personally rarely need to do this, though it’s handy to know how. Here is the basic syntax to resize panes:

PREFIX : resize-pane -D (Resizes the current pane down)
PREFIX : resize-pane -U (Resizes the current pane upward)
PREFIX : resize-pane -L (Resizes the current pane left)
PREFIX : resize-pane -R (Resizes the current pane right)
PREFIX : resize-pane -D 20 (Resizes the current pane down by 20 cells)
PREFIX : resize-pane -U 20 (Resizes the current pane upward by 20 cells)
PREFIX : resize-pane -L 20 (Resizes the current pane left by 20 cells)
PREFIX : resize-pane -R 20 (Resizes the current pane right by 20 cells)
PREFIX : resize-pane -t 2 20 (Resizes the pane with the id of 2 down by 20 cells)
PREFIX : resize-pane -t -L 20 (Resizes the pane with the id of 2 left by 20 cells)

Copy mode:

Pressing PREFIX [ places us in Copy mode. We can then use our movement keys to move our cursor around the screen. By default, the arrow keys work. we set our configuration file to use Vim keys for moving between windows and resizing panes so we wouldn’t have to take our hands off the home row. tmux has a vi mode for working with the buffer as well. To enable it, add this line to .tmux.conf:

setw -g mode-keys vi

With this option set, we can use h, j, k, and l to move around our buffer.

To get out of Copy mode, we just press the ENTER key. Moving around one character at a time isn’t very efficient. Since we enabled vi mode, we can also use some other visible shortcuts to move around the buffer.

For example, we can use "w" to jump to the next word and "b" to jump back one word. And we can use "f", followed by any character, to jump to that character on the same line, and "F" to jump backwards on the line.

   Function                vi             emacs
   Back to indentation     ^              M-m
   Clear selection         Escape         C-g
   Copy selection          Enter          M-w
   Cursor down             j              Down
   Cursor left             h              Left
   Cursor right            l              Right
   Cursor to bottom line   L
   Cursor to middle line   M              M-r
   Cursor to top line      H              M-R
   Cursor up               k              Up
   Delete entire line      d              C-u
   Delete to end of line   D              C-k
   End of line             $              C-e
   Goto line               :              g
   Half page down          C-d            M-Down
   Half page up            C-u            M-Up
   Next page               C-f            Page down
   Next word               w              M-f
   Paste buffer            p              C-y
   Previous page           C-b            Page up
   Previous word           b              M-b
   Quit mode               q              Escape
   Scroll down             C-Down or J    C-Down
   Scroll up               C-Up or K      C-Up
   Search again            n              n
   Search backward         ?              C-r
   Search forward          /              C-s
   Start of line           0              C-a
   Start selection         Space          C-Space
   Transpose chars                        C-t

Misc

d  detach
t  big clock
?  list shortcuts
:  prompt

Configurations Options:

# Mouse support - set to on if you want to use the mouse
* setw -g mode-mouse off
* set -g mouse-select-pane off
* set -g mouse-resize-pane off
* set -g mouse-select-window off

# Set the default terminal mode to 256color mode
set -g default-terminal "screen-256color"

# enable activity alerts
setw -g monitor-activity on
set -g visual-activity on

# Center the window list
set -g status-justify centre

# Maximize and restore a pane
unbind Up bind Up new-window -d -n tmp \; swap-pane -s tmp.1 \; select-window -t tmp
unbind Down
bind Down last-window \; swap-pane -s tmp.1 \; kill-window -t tmp
Category: Linux | Comments Off on Linux: tmux shortcuts & cheatsheet
November 19

Linux: Screen Command

Getting in test
start a new screen session with session name 	screen -S <name>
list running sessions/screens 	screen -ls
attach to a running session 	screen -x
attach to session name 	screen -r <name>
the “ultimate attach” 	screen -dRR (Attaches to a screen session. If the session is attached elsewhere, detaches that other display. If no session exists, creates one. If multiple sessions exist, uses the first one.)
Escape key

All screen commands are prefixed by an escape key, by default C-a (that's Control-a, sometimes written ^a). To send a literal C-a to the programs in screen, use C-a a. This is useful when working with screen within screen. For example C-a a n will move screen to a new window on the screen within screen.
Getting out
detach 	C-a d
detach and logout (quick exit) 	C-a D D
exit screen 	C-a \ Exit all of the programs in screen. (not recommended)
force-exit screen 	C-a C-\ (not recommended)
getting out of the screen session 	exit
Window Management
create new window 	C-a c
change to last-visited active window 	C-a C-a (commonly used to flip-flop between two windows)
change to window by number 	C-a <number> (only for windows 0 to 9)
change to window by number or name 	C-a ' <number or title>
change to next window in list 	C-a n or C-a <space>
change to previous window in list 	C-a p or C-a <backspace>
see window list 	C-a " (allows you to select a window to change to)
show window bar 	C-a w (if you don't have window bar)
close current window 	Close all applications in the current window (including shell)
kill current window 	C-a k (not recommended)
kill all windows 	C-a \ (not recommended)
rename current window 	C-a A
Split screen
split display horizontally 	C-a S
split display vertically 	C-a | or C-a V (for the vanilla vertical screen patch)
jump to next display region 	C-a tab
remove current region 	C-a X
remove all regions but the current one 	C-a Q
Clipboard and Navigation
freely navigate buffer 	C-a [ or C-a <esc>
toggle selection to copy 	space
paste 	C-a ]
Help
See help 	C-a ? (lists keybindings)

The man page is the complete reference.
Scripting

To any session name,
send a command to a named session 	screen -S <name> -X <command>
create a new window and run ping example.com 	screen -S <name> -X screen ping example.com
stuff characters into the input buffer
using bash to expand a newline character
(from here) 	

screen -S <name> [-p <page>] -X stuff $'quit\r'

A full example:

# run bash within screen
screen -AmdS bash_shell bash
# run top within that bash session
screen -S bash_shell -p 0 -X stuff $'top\r'
 
# ... some time later
 
# stuff 'q' to tell top to quit
screen -S bash_shell -X stuff 'q'
# stuff 'exit\n' to exit bash session
screen -S bash_shell -X stuff $'exit\r'

Misc
redraw window 	C-a C-l
monitor window for activity 	C-a M
monitor window for silence 	C-a _
enter digraph (for producing non-ASCII characters) 	C-a C-v
lock (password protect) session 	C-a x
enter screen command 	C-a :
enable logging in the screen session 	C-a H
Scrollback-buffer

In copy mode, one can navigate the scrollback buffer in various ways:
half page up 	C-u 		half page down 	C-d
back 	C-b 		forward 	C-f
cursor left/down/up/right 	h/j/k/l 

Other Examples:
screen -AmdS bash_shell bash ; screen -S bash_shell -p 0 -X stuff $'yum update -y\r' ; screen -S bash_shell -p 0 -X stuff $'exit\r'
screen -AmdS bash_shell bash ; screen -S bash_shell -p 0 -X stuff $'yum update -y\r' ; screen -S bash_shell -p 0 -X stuff $'reboot\r'
Category: Linux | Comments Off on Linux: Screen Command