Linux and Unix How To

From KnowWiki
Jump to: navigation, search

Contents

[edit] 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 

[edit] How to get CPU info

cat /proc/cpuinfo

or

lscpu

or

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

[edit] 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

[edit] Configure UFW firewall to allow NFS connections

First, fix the NFS port from the default floating one. Edit /etc/default/nfs-kernel-server and change RPCMOUNTDOPTS=--manage-gids to RPCMOUNTDOPTS="-p 13335" where 13335 is just a randomly selected port. Then restart NFSd

sudo service nfs-kernel-server restart

Now configure the UFW to accept incoming connections on fixed port and ports 111 and 2049:

sudo ufw allow from 192.168.1.0/24 to any port 111
sudo ufw allow from 192.168.1.0/24 to any port 2049
sudo ufw allow from 192.168.1.0/24 to any port 13325

[edit] 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

[edit] 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 /

[edit] How to configure sane and xsane for network scanner access

On the server, edit /etc/default/saned to read:

RUN=yes

Edit /etc/sane.d/saned.conf to share the printer on your subnet:

192.168.1.0/24

Make sure saned user has the correct permissions to access the scanner device:

sudo adduser saned lp
sudo su -s /bin/bash saned
scanimage -L

Then

sudo service saned restart
sudo update-rc.d saned defaults

On the client, edit (or create) /etc/sane.d/net.conf and add the ip of your saned server

192.168.1.10

Then test by running xsane or skanlite

[edit] 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:
#!/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
  • 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.

[edit] 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"

[edit] How to configure remote scanning

On the server (box with the scanner attached to) do

sudo vi /etc/default/saned

Set RUN=yes

sudo vi /etc/sane.d/saned.conf

Add your network mask somewhere in that file. For your normal home network it will be 192.168.1.0/24

Add the saned user to the appropriate groups

sudo adduser saned scanner
sudo adduser saned lp

Start the scanner server

sudo service saned start

On the client

vi /etc/sane.d/net.conf

And add the name or the IP of the server

[edit] 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

[edit] 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.

[edit] 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 script and save it to /home/user/bin/pdfpostproc.sh. Download

#!/bin/bash
CURRENT_PDF="${1}"
CURRENT_USER="${2}"
DISPLAY=:0.0
export DISPLAY
XAUTHORITY=/home/${CURRENT_USER}/.Xauthority
export XAUTHORITY
CURRENT_HOME="$(/bin/grep ${CURRENT_USER} /etc/passwd | /usr/bin/cut -d: -f6)"
CONFIG_FILE="${CURRENT_HOME}/.pdf-writer.conf"
CANCELLED="No"
get_filename()
{
        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 - $BASENAME" --file-filter="*.pdf")
                if [ ${?} -eq 1 ]; then
                        CANCELLED="Yes"
                        break
                fi
                if [ ! "${FILENAME}" = "" ]; then
                        FILENAME=$(echo ${FILENAME}.pdf | sed -re "s/(\.pdf)+$/.pdf/g")
                        break;
                else
                        /usr/bin/zenity --error --text "You must select a file or Cancel"
                fi
        done
        return
}
get_filename
if [ "${CANCELLED}" == "No" ]; then
        /bin/cp "${CURRENT_PDF}" "${FILENAME}"
        #evince "${FILENAME}" &
        okular "${FILENAME}" &
fi
/bin/rm "${CURRENT_PDF}"
exit 0

Make it executable. Now, specify the folder name where PDFs shall go by default (for example /home/user/Temp):

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 

Now adding a userland script to a root component is a punishable offense, but it's the easy way out. So, to make it all go nicely with the linux security system edit /etc/apparmor.d/usr.sbin.cupsd. Change the line that reads

@{HOME}/PDF/ rw,

To

@{HOME}/folder specified in .pdf-writer.conf/ rw,

Then add the following line to the end, before the closing curly bracket:

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

Restart cupsd and app armor.

sudo service cups restart
sudo service apparmor restart

Try printing and enjoy.

[edit] 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>

[edit] How to enable or disable KDE compositing from the command line

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

[edit] 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 {} \;

[edit] 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

[edit] 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

[edit] 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

[edit] 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)

[edit] How to check Ubuntu version

lsb_release -a

[edit] 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.

[edit] 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

[edit] 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

[edit] 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

[edit] 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

[edit] How to forcefully clear memory used by kernel for caching

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

[edit] 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

[edit] How to remove Alt-F2 popup after having xfc installed

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

[edit] 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

[edit] 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.

[edit] How to edit an apt-get key

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

[edit] How to lower ati power consumption

aticonfig --set-powerstate 1

[edit] 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.

[edit] 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

[edit] 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.

[edit] How to start OpenVPN on boot

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

then

sudo update-rc.d openvpn defaults 96 4
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox