Linux and Unix How To

How to install Kcmsystemd on Kubuntu 15.04


Get the prerequisites:

sudo apt-get install libkf5i18n-dev libkf5configwidgets-dev libkf5coreaddons-dev libkf5service-dev
sudo apt-get install cmake extra-cmake-modules qt5-default libsystemd-dev
sudo apt-get install libboost-dev libboost-filesystem-dev libboost-system-dev libboost-chrono-dev

Get the code and compile:

git clone ''https://github.com/rthomsen/kcmsystemd.git''
cd kcmsystemd
mkdir build
cd build
cmake -DQT_PLUGIN_INSTALL_DIR=/usr/lib/x86_64-linux-gnu/qt5/plugins/ -DCMAKE_INSTALL_PREFIX=/usr ..
make
sudo make install

You could instead add /usr/lib/x86_64-linux-gnu/plugins/ to $QT_PLUGIN_PATH. Use

kcmshell5 kcm_systemd

or

systemsettings5

Then click on systemd

How to convert uptime based timestamp into normal time


Substitute uptime-tick-value with a number of seconds.microseconds elapsed since boot time, e.g what dmesg shows by default

date -d "70-1-1 + $(date +%s) sec - $(cut -d ' ' -f1 < /proc/uptime) sec + ''uptime-tick-value'' sec UTC" +"%F %T"

How to list packages installed from a given ppa or a deb repository


  1. First find name of the repository in /var/lib/apt/lists/
  2. Then run this

awk '$1 == "Package:" { print $2 }' /var/lib/apt/lists/''repo'' ''name''

How to remove everything from a ppa


Remove the PPA, downgrading gracefully packages it provided to packages provided by official repositories:

sudo ppa-purge ppa:name/ppa

Downgrade a package


Find available versions

apt-cache showpkg <package-name>

Then run the downgrade command

sudo apt-get install <package-name>=<package-version-number>

You might also want to hold the package at the needed version

apt-mark hold <package-name>

How to add more sensors on a Gigabyte Z97X-UD5H motherboard


Gigabyte runs the IT8620E sensors (from googling and here). You can either load the generic driver by forcing its compatibility or build the latest driver. To use generic

sudo modprobe it87 force_id=0x8728

If that works, make it permanent by

echo "options it87 force_id=0x8728" | sudo tee /etc/modprobe.d/it87.conf
echo "it87" | sudo tee -a /etc/modules

To compile the latest driver that supports the sensors out of the box do this:

git clone ''https://github.com/groeck/it87.git''
cd it87
make
sudo make install (that copies it into /lib/modules/$(uname -r)/)

How to change NVIDIA fan speed


There are two ways to do it - natively and through nvclock third party tool.

NVClock: Get it with apt-get and run

/usr/bin/nvclock -f -F 60 &

