Month: January 2015

How to monitor network connections in Linux (using netstat and ss)

netstat displays network connections, routing tables, interface statistics, masquerade connections, and multicast memberships. On Linux, netstat (part of “net-tools”) is deprecated, ss@man (part of iproute2) should be used instead of netstat@man.

# output
'-n/--numeric' numerical addresses instead of trying to resolve to names
'-c/--continuous [delay]' print the selected information every second continuously
'-p/--program' Show the PID and name of the program to which each socket belongs

# filter by protocol and state
'-t' only tcp, '-u' only udp, '-w' only raw, '-x' only unix
'-l' only listening, '-a' all sockets

# show open sockets, default
$ netstat -a or ss -a

# show stats, '-s/--statistics [delay]'
$ netstat -s or ss -s

from 20 Netstat Commands for Linux Network Management

ss [ OPTIONS ] [ FILTER ]
'state|exclude [state]' where state is established|syn-sent|syn-recv|fin-wait-1|fin-wait-2|time-wait|closed|close-wait|last-ack|listen|closing|all|connected(all except listen and closed)|synchronized(connected states except syn-sent)
'dst|src prefix:port' filter by src/dst where both prefix and port are optional, e.g.: dst 10.0.0.1/32
'sport|dport >= :num' filter by port expression (>=,<=,=,!=), e.g.: dport != :22

