Po-Yi Chou

undergraduate in EECS in NCTU


Project maintained by poyichou Hosted on GitHub Pages — Theme by mattgraham

Home Notes Scripts Code Contact Blog

Notes

Linux

Notes-Linux

Change time zone (for example: change to CDT)

$ cp /usr/share/zoneinfo/America/Chicago /etc/localtime

Analyze size of folder content

$ ncdu

big5 garbled in compressed file (take zip for example)

$ sudo apt-get install convmv
$ LANG=C unzip file.zip
$ convmv -f big5 -t utf8 -r --notest *

unzip produce ‘unsupported compression method 99’

# may caused by WinRAR/WinZIP default encryption method (i.e. AES)
# currently not supported by unzip
# alternative: 7z, take ubuntu for example
$ sudo apt install p7zip-full
$ 7z x <file.zip>

USB is read only in Nautilus when it is not

# it's a bug of Nautilus
killall nautilus

crontab

# run a script as a normal user
$ crontab -e
# run a script as root
$ sudo crontab -e
# file format
# '*' implies every interval
# '*/n' implies every n interval
# 'x-y' implies every interval between x and y
# 'x,y,z' implies particular times x, y, z
[minute(1-59)] [hour(1-23)] [date(1-31)] [month(1-12)] [day(0-6(Sunday-Friday))] [command]

# Example: upgrade packages with apt-get every 2 hours
00 */2 * * * /usr/bin/apt-get update && /usr/bin/apt-get upgrade -y

tmux

# Commands
# start a new session
$ tmux [|new -s <session name>]
# list running sessions
$ tmux ls
# attach
$ tmux a [|-t <session name>]
# delete a session
$ tmux kill-session -t <session_name>
# delete all sessions
$ tmux kill-session -a

# Shortcut
# Help
Ctrl+b ?
# detach
Ctrl+b d
# create a window
Ctrl+b c
# switch to previous/next/specific window
# according to the order in status bar
Ctrl+b p/n/<number>
# navigate panes
Ctrl+b <arrow>
# split a pane into a left and a right pane
Ctrl+b %
# split a pane into a top and a buttom pane
Ctrl+b "

gdm-plymouth

# After `systemctl status gdm-plymouth.service`

# gdm-password][691]: PAM unable to dlopen(/usr/lib/security/pam_gnome_keyring.so): ****
# gdm-password][691]: PAM adding faulty module: /usr/lib/security/pam_gnome_keyring.so

# Install gnome-keyring
# Example
$ sudo pacman -S gnome-keyring

“No cast destinations found” in Chromium and Google Chrome on Linux

chrome://flags/#load-media-router-component-extension -> Load Media Router Component Extension, change Default to Enabled.

beep sound

# To enable the beep sound, make sure that pcspkr module is exist
lsmod | grep pcspkr
# If doesn't exist, to install related package, take ubuntu for example
sudo apt install beep
# remove pcspkr in blacklist
sudo vim /etc/modprobe.d/blacklist.conf # remove "blacklist pcspkr"
reboot # reboot to make change of /etc/modprobe.d/blacklist.conf take effect

Disable/re-enable suspend

# disable
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
# re-enable
sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target

Make Grub remember last choice

# put following in /etc/default/grub
#GRUB_DEFAULT=saved
#GRUB_SAVEDEFAULT=true
$ sudo update-grub
# or for some distribution without update-grub
$ sudo grub-mkconfig -o /boot/grub/grub.cfg

Disable GDM auto suspend

# configure policy on ac, for battery, change ac below to battery
sudo su gdm -s /bin/bash -c "dbus-launch gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 'nothing'"
sudo su gdm -s /bin/bash -c "dbus-launch gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-timeout 0"
# To verify changes
sudo su gdm -s /bin/bash -c "gsettings list-recursively org.gnome.settings-daemon.plugins.power"
# Restart GDM to activate your changes. 

Laptop modify backlight fail

xbacklight -get No outputs have backlight property add file /etc/X11/xorg.conf.d/20-intel.conf first check if /sys/class/backlight/intel_backlight exists

Section "Device"
    Identifier  "Intel Graphics"
    Driver      "intel"
    Option      "Backlight"  "intel_backlight"
EndSection

Disable USB autosuspend (useful when your os is installed in USB drive)

# modify usbcore.autosuspend kernel module parameter, suppose the bootloader is grub2
# usbcore.autosuspend=<delay second>, -1 to disable
sudo sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="[a-z ]*/& usbcore.autosuspend=-1/' /etc/default/grub
sudo update-grub2
reboot
# to check result, should be -1
cat /sys/module/usbcore/parameters/autosuspend
disk

Notes-disk

Mount a new deivce

if your device file is /dev/hda1

# Create a new filesystem using the ext4 filesystem type:  
$ mke2fs -t ext4 /dev/hda1
# Mount
$ mount -t ext4 /dev/hda1 /wherever

Disk Scheduler

# check available disk schedulers (in my case, cfq is in use).
$ cat /sys/block/sda/queue/scheduler
noop deadline [cfq]
# enable specific disk scheduler (for example, cfq)
# SCHEDNAME = Desired I/O scheduler
# DEV = device name (e.g., hda)
$ echo SCHEDNAME > /sys/block/DEV/queue/scheduler
# To make it consistent after reboot
# On Grub 2
# Add "elevator=noop" to the GRUB_CMDLINE_LINUX_DEFAULT line.
$ vim /etc/default/grub
$ update-grub