If that works add it to /etc/X11/Xsession.d/ and chmod the script to 644 (it's sourced, not run). It may not work with SDDM, so you could hack it in by adding this line to the beginning of /usr/share/sddm/scripts/Xsetup

Nvidia-settings: First enable the control the fan speed to the /etc/X11/xorg.conf. Under the Device section add

Option "Coolbits" "12"

You can then change it through the nvidia-settings GUI, or with a command line.

nvidia-settings -a "[gpu:0]/GPUFanControlState=1" -a "[fan:0]/GPUCurrentFanSpeed=''speed'' ''percent'' ''from'' ''0'' ''to'' ''100''" &

To make the change automatically apply after a user is logged in create /etc/X11/Xsession.d/95nvidia-fan with the following contents:

#!/bin/sh
/usr/bin/nvidia-settings -a "[gpu:0]/GPUFanControlState=1" -a "[fan:0]/GPUCurrentFanSpeed=''60''" &

Change the access mask to chmod 644 (that's right, not executable like 755).

How to make "send to" command for shotwell work under KDE with thunderbird


Create the following script in /usr/local/bin/nautilus-sendto and make it executable (chmod 755)

#!/bin/bash
attach="attachment='"
for file in "$@"; do
     attach+="$(readlink -f "$file"),"
done
thunderbird -compose "${attach%?}'"

How to improve speed and security while potentially sacrificing usability of Unity/Gnome


Remove Gnome/Unity Zeitgeist - the activity tracker that knows which files you opened when and what you click etc. It could be present on KDE if you've installed GTK packages that depend on it. The last three are example packages that depend on zeitgeist

sudo aptitude purge zeitgeist zeitgeist-core libzeitgeist-1.0-1 zeitgeist-datahub nautilus nautilus-sendto dockmanager

How to get CPU info


cat /proc/cpuinfo

or

lscpu

or

cat /var/log/dmesg | grep "MHz processor"

How to print a test page from a command line


Find your testpage and run lpr:

locate testpage
lpr -P [printer] /usr/share/cups/data/default-testpage.pdf

How to manipulate KDE clipboard from a command line


Read

qdbus org.kde.klipper /klipper getClipboardContents

Write

#  run with echo "foobar" | ./clipboard''
if ! tty -s && stdin=$(''''</dev/stdin) && [[ "$stdin" ]]; then
	 stdin=$stdin$'\n'$(cat)
	 qdbus org.kde.klipper /klipper setClipboardContents "$stdin"
 fi

How to find which dpkg package contains a given file

Get the apt-file tool and update it's cache
sudo apt-get install apt-file
sudo apt-file update
Then search
apt-file search /path/to/file

How to check if you are inside a chroot container

inode # for real / is always 2, otherwise it's some other number
stat -c %i /
or
ls -id /

How to configure sane and xsane for remote network scanner access

On the server with the scanner attached, edit /etc/default/saned:
sudo vi /etc/default/saned
Set
RUN=yes
Add your network mask somewhere in that file. For your normal home network it will be 192.168.1.0/24:
192.168.1.0/24
Make sure saned user has the correct permissions to access the scanner device:
sudo adduser saned scanner
sudo adduser saned lp
Then
sudo service saned restart
If the server does not start on boot you migh need "sudo update-rc.d saned defaults"
Test
sudo -su saned
scanimage -L

On the client
vi /etc/sane.d/net.conf
And add the name or the IP of the server. Then test by running xsane or skanlite

How to add another resolution mode and set it in KDE after wake up from sleep

Sometimes KDE forgets the mode, or messes up resolutions on wake up. Here is how to fix it, from an example of DFP1 as the output device and the 3840x1200 being the problematic mode.

  • Set up the screens to work properly using "display" system setting.
  • Get the xrandr command line that it stores the settings in from the top of ~/.kde/share/config/krandrrc
  • Get the active resolution mode

xrandr -q | grep +

  • Convert the settings into a modeline using Coordinated Video Timings (CVT)

cvt 3840 1200 59.9
For reference: you could also try conversion using Generalized Timing Formula (GTF), which was a standard used before CVT
gtf 3840 1200 59.9

  • Create a bash script, based on the collected information:

<source lang="bash">''

  1. !/bin/bash

devconnected=$(xrandr -q | grep "DFP1 connected" > /dev/null ; echo $?)
if [ $devconnected == '0' ] ; then
# Add the mode from the modeline
xrandr --newmode "3840x1200_59.90"  385.67  3840 4096 4512 5184  1200 1201 1204 1242  -HSync +Vsync
xrandr --addmode DFP1 "3840x1200_59.90"
# Your xrandr commands from krandrrc here:
xrandr --output LVDS --pos 3840x0 --mode 1680x1050 --refresh 59.8833
xrandr --output DFP1 --pos 0x0 --mode 3840x1200 --refresh 59.8785
xrandr --output DFP1 --primary
# restart plasma (bug #260360, may not be necessary in the latest KDE)
killall plasma-desktop
sleep 2
plasma-desktop &

fi

</source>

  • Now do the sleep/wake cycle or break your screen some other way, so it's missing needed resolution mode. Run the script with DFP1 as the argument to make sure it works. If you still experience issues sure that the new mode can fit within the maximum framebuffer size

xrandr | grep maximum

  • Add the script to be run when KDE starts using system-settings.

How to set shutter as a default screen capture for KDE


In system settings, shortcuts and gestures, custom shortcuts expand preset actions, printscreen and set its action to "shutter --full"

How to automatically add a CUPS printer when system boots


If your printer is disappearing after reboot first try to edit /etc/cups/printer.conf while cupsd is running, contrary to the comments inside that file. Reboot and test. If that did not work then add teh following to the /etc/rc.local

/usr/sbin/lpadmin -p Your-printer-name -E -v ipps://printer-server/printers/PRINTER-QUEUE-NAME
/usr/sbin/lpadmin -d Your-printer-name

How to read a PST mailbox with Thunderbird


Get the tool

sudo apt-get install readpst

Convert the PST, keeping deleted messages

mkdir pstmailfolder; readpst -D -o pstmailfolder <yourmailbox.pst>

Create the proper folder structure and copy the converted mailbox:

touch ~/.thunderbird/''random'' ''string''.default/Mail/Local Folders/pstmailfolder;
mkdir ~/.thunderbird/''random'' ''string''.default/Mail/Local Folders/pstmailfolder.sbd;
cp pstmailfolder/* ~/.tunderbird/''random'' ''string''.default/Mail/Local Folders/pstmailfolder.sbd/

Where random string is your Thunderbird profile identifier. Restart Thunderbird

How to prevent kernel upgrades in Ubuntu


So you have a custom kernel build and do not want to get the stock kernels since the update would require fixing the grub menu and reinstalling video drivers. Do the following to hide kernel updates in Ubuntu. First, get the installed stock kernel version:

dpkg -l | grep linux-generic

It will show you something like this:

ii  linux-generic                                 ''3.2.0.26.28''                             Complete Generic Linux kernel

The number part is your version. Now create the /etc/apt/preferences file and put the following in there:

Package: linux-generic linux-headers-generic linux-image-generic linux-restricted-modules-generic
Pin: version ''3.2.0.26.28''
Pin-Priority: 1001

Use your version number, of course. This will pin the stock kernel version to the one you already have and prevent any updates from the Ubuntu repository.

How to add a PDF printer that allows naming a file, choosing location and shows a preview

I found Windows is quite good at it and wanted to mimic it in Linux. Some call it a heresy, I call it creative borrowing. Start by installing cups pdf printer: sudo aptitude install cups-pdf Add the PDF printer via
kcmshell4 system-config-printer-kde
or
system-config-printer
Use default (recommeded) drivers. Get the following scripts and save them to /home/user/bin. The scripts rely on kdialog from KDE. You could switch it for zenity from Gnome per comments inside.

KDialog is a bit needy, and will not work unless you craft the environment for it. To make kdialog work from a foreign shell, find the DBUS address, export it out in a variable, along with DISPLAY, XAUTHORITY and HOME. No such nonsence for zenity.

#!/bin/bash
CURRENT_PDF="$1"
CURRENT_USER="$2"

export DISPLAY=:0
export XAUTHORITY=/home/${CURRENT_USER}/.Xauthority
export HOME=/home/${CURRENT_USER}/
CONFIG_FILE="/home/${CURRENT_USER}/.pdf-writer.conf"
CANCELLED="No"

export $(cat /proc/$(pgrep "kded4" -u "${CURRENT_USER}")/environ | grep -z "^DBUS_SESSION_BUS_ADDRESS=")

while [ True ]; do
    CURDATE=$(/bin/date +%Y%m%d)
    CURNAME=$(/bin/cat "$CONFIG_FILE")
    BASENAME=$(basename $CURRENT_PDF)
    #FILENAME=$(/usr/bin/zenity --file-selection --save --confirm-overwrite --title="Save PDF" --filename="$CURNAME$CURDATE - " --file-filter="*.pdf")
    FILENAME=$(/usr/bin/kdialog --getsavefilename "$CURNAME$CURDATE - " "*.pdf" --title="Save PDF")
    if [ $? -eq 1 ]; then
        CANCELLED="Yes"
        break
    fi
    echo $FILENAME
    if [ ! "$FILENAME" = "" ]; then
        if [ -e "$FILENAME" ]; then
            /usr/bin/kdialog --warningcontinuecancel "File already exists"
            if [ $? -eq 1 ]; then
                continue;
            fi
        fi
        FILENAME=$(echo $FILENAME.pdf | sed -re "s/(\.pdf)+$/.pdf/g")
        break;
    else
        #/usr/bin/zenity --error --text "You must select a file or Cancel"
        /usr/bin/kdialog --error "You must select a file or hit cancel. No mocking around."
    fi
    break
done

if [ "${CANCELLED}" == "No" ]; then
    /bin/cp "${CURRENT_PDF}" "${FILENAME}"
    #evince "${FILENAME}" &
    okular "${FILENAME}" & #--geometry 1500x1000 "${FILENAME}" & # fighting an odd maximization of the window
fi
/bin/rm "${CURRENT_PDF}"
exit 0

Make the scripts executable. Specify the folder name where PDFs shall go by default (for example /home/user/Documents):

echo /home/[user]/[folder] > ~/.pdf-writer.conf

Edit /etc/cups/cups-pdf.conf and change the PostProcessing line to read

PostProcessing /home/[user]/bin/pdfpostproc.sh

While I was there I changed the "Out" directory to {HOME}/Temp. I just hate extraneous home root folders. Tidy it should be, my friend.

Now, cupsd is apparmor protected. So, to make it all go nicely with the linux security system edit /etc/apparmor.d/usr.sbin.cupsd. Add the following line to the end, before the closing curly bracket:

@{HOME}/bin/pdfpostproc.sh rUx,

If you changed the default cups folder than change the lines that reads

@{HOME}/PDF/ rw,
@{HOME}/PDF/* rw,

To

@{HOME}/Temp/ rw,
@{HOME}/Temp/* rw,

Restart cupsd and app armor.

sudo systemctl restart cups
sudo systemctl restart apparmor

or

sudo service cups restart
sudo service apparmor restart

Try printing and enjoy.

How to roll back to a stable version with aptitude aka How to downgrade a package


If you got it from a PPA that you need to disable, use ubuntu-tweak.

  • Open Ubuntu Tweak, and select Package Cleaner in the list on the left.
  • Click on the Purge PPAs button near the right.
  • Select the PPA in question and click apply. You'll be prompted to downgrade related packages

To do it manually, first find the version you want to use:

sudo apt-cache showpkg ''<pkg>''

Then install the version you need:

sudo aptitude install ''<pkg>''=''<version>''

How to enable or disable KDE compositing from the command line


export DISPLAY=:0.0
qdbus org.kde.kwin /KWin org.kde.KWin.toggleCompositing

How to reinforce directory and file access limits


find . -perm /077 -type d -exec chmod -v 700 {} \;
find . -perm /077 -type f -exec chmod -v o-rwx,g-rwx {} \;

How to change system wide umask to the most secure one


For new versions of ubuntu (12.04+) edit /etc/pam.d/login and add

session optional pam_umask.so umask=0077

For everything else edit /etc/profile as root and set

umask 0077

For a personal umask edit ~/.profile

How to cp (copy) in a command line with a progress indicator


rsync -Pacz ''source'' ''destination''

This will copy the metadata as well. If you want it to use the new date/time/owner, just like cp does, run the following. Note though that running this twice will copy the files twice unless you add the -c switch for checksumming files.

rsync -ghop --progress ''source'' ''destination''

How to attach a console/stdout to an already running process


First find out what your console device is

tty

Then connect to the process and modify it's handles

gdb -p `pgrep ''processname''`
p dup2(open("/dev/pts/3",1),0)
p dup2(open("/dev/pts/3",1),1)
p dup2(open("/dev/pts/3",1),2)
quit

Where /dev/pts/3 is the name of your stdout device. To check where a running process is sending it's redirects run

ls -al /proc/`pgrep ''processname''`/fd

How to make an already running job survive a logout


Ctrl-Z to suspend it, then type

bg

to make it a background job. Then type

disown -a

to make it ignore SIGHUP signals sent on a shell logout (similar to nohup)

How to check Ubuntu version


lsb_release -a

How to install OpenCV 2.0 on Ubuntu 9.10 Karmic Koala


OpenCV is a widely used computer vision library for research and development. I've tried using instructions for installing it from the official manual, but it failed miserably. It seems that 2.0 code is incompatible with the latest incarnation of ffmpeg. Couple minutes in googling and I had it working.

UPDATE The following process describes building the latest stable version from the sources. There is an easier way tin install it by using a third-party repository. Configure it in with add-apt-repo and install.

Here is what needs to be done if you want to build OpenCV from sources:

Get all the prerequisites:

sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg62-dev libtiff4-dev
sudo apt-get build-dep libswscale-dev swig

Get OpenCV 2.0, and unpack it somewhere.

Fix ffmpeg links. Make sure you are root (sudo -s) and do the following:

mkdir /usr/include/ffmpeg
ln -s /usr/include/libavcodec/avcodec.h /usr/include/ffmpeg/avcodec.h
ln -s /usr/include/libavformat/avformat.h /usr/include/ffmpeg/avformat.h
ln -s /usr/include/libavformat/avio.h /usr/include/ffmpeg/avio.h
ln -s /usr/include/libavutil/avutil.h /usr/include/ffmpeg/avutil.h

Configure OpenCV. In the folder you've unpacked it to run:

./configure --prefix=/usr/local/opencv --enable-apps --enable-shared --enable-swscale --enable-gpl --with-swig
sudo ln -s /usr/include/libswscale/swscale.h /usr/include/ffmpeg/swscale.h

Make and install it:

make
sudo make installYou could also test it by running make test

Configure your system to look for opencv libraries:

echo /usr/local/opencv/lib > /etc/ld.so.conf.d/opencv.confReload the libraries and make sure opencv shows up now
ldconfig -v | grep opencvYou may get warnings on unaccessible lib paths, that is ok. You are looking for a line that says "/usr/local/opencv/lib"

Set-up pkg-config:

echo 'export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/opencv/lib/pkgconfig' >> /etc/bash.bashrc
echo 'export PYTHONPATH=/usr/local/opencv/lib/python2.6/site-packages/opencv' >> /etc/bash.bashrcRestart your terminal to get the new paths

Test by building samples:

cd ~/Programs/OpenCV-2.0.0/samples/c
. build_all.sh

You're done.

How to check why a system reboot/restart is required


The following will tell you which packages require a reboot

cat /var/run/reboot-required.pkgs

How to prevent a package from being upgraded


Normally it could be done with aptitude

sudo aptitude hold [packagename]

But sometimes aptitude does not work. Use dpkg:

sudo -s
echo linux-image-generic hold | dpkg --set-selections

Check with

dpkgs --get-selection  | grep linux-image-generic

Reset with

echo linux-image-generic install | dpkg --set-selections

How to change default java used on Ubuntu


Assuming you have more than one java installed. Run:

sudo update-alternatives --config java

Or if you want graphical interface do

sudo apt-get install galternatives
galternatives

How to login remotely with lightdm


Use VNC to connect to the root screen. Run the following on the server

sudo x11vnc -auth /var/lib/lightdm/.Xauthority -display :0

Then connect via a vnc client and login. Use the ssh display forwarding capable vncclient from the client machine:

vncviewer -via user@server localhost:0

Or you can also enable XDMCP protocol on lightdm and login with an XDMCP client. Edit /etc/lightdm/lightdm.conf and change

[XDMCPServer]
enabled=true

Then use tsclinet. The XDMCP is available in tsclinet by installing xnest. Xmanager is another option

sudo apt-get install xnest

How to enable screen switching functionality on Thinkpads using Fn-F7


Only works for Thinkpads with Nvidia right now. Get disper either from its website or set the repos, apt-get update and then apt-get install. do as super user:

echo "event=ibm/hotkey HKEY 00000080 00001007" > /etc/acpi/events/ibmvideobtn
echo "action=/home/CHANGE ME/bin/thinkpad-screen-switcher.sh fnf7 >/var/log/thinkpad-screen 2>&1" >> /etc/acpi/events/ibmvideobtn
echo "echo enable,0x084e > /proc/acpi/ibm/hotkey" > /etc/acpi/resume.d/91-ibm-hotkey-enable.sh

Add manually "echo enable,0x084e > /proc/acpi/ibm/hotkey before the end /etc/rc.local for the mapping to survive reboot and suspend. thinkpad-screen-switcher.sh is the great Thinkpad Display Script written by Stuart Hopkins

How to forcefully clear memory used by kernel for caching


sudo sh -c "echo 1 > /proc/sys/vm/drop_caches"

How to find out biggest memory consuming processes with ps


For the real memory:

sudo ps -eo pmem,vsize,pcpu,rss,vsize,args | sort -rnk 1 | head

For the virtual memory

sudo ps -eo vsize,pmem,pcpu,rss,vsize,args | sort -rn | head

How to remove Alt-F2 popup after having xfc installed


Run xfc_settings_editor Go to custom and delete the Alt-F2 entry

How to clean up disk space in Ubuntu


  • Clean package infromation and obsolete/unused packages

sudo aptitude clean
sudo aptitude autoclean
sudo apt-get autoremove
sudo apt-get install localepurge
sudo localepurge
sudo apt-get install deborphan
sudo deborphan | xargs sudo apt-get -y remove --purge

Start Synaptic Package Manager. Click the Status button and remove all residiual configurations (if present)

  • Clean kernels

Edit /boot/grub/menu.lst and change

# howmany=all

to

# howmany=2

then save it and run

sudo update-grub

this keeps the kernels installed, but limits your grub menu to the latest 2 kernels at all times.

  • Other tools that could help: fslint, gtkorphan

How to add openclipart galleries to open office 3


Install first:

sudo apt-get install openclipart

then run

dpkg-query -L openclipart-openoffice.org

Note the many files in /usr/lib/openoffice/share/gallery/. You should see the same thing. In OpenOffice 3, go to Tools > Options. Click Paths in the left panel, then Gallery in the right. Click Edit. Add a new path '/usr/lib/openoffice/share/gallery' . After a few clicks of OK to accept the changes, restart open office.

How to edit an apt-get key


sudo gpg --keyring /etc/apt/trusted.gpg --trustdb-name /etc/apt/trustdb.gpg --edit-key 7EBC211F trust

How to lower ati power consumption


aticonfig --set-powerstate 1

How to save power under Linux on a ThinkPad


Ubuntu mostly has everything you need. You could get powertop and follow its recommendations. Alternatively you can go to 1, download debian package and install. Then edit

/etc/default/acpi-support

Set

ENABLE_LAPTOP_MODE=true.

How to set hardware time


echo "About to set date with following parameters :"
echo "YEAR=$2"
echo "MONTH=$3"
echo "DAY=$4"
echo "HOUR=$5"
echo "MINUTE=$6"
echo "SECOND=$7"
date -s "YEAR.MONTH.DAY-HOUR$2.$3.$4-$5:$6:$7" > /dev/null
hwclock -w

How to get a boot log in Ubuntu


Enable the bootlogd deamon by editing the file in /etc/defaults/bootlogd, and setting

BOOTLOGD_ENABLE=Yes

Reboot. The boot daemon is started at the beginning and stopped at the end of the system uptime. Check out /var/log/boot for all the informations that was pushed out during the boot time.

How to start OpenVPN on boot


sudo update-rc.d -n openvpn defaults 96 4

then

sudo update-rc.d openvpn defaults 96 4


@HowTo @LinuxandUnix