# show all established HTTP connections
$ ss -o state established '( dport = :http or sport = :http )'
# find all local processes connected To X server
$ ss -x src /tmp/.X11-unix/*
# show all TCP sockets in state FIN-WAIT-1 for our httpd to network 10.0.0.0/8
$ ss -o state fin-wait-1 '( sport = :http or sport = :https )' dst 10.0.0.0/8

from SS Utility: Quick Intro and ss: Display Linux TCP / UDP Network and Socket Information
from TCP states

Advertisements

How to record/playback terminal in Linux (using scriptreplay, ttyrec, TermRecord, asciinema, showterm)

It is useful to be able to rapidly share computer activity with a screencast, by recording and playback TTY output of a text-mode program.

$ script -t 2> timingfile
# script started, file is typescript
$ ls
<etc, etc>
$ exit
# script done, file is typescript
$ scriptreplay timingfile
  • ttyrec/ttyplay is a program and/or its file format capable of recording the TTY output of a text-mode program together with timestamps and then replaying it. similar to the script command, but also allows for pausing, slowing down or speeding up playback. ttycast broadcast your ttyrec in real time.
$ ttyrec
# in the executed shell, do whatever you want and exit
$ ttyplay ttyrecord

$ npm install -g ttycast
$ ttyreccast outfile.tty
# open browser to 'http://localhost:13377/'
$ reset && ttyrec /tmp/ttycast
  • TermRecord@github saves your recording locally as a sel-contained html file and you can replay it in your browser.
$ pip install TermRecord
$ TermRecord -o /path/to/output_html
  • asciinema.org is a free and open source solution for recording the terminal sessions and sharing them on the web.
$ curl -sL https://asciinema.org/install | sh
$ asciinema rec
  • showterm.io variation of asciinema for replaying terminal sessions but this one is in pure text. It is both lightweight and the result is copy and pasteable.
$ gem install showterm
$ showterm 
# or if you have not installed showterm, you can run the standalone
$ bash <(curl record.showterm.io)
  • monitor recordings are uploaded to commands.com. You can also download the scripts (check the installation step).
$ curl commands.io/install-monitor-ubuntu
$ monitor -u myusername

How to do link aggregation (bonding and team) in Linux

Link aggregation applies to various methods of combining (aggregating) multiple network connections in parallel in order to increase throughput beyond what a single connection could sustain, and to provide redundancy in case one of the links should fail.

Bonding

The Linux bonding driver provides a method for aggregating multiple network interface controllers (NICs) into a single logical bonded interface of two or more so-called (NIC) slaves. The behavior of the single logical bonded interface depends upon its specified bonding driver mode. The default parameter is balance-rr:

  • Round-robin balance-rr/0: Transmit network packets in sequential order from the first available network interface (NIC) slave through the last. This mode provides load balancing and fault tolerance.
  • Active-backup active-backup/1: Only one NIC slave in the bond is active. A different slave becomes active if, and only if, the active slave fails. The single logical bonded interface’s MAC address is externally visible on only one NIC (port) to avoid distortion in the network switch. This mode provides fault tolerance.
  • … see Linux Ethernet Bonding Driver HOWTO for all options.
## bonding using ifcfg/rhel
# create ethernet channel bonding
$ cat /etc/sysconfig/network-scripts/ifcfg-{eth1,eth2}
....
MASTER=bond0
SLAVE=yes

# configure channel bonding interface mode=0 (balance-rr) or mode=1 (active-backup)
$ cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
ONBOOT=yes
IPADDR=192.168.246.130
NETMASK=255.255.255.0
# balance-rr
#BONDING_OPTS="mode=0 miimon=100"
# active-backup
BONDING_OPTS="mode=1 miimon=100"

# if your version of initscripts that desnt support 'BONDING_OPTS' use '/etc/modprobe.d/bonding.conf'
$ cat /etc/modprobe.d/bonding.conf
alias bond0 bonding
options bond0 mode=balance-rr miimon=100
# use '/etc/modprobe.d/bonding.conf' for non-interface specific options
$ cat /etc/modprobe.d/bonding.conf
options bonding max_bonds=1

$ modprobe -r bonding; modprobe bonding; service network restart
# if you get error, make sure bonding is loaded 'modprobe bonding'

# manually down/up slave to check bonding working
$ watch -n .1 cat /proc/net/bonding/bond0
$ ifconfig eth1 down

from bond@rhel6

## bonding in debian
$ sudo apt-get install ifenslave-2.6

# configure network interfaces
$ cat /etc/network/interfaces
auto eth0
iface eth0 inet manual
    bond-master bond0
    bond-primary eth0 eth1
auto eth1
iface eth1 inet manual
    bond-master bond0
    bond-primary eth0 eth1
auto bond0
iface bond0 inet dhcp
    bond-mode active-backup # or balance-rr
    bond-slaves none # we already defined the interfaces above with bond-master
    bond-miimon 100 # how often link state is sinspected for failures

# to verify bonding
$ watch -n .1 cat /proc/net/bonding/bond0
$ tail -f /var/log/messages
$ /etc/init.d/networking start

# if you get 'bonding: Warning: either miimon or arp_interval ...'
$ cat /etc/modprobe.d/aliases-bond.conf
alias bond0 bonding
options bonding mode=1 arp_interval=2000 arp_ip_target=192.168.3.1

from bonding@ubuntu and bonding@debian

## bonding using nmcli
# create 'bond0' connection
$ nmcli con add type bond con-name mybond0 ifname mybond0 mode active-backup
# add slave adaptors
$ nmcli con add type bond-slave ifname ens7 master mybond0
$ nmcli con add type bond-slave ifname ens3 master mybond0
# bring up slaves first, then bond
$ nmcli con up bond-slave-ens7
$ nmcli con up bond-slave-ens3
$ nmcli con up bond-mybond0
# view status
$ nmcli -p con show active

from bond@rhel7

Team

The Linux team driver provides an alternative to bonding driver. The main difference is that Team driver kernel part contains only essential code and the rest of the code (link validation, LACP implementation, decision making, etc.) is run in userspace as a part of teamd daemon. See libteam. Team daemon teamd supports a number of modes: called _runners:

  • broadcast: all packets are sent via all available ports
  • roundrobin: data is transmitted over all ports in turn
  • random: same as previous but transmit port is selected randomly for each outgoing
  • activebackup: one port or link is used while others are kept as a backup
  • loadbalance: uses a hash function to try to reach a perfect balance when selecting ports for packet transmission
  • … see libteam for all options
## installation
$ sudo yum install teamd

# convert bond to team
$ /usr/bin/bond2team --master bond0 --rename team0

## teaming using teamd
$ cp /usr/share/doc/teamd-*/example_configs/activebackup_ethtool_1.conf \ ~/activebackup_ethtool_1.conf
$ teamd -g -f activebackup_ethtool_1.conf -d
$ teamdctl team0 state
# add address to team interface
$ ip addr add 192.168.23.2/24 dev team0
$ ip addr show team0
$ ip link set dev team0 up
# terminate daemon and remove team0
$ teamd -t team0 -k

