Linux and Unix How To

How to run powertop on switching to battery power

sudo vi /etc/udev/rules.d/50-powersave.rules
SUBSYSTEM=="power_supply", ATTR{online}=="0", RUN+="/usr/bin/powertop-autotune"

How to run powertop on startup with systemd

cat << EOF | sudo tee /etc/systemd/system/powertop.service
[Unit]
Description=PowerTOP auto tune

[Service]
Type=idle
Environment="TERM=dumb"
ExecStart=/usr/sbin/powertop --auto-tune

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable powertop.service

How to get WebEx working on Linux

First off, only meeting center works, personal meetings are dead for linux, cause you know, Cisco.
You also may not be able to see files that are shared with you.

for x in $(ldd $HOME/.webex/*/*.so | grep "not found" | sort -u | awk '{print $1}') ; do apt-file search $x ; done

Then install the missing libs. For example:
sudo apt install libgtk2.0-0:i386 openjdk-8-jdk-headless:i386 libpangoxft-1.0-0:i386 libxft2:i386 libxmu6:i386 libxtst6:i386 libxv1:i386 libpangox-1.0-0:i386
or
sudo apt-get install -y libxmu6:i386 libasound2:i386 libxv1:i386 libxtst6:i386 libgcj12-awt:i386
or
sudo apt install libgtk2.0-0:i386 openjdk-8-jdk-headless:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libxft2:i386 libxmu6:i386 libxt6:i386 libxtst6:i386 libxv1:i386

References
http://blog.michelemattioni.me/2016/02/09/how-to-get-webex-running-on-an-ubuntu-smoothly/
https://askubuntu.com/questions/459838/webex-is-not-working-in-ubuntu-14-04-please-help

But honestly, don't use webex if you can avoid it.

How to record screen on linux

sudo add-apt-repository ppa:maarten-baert/simplescreenrecorder
sudo apt-get update
sudo apt-get install simplescreenrecorder

How to compare installed packages between two systems

On one system do dpkg -l > dpkglist.log and copy it to the other system. Run the following command that will ignore versions buit will include descriptions

colordiff -y <(dpkg -l | grep ^ii | awk '{print $2": "$5" "$6" "$7}') <(grep ^ii dpkglist.log |awk '{print $2": "$5" "$6" "$7}') | less -r
Also try vim -dR - (vim diff and read only)
or simply, ignoring specific versions
diff <(awk '{ print $2 }' one) <(awk '{print $2}' dpkglist.log)


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/reponame

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

How to 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>

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

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
Although note that this script is not run when the system comes out from suspend-to-ram. To fix that create

[Desktop Entry]
Type=Application
Exec="/home/user/bin/tamenvidia.sh"
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_IN]=TameNvidia
Name=TameNvidia
Comment[en_IN]=LowerRPM
Commen=LowerRPM

then
echo sudo /usr/bin/nvclock -f -F 60 \& > ~/bin/tamenvidia.sh
and do not forget to add
(ALL) NOPASSWD: /usr/bin/nvclock
via sudo visudo

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 an 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 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 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 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 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 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 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

How to do a linux soft reboot with keys

Hold down the Alt and SysRq (Print Screen) keys.
While holding those down, type the following keys in order, several seconds apart: REISUB
Computer should reboot.

Mnnemonics - "Reboot Even If System Utterly Broken"

unRaw (take control of keyboard back from X),
tErminate (send SIGTERM to all processes, allowing them to terminate gracefully),
kIll (send SIGKILL to all processes, forcing them to terminate immediately),
Sync (flush data to disk),
Unmount (remount all filesystems read-only),
reBoot.

How to disable SELinux on RHEL or Centos

The following is for RHEL and CentOS. For SLES change the file location to /etc/sysconfig/selinux

sudo -s
setenforce 0 # temporary
sed -i 's/SELINUX=\(enforcing\|permissive\)/SELINUX=disabled/g' /etc/selinux/config  # permanent

Reboot the server. Check to make sure it's disabled:

sestatus 

Configure SMTP mail catcher on SLES

Go to the mail config in Yast and add the following to the virtual domains on the last page

idsake.com	catchall
@idsake.com	user@localhost

you can verify that it shows up at the end of /etc/postfix/virtual
all mail will be found in
/var/spool/mail/user

you could also add these lines manually to /etc/postfix/virtual and then run postmap /etc/postfix/virtual in order to generate the indexed /etc/postfix/virtual.db Postfix will read.

another way to do this is main.cf
mydestination = pcre:/etc/postfix/mydestinations
and /etc/postfix/mydestinations should contain
/.*/ ACCEPT
or
In /etc/postfix/main.cf add
alias_maps = hash:/etc/aliases, regexp:/etc/postfix/catch-all-local.regexp
In /etc/postfix/catch-all-local.regexp add
!/^owner-/ your-catch-all-user
detailed instructions are at http://www.postfix.org/VIRTUAL_README.html

install and configure kmail for local mail, specify no locking (you're only reading email). configure appearance-layout - short folder list, uncheck show favorite folder, never show message structure. Message list - hide tab bar
set classic theme on the left most button onthe message list, then right click the header, unselect "sender/receiver" and select "sender" and "receiver"

@HowTo @LinuxandUnix