Move whole os to smaller drive (w/ example, i.e. sdc->sdd)

$ lsblk # not related blocks truncated
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sdc      8:32   1 235.5G  0 disk 
├─sdc1   8:33   1   512M  0 part 
└─sdc2   8:34   1   235G  0 part
sdd      8:48   1 114.6G  0 disk 
└─sdd1   8:49   1 114.6G  0 part

To shrink, shrink filesystem then partition
To enlarge, enlarge partition then filesystem
Check filesystem

$ sudo e2fsck /dev/sdc2
e2fsck 1.46.2 (28-Feb-2021)
/dev/sdc2: clean, 204536/15409152 files, 3147421/61608704 blocks
$ sudo e2fsck -f /dev/sdc2
e2fsck 1.46.2 (28-Feb-2021)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/sdc2: 204536/15409152 files (0.2% non-contiguous), 3147421/61608704 block

resize ext2/ext3/ext4 file system

$ sudo resize2fs /dev/sdc2 114G
resize2fs 1.46.2 (28-Feb-2021)
Resizing the filesystem on /dev/sdc2 to 29884416 (4k) blocks.
The filesystem on /dev/sdc2 is now 29884416 (4k) blocks long.

Shrink partition

$ sudo fdisk /dev/sdc

Welcome to fdisk (util-linux 2.36.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/sdc: 235.52 GiB, 252888219648 bytes, 493922304 sectors
Disk model: USB3.0 CRW   -SD
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 080B7B7D-7982-4AE4-A8A9-F1FB34D18F97

Device       Start       End   Sectors  Size Type
/dev/sdc1     2048   1050623   1048576  512M EFI System
/dev/sdc2  1050624 493920255 492869632  235G Linux filesystem

Command (m for help): d
Partition number (1,2, default 2): 2

Partition 2 has been deleted.

Command (m for help): n
Partition number (2-128, default 2): 
First sector (1050624-493922270, default 1050624): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (1050624-493922270, default 493922270): +119537664K

Created a new partition 2 of type 'Linux filesystem' and of size 114 GiB.
Partition #2 contains a ext4 signature.

Do you want to remove the signature? [Y]es/[N]o: N

Command (m for help): p

Disk /dev/sdc: 235.52 GiB, 252888219648 bytes, 493922304 sectors
Disk model: USB3.0 CRW   -SD
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 080B7B7D-7982-4AE4-A8A9-F1FB34D18F97

Device       Start       End   Sectors  Size Type
/dev/sdc1     2048   1050623   1048576  512M EFI System
/dev/sdc2  1050624 240125951 239075328  114G Linux filesystem

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

Recheck filesystem

$ sudo e2fsck -f /dev/sdc2
e2fsck 1.46.2 (28-Feb-2021)
Pass 1: Checking inodes, blocks, and sizes
Inode 8 extent tree (at level 2) could be narrower.  Optimize<y>? yes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/sdc2: 204536/7471104 files (0.8% non-contiguous), 2649209/29884416 blocks

Move whole os from sdc to sdd

$ sudo dd if=/dev/sdc of=/dev/sdd # traditional way
#or
$ sudo su -s /bin/bash -c 'pv -s 122944486912 -S < /dev/sdc > /dev/sdd' # speed up and show progress, 122944486912 equals 240125951 (end of partition) * 512 byte
65.4GiB 0:47:32 [22.2MiB/s] [============>                                    ] 27% ETA 2:03:31

partition sdd if you want to use 100% unallocated space

$ sudo parted /dev/sdd
GNU Parted 3.4
Using /dev/sdd
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: SanDisk Ultra USB 3.0 (scsi)
Disk /dev/sdd: 123GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End    Size   File system  Name                  Flags
 1      1049kB  538MB  537MB  fat32        EFI System Partition  boot, esp
 2      538MB   123GB  122GB  ext4

(parted) resizepart 2
End?  [123GB]? 100%
(parted) q
Information: You may need to update /etc/fstab.
$ sudo e2fsck -f /dev/sdd2
e2fsck 1.46.2 (28-Feb-2021)
Pass 1: Checking inodes, blocks, and sizes
Inode 8 extent tree (at level 2) could be narrower.  Optimize<y>? yes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/sdd2: 204544/7471104 files (0.8% non-contiguous), 2653626/29884416 blocks

resize ext4 filesystem to fit

$ sudo resize2fs /dev/sdd2
resize2fs 1.46.2 (28-Feb-2021)
Resizing the filesystem on /dev/sdd2 to 29912827 (4k) blocks.
The filesystem on /dev/sdd2 is now 29912827 (4k) blocks long.


clone disk in windows (msys, slow speed but easy)

# find out device names
 $ cat /proc/partitions
major minor  #blocks  name   win-mounts

    8     0 1953514584 sda
    8     1     16384 sda1
    8     2 1023983616 sda2   D:\
    8     3 929512448 sda3   F:\
    8    16 244198584 sdb
    8    17    460800 sdb1
    8    18    102400 sdb2
    8    19     16384 sdb3
    8    20 242815689 sdb4   C:\
    8    21    800768 sdb5
    8    32 3907018584 sdc
    8    33     16384 sdc1
    8    34 1023983616 sdc2
    8    35 929512448 sdc3
# may need to run msys in administrator mode 
# specify bs since default value (512 bytes) might causing slow speed
 $ dd if=/dev/sda of=/dev/sdc status=progress bs=128K

clone disk in windows (native, cmd, fast)

download dd for windows in website
find out device names, Partition0 is the entire disk

C:\Dowload\Path\dd-0.5>dd --list
rawwrite dd for windows version 0.5.
Written by John Newbigin <jn@it.swin.edu.au>
This program is covered by the GPL.  See copying.txt for details
Win32 Available Volume Information
\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume2
  fixed media
  Mounted on \\.\d:

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume3
  fixed media
  Mounted on \\.\f:

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume4
  fixed media
  Not mounted

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume7
  fixed media
  Mounted on \\.\c:

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume8
  fixed media
  Not mounted

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\HarddiskVolume5
  fixed media
  Not mounted

\\.\Volume{xxx-xxx-xxx-xxx-xxx}\
  link to \\?\Device\CdRom0
  CD-ROM
  Mounted on \\.\e:


NT Block Device Objects
\\?\Device\CdRom0
  size is 2147483647 bytes
\\?\Device\Harddisk0\Partition0
  link to \\?\Device\Harddisk0\DR0
  Fixed hard disk media. Block size = 512
  size is 2000398934016 bytes
\\?\Device\Harddisk0\Partition1
  link to \\?\Device\HarddiskVolume1
  Fixed hard disk media. Block size = 512
  size is 16777216 bytes
\\?\Device\Harddisk0\Partition2
  link to \\?\Device\HarddiskVolume2
\\?\Device\Harddisk0\Partition3
  link to \\?\Device\HarddiskVolume3
\\?\Device\Harddisk1\Partition0
  link to \\?\Device\Harddisk1\DR1
  Fixed hard disk media. Block size = 512
  size is 250059350016 bytes
\\?\Device\Harddisk1\Partition1
  link to \\?\Device\HarddiskVolume4
  Fixed hard disk media. Block size = 512
  size is 471859200 bytes
\\?\Device\Harddisk1\Partition2
  link to \\?\Device\HarddiskVolume5
  Fixed hard disk media. Block size = 512
  size is 104857600 bytes
\\?\Device\Harddisk1\Partition3
  link to \\?\Device\HarddiskVolume6
  Fixed hard disk media. Block size = 512
  size is 16777216 bytes
\\?\Device\Harddisk1\Partition4
  link to \\?\Device\HarddiskVolume7
\\?\Device\Harddisk1\Partition5
  link to \\?\Device\HarddiskVolume8
  Fixed hard disk media. Block size = 512
  size is 819986432 bytes
\\?\Device\Harddisk2\Partition0
  link to \\?\Device\Harddisk2\DR4
  Fixed hard disk media. Block size = 512
  size is 4000787030016 bytes

Virtual input devices
 /dev/zero   (null data)
 /dev/random (pseudo-random data)
 -           (standard input)

Virtual output devices
 -           (standard output)

–progress make it show copied block
–size makes sure dd not to read past end of an entire device
specify bs since default value (512 bytes) might causing slow speed

C:\Dowload\Path\dd-0.5>dd if=\\?\Device\Harddisk0\Partition0 of=\\?\Device\Harddisk2\Partition0 bs=16M --progress --size
networking

Notes-networking

Bind a binary to a local port

# method 1
ncat -vc [binary] -kl 127.0.0.1 [port] 
# method 2
rm -f /tmp/f; mkfifo /tmp/f
while [ 1 ]; do cat /tmp/f | [binary] 2>&1 | nc -l 127.0.0.1 [port] > /tmp/f; done
rm -f /tmp/f

ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused

# add "ssh: ALL"
$ sudo vim /etc/hosts.allow
$ sudo systemctl restart sshd

establish a wireless connection with netctl

# require package "wpa_passphrase"
# dhcpcd.service should be active

# If profile file is not exists
# generate profile file and establish a connection 
# set -o flag to obfuscate the wireless passphrase
$ sudo wifi-menu -o # choose the ssid, enter the password if required

# Once profile file has been generated
# to establish/stop a connection
# <profile file> is only the file name, not full path
$ sudo netctl [start|stop] <profile file>

# To enable/reenable a profile to start at boot
# use reenable after changing profile file
$ sudo netctl [enable|reenable] <profile file>

# If you want to use dhcpcd manually
$ sudo dhcpcd <interface> # check interface with "ip link"

## netctl-auto
# To enable auto connect to exist profile
$ sudo systemctl enable netctl-auto@<wireless interface>.service
$ sudo systemctl start netctl-auto@<wireless interface>.service

# Switch to another ssid
$ sudo netctl-auto switch-to <profile file>

netctl configuration file for 802.1X (PEAP-MSCHAP v2)

Description='A descriptive name'
Interface=wlp2s0
Connection=wireless
Security=wpa-configsection
ESSID=SSID
IP=dhcp
WPAConfigSection=(
    'ssid="SSID"'
    'key_mgmt=WPA-EAP'
    'eap=PEAP'
    'identity="MYIDENTITY"'
    'password="MYPASSWORD"'
    'phase2="auth=MSCHAPV2"'
)

netctl configuration file for 802.1X (PEAP-MSCHAP v2) while hash password instead of plaintext

Description='A descriptive name'
Interface=wlp2s0
Connection=wireless
Security=wpa-configsection
ESSID=SSID
IP=dhcp
WPAConfigSection=(
    'ssid="SSID"'
    'key_mgmt=WPA-EAP'
    'eap=PEAP'
    'identity="MYIDENTITY"'
    'password=hash:NT_HASH_OF_PASSWORD_HERE'
    'phase2="auth=MSCHAPV2"'
)

To generate nthash of password

echo -n MYPASSWORD | iconv -t utf16le | openssl md4

error when establishing a wireless connection with netctl

# error code
Job for netctl@xxxxxx.service failed because the control process exited with error code.
See "systemctl status "netctl@xxxxxx.service"" and "journalctl -xe" for details.
# solution
sudo systemctl stop dhcpcd.service
sudo systemctl disable dhcpcd.service
sudo rm /var/lib/dhcpcd/*.lease # and reboot
sudo wifi-menu -o
sudo dhcpcd <interface> # check interface with "ip link"

Monitor 802.11 packets

# put WiFi interface in monitor mode
sudo iw dev <wlan interface> interface add mon0 type monitor
sudo ip link set mon0 up
sudo wireshark -I # in monitor mode, monitor on mon0
# remove virtual interface afterwards
sudo iw dev mon0 interface del
Ubuntu

Notes-Ubuntu

Use other kernel version

# keep apt from upgrading kernel ver.
apt-mark hold linux-image-generic linux-headers-generic
# install other kernel ver.(for example: 4.8.0-52-generic)
apt install linux-image-4.8.0-52-generic
#(comment out `GRUB_HIDDEN_TIMEOUT=0` and `GRUB_HIDDEN_TIMEOUT_QUIET=true`)
vim /etc/default/grub
update-grub
# boot into other kernel ver.
reboot
# find other image on the host
dpkg --list | grep linux-image
# remove the target image (for example: 4.8.0-42-generic)
apt purge linux-image-4.8.0-42-generic
apt autoremove

Check if Ubuntu needs a reboot (usually after apt upgrade)

# needs if file exists
cat /var/run/reboot-required
# list packages cause the need of reboot
cat /var/run/reboot-required.pkgs

Before kernel programming

apt install module-assistant
m-a prepare

apt upgrade failed in desktop version

# Example  
$ sudo apt upgrade
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?

# Solution  
sudo systemctl stop apt-daily.timer
sudo systemctl stop apt-daily.service
# Example 2
$ sudo apt upgrade
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

# Solution
# Get process id using this file and kill SIGKILL to it
sudo kill -s 9 $(sudo fuser /var/lib/dpkg/lock-frontend)
# Example 3
$ poweroff
Operation inhibited by "APT" (PID 2815 "unattended-upgr", user root), reason is "APT is installing or removing packages".
Please retry operation after closing inhibitors and logging out other users.
Alternatively, ignore inhibitors and users with 'systemctl poweroff -i'.
# Solution
sudo vim /etc/apt/apt.conf.d/20auto-upgrades

file /etc/apt/apt.conf.d/20auto-upgrades

APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "1";

Then

sudo apt update && sudo apt upgrade

grub still hides after GRUB_TIMEOUT set > 0

sudo vim /etc/default/grub # add GRUB_TIMEOUT_STYLE="menu"
sudo update-grub

Disable autosuspend in GDM3 login screen

# To print setting, which print suspend and 1200 respectively
sudo dbus-launch gsettings get org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type
sudo dbus-launch gsettings get org.gnome.settings-daemon.plugins.power sleep-inactive-ac-timeout
# To turn off suspension
sudo dbus-launch gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type nothing
CISCO-switch

Notes-CISCO switch

Some basic commands

# Enables privileged EXEC mode(enter your password if prompted) 
Switch> en
# Get into configuration terminal
Switch# conf t
# Get out of configuration terminal
Switch(config-if)# exit
Switch(config-if)# end

Some “show” commands

# Show all the interfaces
Switch# show int br
Switch# show int
Switch# show bgp
Switch# show ip route
Switch# show cdp neighbors

Convert a port into a routed port

# Affects only a single port of a L3 Switch
# Makes the port into a routed port 
#   then you can apply an IP address directly to the port 
#   but can't be assigned to a certain VLAN 
#   as it's now a routed port not a switched port
# Set an ip address to an interface
Switch(config)# int [interface]
Switch(config-if)# no switchport

Set IP address to an interface

# Set an IP address to an interface
Switch(config)# int [interface]
Switch(config-if)# ip add [ip.addr.you.want] [the.mask.of.ip]
# No shutdown
Switch(config-if)# no shut

Write current configuration to start-up configuration

# "do wr" works in configure mode of console 
#   and "wr" works in normal console window
Switch(config)# do wr
#or
Switch# wr

Set up OSPF

Switch(config)# router ospf [process-id]
# Defines an interface on which OSPF runs
#   and defines the area ID for that interface
Switch(config-router)# network [ip-address] [wildcard-mask] area [area-id] 
# Example
Switch(config)# router ospf 1
Switch(config-router)# network 10.0.0.0 0.0.0.7 area 0
Switch(config-router)# network 13.0.0.0 0.0.255.255 area 0

Set up CDP (for cisco devices, use CDP instead of LLDP)

Switch(config)# no cdp log mismatch duplex
Switch(config)# cdp timer 30
Switch(config)# cdp holdtime 120

Set up route map (example)

# Community-list 20, deny traffic with "tag" "7000:10"
Switch(config)# ip community-list 20 deny 7000:10
Switch(config)# ip community-list 20 permit
# Used in BGP below
# Two route-map: FROM-9000 and TO-9000
#   FROM-9000: set a tag, TO-9000: obey rules of "community-list 20"
# Route-map
Switch(config)# route-map FROM-9000 permit 10
# Set 'tag'
Switch(config-if)# set community 9000:10
Switch(config)# route-map TO-9000 permit 30
# Only allows traffic that "community-list 20" allows (see above)
Switch(config-if)# match community 20

Set up BGP (example)

Switch(config)# router bgp 8000
Switch(config-router)# no synchronization
Switch(config-router)# bgp log-neighbor-changes
# Claim what you have
Switch(config-router)# network 13.0.0.0 mask 255.255.0.0
# Other IPs in the same AS
Switch(config-router)# neighbor 10.0.0.2 remote-as 8000
Switch(config-router)# neighbor 10.0.0.2 send-community
#other IPs in the other AS
Switch(config-router)# neighbor 197.0.0.2 remote-as 9000
Switch(config-router)# neighbor 197.0.0.2 next-hop-self
Switch(config-router)# neighbor 197.0.0.2 send-community
#set route-map for outbound and inbound traffic
Switch(config-router)# neighbor 197.0.0.2 route-map TO-9000 out
Switch(config-router)# neighbor 197.0.0.2 route-map FROM-9000 in
Arch-basic-setup

Notes-Arch-basic-setup

Basic setup after installation of Arch Linux with shell script at Scripts -> arch-install.sh

create an user

#### log in root ####
# change root password
passwd root
useradd --create-home --groups wheel --shell /bin/bash <user_name>
# change <user_name> password
passwd <user_name>

configuration

export EDITOR=vim
visudo # comment out '%wheel ALL=(ALL) ALL'
#### log in normal user ####
# personal vim initializations
wget -O .vimrc https://poyichou.github.io/config_file/myvimrc
# system wide vim initializations
sudo cp .vimrc /etc/vimrc
wget -O .bashrc https://poyichou.github.io/config_file/mybashrc

destop

sudo pacman -S gnome-shell gdm gnome-tweak-tool
# To unlock option gnome-tweak-tool -> Appearance -> Shell,
# enable option gnome-tweak-tool -> Extensions -> User themes later
sudo pacman -S gnome-shell-extensions
sudo systemctl enable gdm
# terminal emulator
sudo pacman -S termite compton
mkdir -p ~/.config/termite/
wget -O ~/.config/termite/config https://poyichou.github.io/config_file/termite_config

# reboot to see if succeeded

notebook touchpad

# advanced touchpad fearue control
sudo pacman -S xf86-input-synaptics
sudo wget -O /etc/X11/xorg.conf.d/70-synaptics.conf https://poyichou.github.io/config_file/70-synaptics.conf

for virtualbox

sudo pacman -S virtualbox-guest-utils # choose 2

remain (After executing this block, refer Arch Wiki to change login screen background image.)

# set chewing in gnome-control-center -> Region & Language later
sudo pacman -S gnome-control-center ibus ibus-chewing

# font
sudo pacman -S noto-fonts noto-fonts-cjk noto-fonts-emoji
# solve terminal emulator character overlap
sudo pacman -S ttf-dejavu

# install yay (in substitution for yaourt)
cd /tmp
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si

cd ~
# add option gnome-tweak-tool -> Extensions -> Dash to dock
yay -S gnome-shell-extension-dash-to-dock # mustn't as root
# change theme with gnome-tweak-tool later
# theme
sudo pacman -S arc-gtk-theme
# icon theme
yay -S paper-icon-theme-git # mustn't as root

# Plymouth
yay -S plymouth # mustn't as root
# Add plymouth to the HOOKS array in mkinitcpio.conf.
# It must be added after base and udev for it to work.
# Example: HOOKS="base udev plymouth [...] "
sudo vim /etc/mkinitcpio.conf
# GRUB_CMDLINE_LINUX_DEFAULT="quiet splash [...] "
sudo vim /etc/default/grub
# generate the main configuration file of grub
sudo grub-mkconfig -o /boot/grub/grub.cfg
sudo mkinitcpio -p linux
# replace gdm with gdm-plymouth
sudo systemctl disable gdm
sudo pacman -R gdm
# libgdm-plymouth and libgdm are in conflict. Remove libgdm? [y/N] y
yay -S gdm-plymouth # mustn't as root
sudo systemctl enable gdm-plymouth.service

# Plymouth Theme
# example: Mageia ColdFire (https://www.opendesktop.org/c/1460735505)
wget -O 170783-Mageia-ColdFire.tar.gz <download_link>
tar zxvf 170783-Mageia-ColdFire.tar.gz
sudo cp -r Mageia-ColdFire/ /usr/share/plymouth/themes/
sudo plymouth-set-default-theme -R Mageia-ColdFire

sudo pacman -S firefox
# reboot to check if succeeded

Useful-tool

# photo management
sudo pacman -S gthumb
# player and theme for the player
sudo pacman -S vlc qt5-styleplugins # qt5-style-plugins on apt
# PDF reader (default viewer of KDE/Gnome)
sudo pacman -S okular evince
# file manager. gui:pcmanfm, nautilus, console:ranger, vifm; vifm is convenient for renaming files
sudo pacman -S pcmanfm nautilus ranger vifm
# sound server, sound server for headphone and the front end (GUI)
sudo pacman -S pulseaudio pulseaudio-jack pavucontrol
# Screen capture
sudo pacman -S gnome-screenshot
sudo pacman -S flameshot
# Managing email, calendars, contacts, tasks, and notes
sudo pacman -S evolution
# disk storage analysis
sudo pacman -S ncdu
cargo install du-dust # dust, du like tool
# fancy system monitoring
sudo pacman -S gnome-system-monitor conky

cron (crontab)

sudo pacman -S cronie
sudo systemctl enable cronie.service
sudo systemctl start cronie.service

Problem solution

# error: libexiv2: signature from "Eli Schwartz <schwartz@archlinux.org>" is unknown trust
sudo pacman -S archlinux-keyring
# changing login screen background image mentioned above doesn't work
=> Disable "High Contrast" option at the top bar on the login screen
Latex

Notes-Latex

Installation

Arch User

# contains most TeX Live packages
sudo pacman -S texlive-most
# contains packages providing character sets and features for non-English languages
sudo pacman -S texlive-lang

Ubuntu User

# most TeX Live packages
sudo apt install texlive-full
# for certain font issues
sudo apt install fonts-arphic-ukai msttcorefonts ttf-mscorefonts-installer

To use chinese

\usepackage{CJKutf8} % add
...
\begin{document}
\begin{CJK}{UTF8}{bsmi} % add
...
\end{CJK} % add
\end{document} 

Problem:

% Description:
%   It happens when compiling with pdflatex while using \tableofcontents
%   with sections containing chinese characters.
%   error message: Package inputenc Error: Unicode char \u 8: XXX not set up for use with LaTeX
%   note: you may have to compile the .tex file twice after applying this solution
...
\clearpage % add
\end{CJK}
Virtualbox

Notes-Virtualbox

Problem: freeze in full screen mode

Machine->Settings->Display, increase Video Memory  

Problem: resolution in guest not change with window resizing in host

Machine->Settings->Graphics Controller, select VBoxVGA  

Problem: clipboard of host and guest not shared

/usr/bin/VBoxClient-all
Arch

Notes-Arch

Problem solution

stuck on boot (displaying _)

# method 1
1.boot into live usb with arch iso installed
2.mount /dev/sdxx properly(ex.mount /dev/sda3 /mnt)
3.arch-chroot /mnt
4.pacman -Syu
5.poweroff
6.remove live usb and boot
# method 2: downgrade kernel version
1.boot into live usb with arch iso installed
2.mount /dev/sdxx properly(ex.mount /dev/sda3 /mnt)
3.arch-chroot /mnt
4.pacman -U /var/cache/pacman/pkg/linux-4.20.3.arch1-1-x86_64.pkg.tar.xz # example filename
5.poweroff
6.remove live usb and boot

error when yay -S xxx or yay -Syu

curl: (33) HTTP server doesn’t seem to support byte ranges. Cannot resume. ==> ERROR: Failure while downloading https://github.com/xxx Aborting… error downloading sources:xxx

# solution
yay -Scc # clean cache
i3wm

Notes-i3wm

To install

$ sudo pacman -S i3-wm i3lock feh lxappearance acpilight
# i3status-rust
$ yay -S i3status-rust-git ttf-font-awesome-4
# from now on, you can use pacman -S i3status-rust, the one in AUR is latest development version
$ sudo pacman -S iw

Basic set up

$ cd ~/.config/i3
$ wget https://poyichou.github.io/config_file/i3_config -O config
$ wget https://poyichou.github.io/config_file/i3_status_rs.toml -O status.toml

$ cd /etc/udev/rules.d/
$ sudo wget https://poyichou.github.io/config_file/backlight.rules
$ sudo usermod -a -G video <username>

To use gesture

# Install fusuma
$ sudo pacman -S libinput xdotool ruby
$ yay -S ruby-fusuma
$ mkdir ~/.config/fusuma/
$ wget -O ~/.config/fusuma/config.yml poyichou.github.io/config_file/fusuma_config.yml
$ fusuma # To run

Basic tips

# open a terminal
$mod + <enter>
# change window titling style to split/stack/tab
$mod + [e|s|w]
# change to other screen
$mod + <arrow> or $mod + [j|k|l|;]
# close a window
Ctrl + w or $mod + Shift + q

# change to another workspace
$mod + <num>
# shift a window to another workspace
$mod + Shift + num

# set themes
lxappearance

Problems

  • After running i3-dmenu-desktop --dmenu="cat", random grids appear
    Something triggered /usr/lib/xscreensaver/abstractile, to stop it, pkill abstractile
Docker

Notes-Docker

tcpdump in docker cannot open

# Error message:
#tcpdump: error while loading shared libraries: libcrypto.so.1.0.0: cannot open shared object file: Permission denied
mv /usr/sbin/tcpdump /usr/bin/tcpdump

Python causes IOError: [Errno 28] No space left on device

Python throw exception 'IOError: [Errno 28] No space left on device' while there's still lots of space on disk.  
'joblib' might try to parallelize jobs.  
When environment variable 'JOBLIB_TEMP_FOLDER' is not set, it consume '/dev/shm' to handle inter process communication.  
'/dev/shm' is by default 64MB in docker. 'joblib' might not detect such limitation.  
Any python module depending on 'joblib' such as 'sklearn' might encounter such exception.

Solution 1

JOBLIB_TEMP_FOLDER=/tmp python [args...]

Solution 2
Add following in python code.

import os
os.environ['JOBLIB_TEMP_FOLDER'] = '/tmp'

Solution 3
Increase /dev/shm size with such command.

docker run --shm-size=512m <image-name>
Arduino

Notes-Arduino

Compile error

# error message: 'Caused by: jssc.SerialPortException: Port name - /dev/ttyACM0; Method name - openPort(); Exception type - Permission denied.'
# solution: add current user into dialout group
sudo usermod -a -G dialout $USER
Android

Notes-Android

Problem solution

in adb shell, even w/ root privilege
note that android 10 seems to prevent anything from mounting system as R/W, so solution above may not work anymore.

# mv xxx /system/bin
#mv: /system/bin/xxx: Read-only file system
# mount # to check mount information
# mount -o remount -o rw /

tshark in android

# binary, it require root access with user name "root"
# Note that in some rooted devices, the user name from following command is shell rather than root
#  adb shell
#  su
#  echo $USER # the answer shoud be root
https://github.com/hasanbulat/tshark-arm64
# check esp related option
tshark -G currentprefs | grep 'esp\.'
# esp auto decode if null decryption
tshark -o esp.enable_null_encryption_decode_heuristic:TRUE [other option]

Log in to Termux environment

Termux is a good tool if you need to run program such as python, tshark in android You can later install tsu to get sudo in Termux Prerequisite

rooted Android phone
Install Termux from Google Play

In Termux

$ pkg install root-repo # don't append other package here, install it until you succeed
$ pkg install openssh
$ sshd # to kill later, killall sshd
$ mkdir ~/.ssh # do if ~/.ssh not exist

In Linux

$ adb push .ssh/id_rsa.pub /sdcard # generate your own ssh key before
$ adb shell
$ su
# cd /data/data/com.termux/files/home/.ssh/
# cat /sdcard/id_rsa.pub >> authorized_keys
# chmod 600 authorized_keys # do if authorized_keys not 600

To use in Linux

## option 1, plug phone with usb
adb forward tcp:8022 tcp:8022
ssh -p 8022 root@localhost
## option 1, through wifi
ssh root@<local ip address>

To disable SSH host key checking for localhost append following in “~/.ssh/config”

Host localhost
   StrictHostKeyChecking no
   UserKnownHostsFile=/dev/null

To get sudo

# Magisk user
$ pkg install tsu
# Super SU user
# follow https://gitlab.com/st42/termux-sudo

To install sklearn in termux

$ pkg install python wget proot clang fftw libzmq freetype libpng pkg-config
$ curl -LO https://its-pointless.github.io/setup-pointless-repo.sh
$ bash setup-pointless-repo.sh
$ pkg install openblas gcc-10
$ termux-chroot
$ pip install -U pip
$ pip uninstall joblib
$ pip install joblib==0.11 Cython wheel
$ ln -s /data/data/com.termux/files/usr/bin/gfortran-10 /data/data/com.termux/files/usr/bin/gfortran
$ ln -s /data/data/com.termux/files/usr/lib/libgfortran.so.5 /data/data/com.termux/files/usr/lib/libgfortran.so
# -v for verbose mode to recognize problems if failed
$ NPY_NUM_BUILD_JOBS=1 pip install scikit-learn==0.23.2 -v

adb over WiFi(no root required)

Plug the device to PC through usb.

# list plugged devices,
# K1AXKN01F823YE5 is the ID of device in this case
$ adb devices
List of devices attached
K1AXKN01F823YE5	device

# show ip address of device,
# 192.168.1.125 is the IP of device in this case
$ adb -s K1AXKN01F823YE5 shell ip a show wlan0
22: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 40:b0:76:bc:39:30 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.125/24 brd 192.168.1.255 scope global wlan0
       valid_lft forever preferred_lft forever
    inet6 fe80::42b0:76ff:febc:3930/64 scope link 
       valid_lft forever preferred_lft forever

# restart the adbd daemon listening on TCP on the 5555 port.
$ adb -s K1AXKN01F823YE5 tcpip 5555

# connect to the device via TCP/IP
$ adb connect 192.168.1.125
connected to 192.168.1.125:5555

# show devices adb can find via usb and 192.168.1.125
$ adb devices
List of devices attached
K1AXKN01F823YE5 device
192.168.1.125:5555      device

Now you can connect to the device in following two ways.

# through usb
adb -s K1AXKN01F823YE5 [commands]
# through WiFi
adb -s 192.168.1.125:5555 [commands]

So it’s OK to unplug the usb cable now.
To restart the adbd daemon listening on USB,

# replace [ID of device] by K1AXKN01F823YE5 or 192.168.1.125:5555,
# depending on how the device and the PC are connected
$ adb -s [ID of device] usb
restarting in USB mode
GNS3

Notes-GNS3

Install instructions for Ubuntu(-based)

sudo add-apt-repository ppa:gns3/ppa
sudo apt update                                
sudo apt install gns3-gui gns3-server
# when prompted whether non-root users should be allowed to use wireshark and ubridge, select ‘Yes’ both times
sudo dpkg --add-architecture i386
sudo apt update
sudo apt install gns3-iou
# To support CISCO router Idle-PC finder
sudo apt install dynamips:i386
# remove old docker
sudo apt remove docker docker-engine docker.io
# install docker ce
sudo apt install apt-transport-https ca-certificates curl  software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - # import docker gpg key
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install docker-ce
# add groups
sudo usermod -aG ubridge <user_name>
sudo usermod -aG libvirt <user_name>
sudo usermod -aG kvm <user_name>
sudo usermod -aG wireshark <user_name>
sudo usermod -aG docker <user_name>

some error

# If not install dynamips:i386
Error: Could not send Dynamips command 'vm get_status "AUTOIDLEPC"' to x.x.x.x:xxxxx: Connection lost, process running: False
web-tools

Notes-web-tools

curl

When encounter such result, -L (wget -H for such web site)

<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>

wget

  • -r/--recursive download specified URLs, parse the markup to find links to other files, and then download those, repeating by default five times.
  • -A/--accept, -I/--include-directories=, -R/--reject specify patterns to filter the set above.
  • -np/--no-parent ensures that only URLs starting with the URLs you’ve given are downloaded.
fonts

Notes-fonts

Install fonts

  • Option1: Install with package manager
  • Option2: manually install
    • Donwload font files (e.g. ttf), puts them into a directory
    • Put the directory into /usr/local/share/fonts/

      To load font without reboot

      #regenerate fonts cache
      $ fc-cache -f -v
      #check installed fonts
      $ fc-list
      #check current fonts in effect
      $ fc-match
      
Nintendo_Switch

Notes-Nintendo_Switch

Audio coexistence with desktop for online chat

  • Sum up: Output Switch audio to a destop, then output both desktop and Switch audio with the desktop. So that you can play Switch along with Discord or other chat app in the desktop.
  • Requirement
    • desktop with Win10 x1
    • Switch x1
    • 3.5mm male-to-male cable x1
  • Step
    • Plug the 3.5mm cable to Switch and rear audio input jack of the desktop.
    • Right click the Speakers icon on the taskbar and select Sound (音效).
    • In Sound window, select Recording (錄製) tab.
    • In Recording tab, select Line in at rear panel (Blue) in the panel and check Properties (內容).
    • In Line in at rear panel (Blue) window, select Listen (接聽) tab and check Listen to this device (聆聽此裝置) then click OK (確定).
    • From now on there should be sound of Switch output from your desktop.
  • Trouble shooting
    • There’s buzz from Switch through the 3.5mm cable to the desktop
      • Solution1: Prepare an USB audio adapter, plug it to the Switch dock and plug the cable in switch side to the adapter, then play Switch in docked mode.
      • Solution2: Prepare a Ground Loop Noise isolator, place it between Switch and the desktop.
XRDP

Notes-XRDP

Test environment

Server: xrdp
Client: Remmina

Cannot start i3wm

Add following before other exec command in /etc/xrdp/startwm.sh

test -x /usr/bin/i3 && exec /usr/bin/i3

Cannot change resolution on-the-fly

This is a feature introduced in xrdp v0.9.16, which may not be available in some distribution

Windows

Notes-Windows

Shell environment

Install git-for-windows instead of normal Git.
Use the included bash for shell environment.

The included bash in git-for-windows provides much friendly environment than one in normal Git, such as pacman support.
With pacman support, installing packages such as python is much easier.
When using vim plugins such as jedi-vim, this is helpful compared to python installed from website or microsoft store.
Git

Notes-Git

Upstream interaction

# check all branches including upstream ones
git branch -a
# create new local branch which name is based on <remote branch>
#   set up upstream configuration
git checkout [--track|-t] <remote branch>

Gerrit

Set up commit hook

# 1. Obtaining hook script inserting Change-ID in each commit
# e.g. curl -L http://gerrit-review.googlesource.com/tools/hooks/commit-msg
curl -L http://<Gerrit Server>/tools/hooks/commit-msg
# 2. Put `commit-msg` into local `.git/hooks/`
# 3. If submodules exist, put `commit-msg` into corresponding `hooks/` in `modules/` in the same `.git/`

Commit

# insert name in commit message
# note that if the script for Change-ID is ready,
# the Change-ID will be inserted after completing commit message
git commit [-s|--signoff]

Push

# push to a special remote branch for others to review the changes
# e.g. git push origin master:refs/for/master
git push origin <local branch>:refs/for/<remote branch>

UTF-16 diff problem

Situations on utf-16 encoded file

"git diff" and "git log -p <utf16 file>" shows "Binary files a/xxx and b/xxx differ" instead of text content,  
"git log -p --text <utf16 file>" garbled in content.  

Solution

git config --global diff.utf16.textconv "iconv -f utf-16 -t utf-8"
echo "<utf16 file> diff=utf16" >> <repo root>/.gitattributes

Git is slow in windows

git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256

Git fails because of key type

Unable to negotiate with XX.XX.XXX.XXX : no matching host key type found . their offer: ssh-rsa

Solution
copy content below into ~/.ssh/config

Host XX.XX.XXX.XXX
	HostkeyAlgorithms +ssh-rsa
	PubkeyAcceptedKeyTypes +ssh-rsa
	IdentityFile ~/.ssh/id_rsa
	HostName XX.XX.XXX.XXX
	User xxx
	Port xxxx
Visual-Studio

Notes-Visual-Studio

Cannot find or open the PDB file in Visual Studio C++ 2010

Error log

'XXX.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', Cannot find or open the PDB file
...

Solution

# Tools->Options->Debugging->Symbols
# check Microsoft Symbol Servers
Vim

Notes-Vim

Example searches

/foo\(\(foo\)\@!\_.\)\{-}\d\{3}.\d\{3} ms\(\(foo\)\@!\_.\)\{-}foo

Search “xxx.xxx ms” between two “foo” (may be in diff lines) while other “foo” excluded

explain
\@! match zero width for preceding keyword
\_. any character including newline
\{-} match as few as possible
\d digit
\{3} repeat 3 times
\(\(foo\)\@!\_.\) any word excluding “foo”