## teaming using teamdctl (teamd client)
# add 'em1' port from 'team0'
$ teamdctl team0 port add em1
# remove 'em1' port from 'team0'
$ teamdctl team0 port remove em1
# apply JSON config
$ teamdctl team0 port config update em1 '{"prio": -10, "sticky": true}'
# dump/view port config
$ teamdctl team0 port config dump em1

## teaming using ifcfg
$ cat /etc/sysconfig/network-scripts/ifcfg-team0
DEVICE=team0
DEVICETYPE=Team
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.11.1
PREFIX=24
TEAM_CONFIG='{"runner": {"name": "activebackup"}, "link_watch": {"name": "ethtool"}}'
$ cat /etc/sysconfig/network-scripts/ifcfg-eno{1,2}
...
DEVICETYPE=TeamPort
TEAM_MASTER=team0
TEAM_PORT_CONFIG='{"prio": 100}' # -MAXINT..MAXINT, defaults to 0
$ ifup team0
$ ip link show

## temming using teamnl/iputils
# add port/enslave
$ ip link set dev em1 down
$ ip link set dev em1 master team0
# set team options
$ teamnl team0 setoption mode activebackup
# show team ports
$ teamnl team0 ports
# add team address
$ ip addr add 192.168.252.2/24 dev team0
# bring up team
$ ip link set team0 up
# show active ports
$ teamnl team0 getoption activeport

## teaming using nmcli
# create team interface and add ports/slaves
$ nmcli con add type team con-name team0 ifname team0 config '{"runner":{"name":"activebackup"}'
$ nmcli con add type team-slave con-name team0-port1 ifname eno1 master team0
$ nmcli con add type team-slave con-name team0-port1 ifname eno2 master team0
$ nmcli con show
# assign IP address to team and enable connection
$ nmcli con mod team0 ipv4.addresses "192.168.1.24/24 192.168.1.1"
$ nmcli con mod team0 ipv4.method manual
$ nmcli con up team0
$ teamdctl team0 state

from teaming@rhel7

How to enable automatic updates in Linux (Fedora/Centos, Debian/Ubuntu and Arch)

Following the unix way, “everything is scriptable, whether the author intended it to be or not” and “anything should be possible to be automated” here is a way to automatically update a few Linus distros.

$ sudo yum install yum-cron

## el6
$ cat /etc/sysconfig/yum-cron
CHECK_ONLY=no
DOWNLOAD_ONLY=no
$ service start yum-cron
$ chkconfig yum-cron on

## el7
$ cat /etc/yum/yum-cron.conf
download_updates = yes
apply_updates = yes
emit_via = stdio
$ systemctl start yum-cron.service
$ systemctl enable yum-cron.service

$ tail -f /var/log/yum.log

from automatic-updates in centos6 and automatic-updates in centos7

$ sudo apt-get install unattended-upgrades

## using 20auto-upgrades
$ sudo dpkg-reconfigure -plow unattended-upgrades
$ cat /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

## or using 02periodic,10periodic
$ cat /etc/apt/apt.conf.d/02periodic
// Enable the update/upgrade script (0=disable)
APT::Periodic::Enable "1";
// Do "apt-get update" automatically every n-days (0=disable)
APT::Periodic::Update-Package-Lists "1";
// Do "apt-get upgrade --download-only" every n-days (0=disable)
APT::Periodic::Download-Upgradeable-Packages "1";
// Run the "unattended-upgrade" security upgrade script every n-days (0=disabled)
APT::Periodic::Unattended-Upgrade "1";
// Do "apt-get autoclean" every n-days (0=disable)
APT::Periodic::AutocleanInterval "5";

$ service unattended-upgrades start
$ tail -f /var/log/apt/history.log /var/log/unattended-upgrades/*

from automatic-updates in debian

  • pacman@arch doing automatic updates from cron is strongly discouraged. It is likely to leave your machine in a broken and unbootable state.
'-S, --sync' synchronize packages, they are installed directly from the remote repositories, including all dependencies
'-u, --sysupgrade' upgrades all packages that are out-of-date
'-y, --refresh' download fresh copy of package list
'-w, --downloadonly' retrieve all packages from the server, but do not install/upgrade anything
'-q, --quiet'

$ yes | pacman -Syuq
# or download only
$ yes | pacman -Syuwq

## in cron
$ cat /etc/cron.daily/pacman-update
#!/bin/bash
yes | pacman -Syuwq

## in systemd timers 
$ cat /etc/systemd/system/pacman-update.service
[Unit]
Description=Pacman update
[Service]
Type=oneshot
ExecStart=/usr/bin/yes | /usr/bin/pacman/pacman -Syuwq
$ cat /etc/systemd/system/pacman-update.timer
[Unit]
Description=Run pacman update daily
[Timer]
OnBootSec=10min
OnUnitActiveSec=1d
[Install]
WantedBy=timers.target

from Update packages from crontab@arch

How to syncronize time in Linux (using ntp, openntpd, systemd-timesyncd and chrony)

Network Time Protocol (NTP) is a networking protocol for clock synchronization between computer systems over packet-switched, variable-latency data networks. The protocol is usually described in terms of a client-server model, but can as easily be used in peer-to-peer relationships where both peers consider the other to be a potential time source. There are a number of implementations.

  • ntpd@man deamon implementation of NTP which sets and maintains the system time of day in synchronism with Internet standard time servers.
## install
$ sudo yum install ntp | sudo apt-get install ntp

## configure NTP server, add servers from http://www.pool.ntp.org/en/
$ cat /etc/ntp.conf
server 0.north-america.pool.ntp.org
server 1.north-america.pool.ntp.org
server 2.north-america.pool.ntp.org
server 3.north-america.pool.ntp.org 

## start service
$(el7) systemctl start ntpd ; systemctl enable ntpd ; sytemctl status ntp
$(el6) service ntpd start ; chkconfig ntpd on
$(deb) /etc/init.d/ntp start

## check logs '/var/log/ntp.log', verify date
$ ntpq -p ; date -R

## manually sync
$ ntpdate -u 0.north-america.pool.ntp.org

from ntp@centos and ntp@debian

  • OpenNTPD/OpenNTPD@wiki is an attempt by the OpenBSD team to produce an NTP daemon implementation that is secure, simple to security audit, trivial to set up and administer, and has small memory requirement that synchronizes local clock on the computer with remote NTP server with reasonable accuracy. It’s an alternative to default default NTPD client/server.
## install (from source)
$ wget ftp://ftp.openbsd.org/pub/OpenBSD/OpenNTPD/openntpd-3.9p1.tar.gz -O - | tar -xz
$ cd $1 ; ./configure ; make ; sudo make install
$ groupadd _ntp
$ useradd -g _ntp -s /sbin/nologin -d /var/empty -c 'OpenNTP daemon' _ntp
$ cp contrib/redhat/ntpd /etc/init.d/openntpd
$ chmod +x /etc/init.d/openntpd
$ cat /etc/init.d/openntpd
PATH=/usr/local/sbin:$PATH

## or install (from repo)
$ sudo apt-get install openntpd (deb/ubuntu)

## configure
$ cat /usr/local/etc/ntpd.conf
listen on 127.0.0.1
...
server ntp.isp.example.com
# Use a random selection of 8 public stratum 2 servers
servers pool.ntp.org
$ chkconfig openntpd on ; service openntpd start
$ tail -f /var/log/messages
$ netstat -tulpn | grep :123

from CentOS / Redhat Linux: Install OpenNTPD To Synchronize The Local Clock

  • systemd-timesyncd is a daemon that has been added for synchronizing the system clock across the network. It implements an SNTP client. In contrast to NTP implementations such as chrony or the NTP reference server this only implements a client side, and does not bother with the full NTP complexity.
## systemd-timesyncd service is available with systemd >= 213 (el7 uses 208), to start and enable it
$ timedatectl set-ntp true

## configuration
# to add time servers or change the provided ones, uncomment the relevant line and list their host name or IP separated by a space
$ cat /etc/systemd/timesyncd.conf
[Time]
NTP=0.arch.pool.ntp.org 1.arch.pool.ntp.org 2.arch.pool.ntp.org 3.arch.pool.ntp.org
FallbackNTP=0.pool.ntp.org 1.pool.ntp.org 0.fr.pool.ntp.org

from systemd-timesyncd@arch

  • chrony@arch is an alternative NTP client and server roaming friendly and designed specifically for systems that are not online all the time.
## install
$ sudo yum install chrony | sydo apt-get install chrony

## configure
'offline' only poll when chronyc is online
'auto_offline' assume server gone offline when 2 requests without reply
'iburst' on start make four measurements over short period (rather than the usual periodic measurements)
'minstratum' increase stratum of the source to a minimum, to avoid being selected; chronyd preferes lower stratum sources
'polltarget' num of measurements used in regression algorithm; higher target means shorter polling intervals
'prefer' prefer this source over sources without prefer option.
'noselect' never select this source

$ cat /etc/chrony.conf
server 1.2.3.4 offline
server 5.6.7.8 offline
server 9.10.11.12 offline
driftfile /etc/chrony.drift
keyfile /etc/chrony.keys
generatecommandkey
commandkey 1
rtconutc
rtcsync
$ systemctl restart chronyd

# show current sources
$ chronyc sources -v
# show rate and offset estimation performance of sources
$ chronyc sourcestats
# show system clock performance
$ chronyc tracking
# set offline/activity; also done automatically by 'networkmanager-dispatcher-chrony' or 'netctl-dispatcher-chrony'
$ chronyc -a activity

from Maintaining System clock using chrony

How to change bash prompt (using PS1, git-prompt.sh, liquid-prompt, bash-it and powerline)

PS: prompt statement: PS1 default, PS2 continuation, PS3 select shell scripts, PS4 "set-x" prefix
PROMPT_COMMAND: executes the content of the PROMPT_COMMAND just before displaying the PS1 variable
see http://www.thegeekstuff.com/2008/09/bash-shell-take-control-of-ps1-ps2-ps3-ps4-and-prompt_command/
PS1 shoud be set in {~/.basrc,/etc/bashrc} because non-interactive bashes go out of their way to unset PS1

# display username \u, hostname \h, FQDN \H, current working directory \w and basename of cwd \W
PS1="\u@\h \w\$"

# display time in 24h format \t, in 12h format \T in am/pm format \@ and date \D{format} in strftime(3)
PS1="\u@\h [\t]$" 

# display command output \$(cmd) or `cmd`, history number \!, last command status \$?, env variable $var
PS1="\! \h \$(uname -r) \$?$" 

# change foreground color \e[x;ym $PS1 \e[m where \e[ is start color scheme, x;y is color pair and \e[m is stop color scheme
PS1="\e[0;31m[\u@\h \W]\$ \e[m $"
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
# change to 1 for bold and 4 for underline

# change background color \e[{code}m
PS1="\e[47m\u@\h \w> \e[m"
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
bakgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# change the prompt color using 'tput setab|setb|setaf|setf' background|foreground and 'tput bold|dim|smul|rmul|rev' bold|dim|underline|reverse
PS1="\[$(tput bold)$(tput setb 4)$(tput setaf 7)\]\u@\h:\w $ \[$(tput sgr0)\]"

# positioning the cursor \[33[;f\], save cursor position \[33[s\], restore \[33[u\]
PS1=">\[33[s\]\[33[1;\$((COLUMNS-4))f\]\$(date +%H:%M)\[33[u\]"

# rhel default
PS1="[\u@\h \W]\\$ "
# ubuntu default
PS1="\u@\h:\W\\$ "
# see https://www.kirsle.net/wizards/ps1.html

from ColorBashPrompt@arch, examples@thegeekstuff and ColorBashPrompt@cyberciti

# add git prompt
$ cat ~/.bashrc
. /usr/lib/git-core/git-sh-prompt
export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

# by defaults only shows current branch name
GIT_PS1_SHOWDIRTYSTATE show unstaged '*' and staged '+' changes 
GIT_PS1_SHOWSTASHSTATE show '$' if something is stashed
GIT_PS1_SHOWUNTRACKEDFILES shows '%' if untracked files
GIT_PS1_SHOWUPSTREAM="auto" shows '','','=' if behind/ahead/diverged/nodiff
GIT_PS1_SHOWUPSTREAM="verbose name" show number of commits ahead/behind (+/-) upstream, and upstream name

from git-prompt.sh

  • liquidprompt@github is an adaptive, smart prompt for Bash and Zsh. It can display various useful information on the shell prompt, only when it's needed.
## install
$ git clone https://github.com/nojhan/liquidprompt.git ~/.liquidprompt
$ cp ~/.liquidprompt/liquidpromptrc-dist ~/.config/liquidpromptrc
$ cat ~/.bashrc
. ~/.liquidprompt/liquidprompt

## usage ~/.config/liquidpromptrc
LP_PS1_PREFIX/LP_PS1_POSTFIX adds prefix/suffix, 'prompt_tag MYTAG' is same as 'LP_PS1_PREFIX'
LP_PS1/LP_PS1_FILE rearranging the prompt, see ~/.liquidprompt/liquid.ps1
LP_ENABLE_XXX enable a feature, e.g.: LP_ENABLE_TIME, LP_ENABLE_RUNTIME 
LP_HOSTNAME_ALWAYS/LP_USER_ALWAYS display if differs from current
'prompt_off/prompt_on' temporally disable/enable

# branch_name(+lines_added/-lines_removed,pending_commits)
# branch_name in green if up-to-date, red if changes, yellow if pending commits to push
# yellow '+' if shashed modification, red '*' if untracked files
[me:~/gitrepo] master(+1/-2)*

## uninstall
# remove '. ~/.liquidprompt/liquidprompt' from '~/.bashrc'
$ rm -rf ~/.config/liquidpromptrc ~/.liquidprompt

from liquid-prompt@ubuntu

  • bash-it@github is a mash up of my own bash commands and scripts, other bash stuff I have found. A shameless ripoff of oh-my-zsh.
## install
$ sudo pip install argcomplete
$ git clone https://github.com/revans/bash-it.git ~/.bash_it
$ cp ~/.bash_profile{,.bak}
$ ~/.bash_it/install.sh
$ for pg in chruby chruby-auto postgres z; do bash-it disable plugin $pg; done
$ . ~/.bash_profile

## enable theme, see https://github.com/revans/bash-it/wiki/Themes
$ cat ~/.bash_profile
# location ~/.bash_it/themes/
export BASH_IT_THEME='bobby'
$ reload

## uninstall
$ cp ~/.bash_profile{.bak,}
$ rm -rf ~/.bash_it ~/.bash_profile.bak
  • powerline@github is a statusline plugin for vim, and provides statuslines and prompts for several other applications, including zsh, bash, tmux, vim …
## install
$ sudo apt-get install powerline (14.10 very old)
or
$ sudo apt-get install python-pip git
$ sudo pip install git+git://github.com/Lokaltog/powerline

# install fonts
$ sudo wget -q https://github.com/Lokaltog/powerline/raw/develop/font/PowerlineSymbols.otf -O /usr/share/fonts/PowerlineSymbols.otf
$ sudo fc-cache -vf
$ sudo wget -q https://github.com/Lokaltog/powerline/raw/develop/font/10-powerline-symbols.conf -O /etc/fonts/conf.d/10-powerline-symbols.conf
# restart all terms

# if you get "coercing to Unicode" then see https://github.com/powerline/powerline/issues/835 and
$ cd /usr/lib/python2.7/dist-packages/
$ sudo wget -q https://github.com/powerline/powerline/commit/ecf26dfbc65e0c39001e8283e776c50899f90e1b.patch
$ sudo patch -p1 < *.patch

## usage
# ~/.{bash,zsh}rc or /etc/{bash.bashrc,zsh/zshrc}
export POWERLINE=/usr/local/lib/python2.7/dist-packages/powerline
if [ -f $POWERLINE/bindings/{bash,zsh}/powerline.sh ]; then
    source $POWERLINE/bindings/{bash,zsh}/powerline.sh
fi
# ~/.tmux.conf
export POWERLINE=/usr/lib/python2.7/dist-packages/powerline
source $POWERLINE/bindings/tmux/powerline.conf
set-option -g default-terminal "screen-256color"
# ~/.vimrc or /etc/vim/vimrc
set rtp+=/usr/local/lib/python2.7/dist-packages/powerline/bindings/vim/
" Always show statusline
set laststatus=2
" Use 256 colours (Use this setting only if your terminal supports 256 colours)
set t_Co=256

## configuration
mkdir ~/.config/powerline
cp -R $POWERLINE/config_files/* ~/.config/powerline
# bash doesnt support right segments, so edit ~/.config/powerline/config.json
    "theme": "default_leftonly"
# add hostname to prompt, edit ~/.config/powerline/themes/shell/{default,_leftonly}.json
    "only_if_ssh": false

## uninstall
$ sudo pip uninstall powerline
or
$ sudo rm -rf /usr/local/bin/powerline* /usr/local/lib/python2.7/dist-packages/powerline ~/.config/powerline

from docs and powerline@ubuntu

How to control media player from CLI using D-Bus/MPRIS

  • MPRIS is a standard dbus interface for programmatic control media players any media player
## install
$ sudo apt-get install qtchooser

## using (clementine)
$ show information about the currently playing song
$ qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata
# same but v2
$ qdbus org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadata
# show all mpris players running
$ qdbus org.mpris.MediaPlayer2.*

# control player
$ qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.Pause
$ qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.VolumeSet 50

from MPRIS@clementine

## install
$ sudo apt-get install mpris-remote

## using
# uses that first media player or MPRIS_REMOTE_PLAYER env
$ mpris-remote identity
# shows current player status, song playing
$ mpris-remote
# shows current track info tags
$ mpris-remote trackinfo
# shows corrent player status
$ mpris-remote playstatus

# control player and volume
$ mpris-remote prev|next|play|stop|pause
$ mpris-remote volume 

# populates current playlist
$ mpris-remote clear
$ find ~/music -name '*.mp3' | mpris-remote addtrack -

# eg: bash prompt with media info
function mpris { echo `{ mpris-remote trackinfo && mpris-remote playstatus; } | sed -n -r 's,'$1': (.*),\1,p'`; }
export PS1_old="$PS1"
export PS1="\$(mpris playing) \$(mpris title)\n$PS1_old"