linux_tips - thawk/wiki GitHub Wiki

Linux Tips

目录

1. 无缝运行Windows虚拟机中的程序

  1. 确保rdesktop已经安装(ubuntu缺省已安装)

    sudo apt-get install rdesktop
  2. windows中开启terminal service

    1. 开启 Terminal Services 服务

    2. 在 Administrative Tools/Terminal Services Configuration 中绑定网卡

    3. 自动关闭session

      Administrative Tools/Terminal Services Configuration 中 Sessions → Overwrite user settings → End Session

    4. 在防火墙上打开3389端口

  3. Turn off the desktop for the user you`ll use to run your Windows apps, by clicking Start → Run typing regedit and selecting HKEY_CURRENT_USER/Software/Microsoft/Windows/ CurrentVersion/Policies/Explorer. Create a DWORD called NoDesktop set to 1.

  4. 在windows中安装seamlessrdp

    1. http://www.cendio.com/seamlessrdp/ 下载

    2. 解压到 c:\\seamlessrdp

    3. 在ubuntu中通过 rdesktop -A -s "c:\\seamlessrdp\\seamlessrdpshell.exe notepad" 的形式运行程序

  5. (可选)windows中安装 Human for Windows theme

    1. http://www.deviantart.com/download/37743373/ 下载

    2. 解压到 c:\\windows\\resources\\themes

    3. gpedit.msc

      navigate to ''User Configuration/Administrative Templates/Control Panel/Display/Desktop Themes''

      open ''Load a specific visual style file or force Windows Classic ''

      enter ''C:\\windows\\resources\\Themes\\Human\\Human.msstyles as the style''

  6. 参考

2. 中文相关

2.1. 查找系统中的中文字体

fc-list :lang=zh

2.2. 查看字体属于哪个文件

fc-match -v "AR PL UKai CN"

2.3. 解决在utf-8下man中出现的<80><98>之类乱码字符

在/etc/man.conf中,在nroff的参数中加上 -Tascii ,强制用ascii进行转换即可

2.4. 按拼音排序

在.profile里加上

export LC_COLLATE="zh_CN.UTF-8"

2.5. 解决java程序中文乱码(如freemind等)

  1. 在jre的lib/fonts下建立fallback目录(archlinux下,应该是在/opt/java/jre/lib/fonts/目录下)

  2. 链接或拷贝一个中文字体到上述目录中

2.6. OpenOffice.org中文问题

2.6.1. 内容汉字显示为方框

Tools→Options→OpenOffice.org→Fonts中把Arial替换为SimSun或其它中文字体

2.7. 输入法设置

xinitrc
imes=(fcitx ibus scim)
for ime in ${imes[@]}
do
    prog=${ime}
    opts=-d
    module=${ime}
    case $ime in
        ibus)
            prog=ibus-daemon
            opts="-d -x"
            ;;
        fcitx)
            module=fcitx
            ;;
    esac

    if which ${prog} &> /dev/null
    then
        export XMODIFIERS=@im=${ime}
        export XIM=${ime}
        export GTK_IM_MODULE=${module}
        export QT_IM_MODULE=${module}
        ${prog} ${opts} & &> /dev/null
        break
    fi
done
fcitx

应安装fcitx-gtk2

3. rc.d/init.d启动脚本模板

#!/bin/bash

# /etc/rc.conf
# /etc/rc.d/functions

# program and arguments
PROGRAM=/usr/sbin/tinyproxy
# description
DESCRITION=tinyproxy
# daemon name
DAEMON_NAME=tinyproxy

PID=`pidof -o %PPID $PROGRAM`
case "$1" in
  start)
    stat_busy "Starting $DESCRITION"
    [ -z "$PID" ] && $PROGRAM
    if [ $? -gt 0 ]; then
      stat_fail
    else
      add_daemon $DAEMON_NAME
      stat_done
    fi
    ;;
  stop)
    stat_busy "Stopping $DESCRITION"
    [ ! -z "$PID" ]  && kill $PID &> /dev/null
    if [ $? -gt 0 ]; then
      stat_fail
    else
      rm_daemon $DAEMON_NAME
      stat_done
    fi
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  *)
    echo "usage: $0 {start|stop|restart}"
esac
exit 0

4. Xdefaults

4.1. 让vim能使用alt-功能键(作为一个键发出,而不是用esc序列)

!alt key
XTerm*eightBitInput:      true
XTerm*metaSendsEscape:    false

4.2. 将xterm识别为256色

XTerm*termName:           xterm-256color

5. screen

5.1. 一些配置

bind j focus down
bind k focus up
bind t focus top
bind b focus bottom
bind ^j focus down
bind ^k focus up
bind ^t focus top
bind ^b focus bottom
# I know about screen.  I don't need to see it every time I start the program.
# (Which is, admittedly, rarely.)
startup_message off
# I like a large scrollback
defscrollback 5000
# Run everything in UTF-8.
defutf8 on
# If a window goes unresponsive, don't block the whole session waiting for it.
defnonblock on

# Make screen messages stand out a little more - black on bright green.
sorendition "+b kG"

5.2. 状态条设置

# 黑底
#hardstatus alwayslastline "%{= kB}%{c}[$LOGNAME@%H]%{-} %-Lw%{= .G}%n%f* %t%{-}%+Lw%< %{c}%=%Y-%m-%d %c:%s %D"

# color test
#hardstatus alwayslastline "%{= kw}kw %{= rw}rw %{= gw}gw %{= yw}yw %{= bw}bw %{= mw}mw %{= cw}cw %{= ww}ww %{= dw}dw %{= Kw}Kw %{= Rw}Rw %{= Gw}Gw %{= Yw}Yw %{= Bw}Bw %{= Mw}Mw %{= Cw}Cw %{= Ww}Ww %{= Dw}Dw"

# 绿底,主机名称和时间使用蓝色,其它都使用缺省前景色,当前窗口使用缺省背景,兼容黑底白字和白底黑字
hardstatus alwayslastline "%{= gd}%{b}[$LOGNAME@%H] %{d}%-Lw%{-}%{dd}%n%f* %t%{-}%{d}%+Lw%{-}%< %{b}%=%Y-%m-%d %c:%s %D"

5.3. xterm hardstatus hack

# Add stuff to xterm (and cousins) title bars.  This is a moderate abuse of the
# hardstatus feature--it just puts the hardstatus stuff into an xterm title
# bar.
termcapinfo xterm*|Eterm|mlterm 'hs:ts=\E]0;:fs=\007:ds=\E]0;screen\007'
defhstatus "screen  (t) | $USER@H"
hardstatus off
# 256 color xterm
attrcolor b ".I"
termcapinfo xterm 'Co#256:AB=\E[48;5;%dm:AF=\E[38;5;%dm'
defbce "on"
# Variants on Sven's custom messages.
activity "%c activity -> %n%f %t"
bell "%c bell -> %n%f %t^G"
vbell_msg " *beep* "
# Make shift-PgUp and shift-PgDn work like they do in xterm.  (Note that this
# requires xterm to be configured to pass those keys through, and not try to
# act on them itself.)
bindkey "^[[5;2~" eval "copy" "stuff ^u"
bindkey -m "^[[5;2~" stuff ^u
bindkey -m "^[[6;2~" stuff ^d

5.4. 显示caption

在分割窗口时,把当前region和非当前region区别显示

%?%F活动窗口设置%:非活动窗口设置%?
#hardstatus alwayslastline "%{= cb}[$LOGNAME@%H] %{=r dd}%-Lw%{-}%{dd}%n%f* %t%{-}%{=r dd}%+Lw%{-}%< %{b}%=%Y-%m-%d %c:%s %D"
caption always "%?%F%{= cb}%:%{= cc}%?[$LOGNAME@%H] %?%F%{=r dd}%:%{= cd}%?%-Lw%{= dd}%n%f* %t%?%F%{=r dd}%:%{= cd}%?%+Lw%?%F%{= cb}%:%{= cc}%?%< %=%S %Y-%m-%d %c %D"

5.5. 在ssh登录时自动启动screen

加入到.bashrc中

# 通过ssh登录时,自动启动一个screen,或重用原来的session
if [ "$SSH_CONNECTION" ]; then
    if [ -z "$STY" ]; then
        # Screen is not currently running, but we are in SSH, so start a session
        screen -d -R ssh
    fi
fi

6. readline

6.1. 移动

M-3 M-b

M-b M-b M-b 向后3 words

M-f

向前一个word

M-b

向后一个word

C-a

行首

C-z

行末

6.2. 历史

C-r

增量搜索历史,再按C-r可以列出下一个找到的历史。C-j接受

6.3. 补全

C-x ~

列出用户名补全

C-x /

列出文件名补全

C-x $

列出bash变量补全

C-x @

列出主机名补全

C-x !

命令补全

M-~

用户名补全

M-/

文件名补全

M-$

bash变量补全

M-@

主机名补全

M-!

命令补全

6.4. killing and yanking

C-k

kill to line end

C-u

kill whole line

C-w

删除光标前的word,放入kill ring

M-d

删除光标后的word

C-y

从kill ring粘贴一项。可以用M-y在kill ring中循环选择

M-\

删除光标附近的空白字符

6.5. 大小写

M-l

将光标后的word小写

M-u

将光标后的word大写

M-c

将光标后的word Capitalize

7. bash

8. 用户管理

8.1. 把一个用户名改为另一个,同时改用户的HOME目录的名称

exec sudo -i
killall -u oldname
id oldname
usermod -l newname oldname
groupmod -n newname oldname
usermod -d /home/newname -m newname
usermod -c “New_real_name” newname
id newname

9. systemd

9.1. 启用服务

sudo systemctl enable <name>

9.2. 启动时,用DHCP配置网络

sudo systemctl enable dhcpcd@eth0

9.3. journalctl查看日志

# 过滤
journalctl SYSLOG_IDENTIFIER=router_guard -b

9.4. 自动运行自己的脚本

使用指定用户,使用指定的virtualenv运行

  1. /etc/systemd/system/router-guard.service

    [Unit]
    Description=What this service does
    
    [Service]
    User=user
    Type=oneshot
    ExecStart=/home/user/.virtualenvs/router_guard/bin/python /home/user/workspace/router_guard/router_guard.py guard
    
    [Install]
    WantedBy=multi-user.target
  2. 启用

    sudo systemctl enable router_guard

10. 命令行小工具

10.1. 查看当前终端是否支持256色

infocmp | grep color
tput colors

10.2. diff/patch

diff -ruN originaldirectory/ updateddirectory/ > patchfile.patch
patch -p0 -i patchfile.patch
Note

geexbox要求用 Make unified diffs ('diff -Naur' or 'hg diff').

Unified diffs can be applied easily with 'patch'. This is much harder with other diff types. Create the diff from the root of the GeeXboX source tree, this makes the diff easier to apply as it saves the step of changing to the correct directory.

10.3. grep

10.3.1. 在二进制文件中查找内容

-a

把二进制文件当作文本文件

-b

输出要查找的内容在文件中的位置

-o

只输出匹配的内容

grep -abo something *

10.3.2. 按段查找内容

可以放到.bashrc中:

grepp() {
  if test -z "$1" || test -z "$2" ; then
    echo "USAGE: grepp searchterm filetosearch";
  else
    perl -00ne "print if /$1/i" < $2
      fi
}

10.3.3. 搜索二进制数据

perl -ln0777e 'print pos(), "\n", join(" ", unpack("H2 "x17,$1)) while /(.....\0\0\0\xCC\0\0\0.....)/g' /path/to/myfile.bin

x17是打印17个byte。re中的.也代替一个字节。

grep -obUaP "\x01\x02" /bin/grep

10.4. awk

10.4.1. 通过正则表达式取匹配的部分内容

echo test4325363test | gawk 'match($0, "([^0-9]*)([0-9]+)(.*)", a) { print a[2] }'

10.5. sed

10.5.1. 压缩连续的空行

sed 'N;/^\n$/d;P;D'

10.6. csplit

按内容分割文件

# 以匹配pattern的行作为每个文件的首行
csplit file.txt "/pattern/" "{*}"
# 以匹配pattern的行的下一行作为每个文件的首行
csplit file.txt "/pattern/+1" "{*}"

10.7. 7zip

10.7.1. 解压超过4G的大文件

在unzip超过4G的大文件时,unzip命令会出错: need PK compat. v4.5 (can do v2.1)

可以用7zip解压

7za e something.zip

10.7.2. 解压windows下压缩的含中文文件名的zip文件

#! /bin/sh
LANG=C /usr/lib/p7zip/7z x -y "$1" | sed -n 's/^Extracting  //p' | sed '1!G;h;$!d' | xargs convmv -f gbk -t utf8 --notest >\dev\null 2>\dev\null

10.8. 查看一个大文件的前面几字节

dd if=Recv1203.zip count=2 bs=1

10.9. 常用的用户和组管理命令

gpasswd -a USERNAME audio # 把用户加入到组中

10.10. 命令行画图工具

10.10.1. gnuplot

Plotting package which outputs to X11, PostScript, PNG, GIF, and others.

可以根据公式作图。

参数
set title    # 设置图片标题
set xlabel   # 设置x轴的文字
set ylabel   # 设置y轴的文字
set dummy x  # 设定x为自变量
plot [0:1] [-1:1] sin(x) # 画出sin(x)的图形。X轴范围是[0,1],Y轴范围是[-1,1]

set datafile separator ","  # 输入是以逗号分隔的CSV文件

set xdata time              # X轴是时间,其格式用下面的timefmt设定
set timefmt "%H%M%S"        # 设定时间的格式

10.10.2. 其它

rrdtool

可以用来画各种图表。X轴是时间

JFreeChart

http://www.jfree.org/jfreechart/

10.11. 破解rar密码

crark

10.12. urlencode/urldecode

如果没有参数,会从标准输入中读取

urlencode() {
    if [ $# -gt 0 ];
    then
        echo "$@" | perl -MURI::Escape -lne 'print uri_escape($_)'
    else
        perl -MURI::Escape -lne 'print uri_escape($_)'
    fi
}

urldecode() {
    if [ $# -gt 0 ];
    then
        echo "$@" | perl -MURI::Escape -lne 'print uri_unescape($_)'
    else
        perl -MURI::Escape -lne 'print uri_unescape($_)'
    fi
}

10.13. perl cpan

一般应该用root权限运行,以便把模块安装到系统中

sudo cpan 会进入其命令行

10.13.1. 升级cpan

install cpan
reload cpan

10.13.2. dbfdump

install DBD::XBase

10.14. 去掉ANSI Color Code

ansiesc() {
    sed -e 's/^[\[[0-9;]\+m//g'
}

10.15. 为不支持readline的程序加入行编辑功能 rlwrap

rlwrap 程序

10.16. ps

ps aux

显示所有进程

ps -eo comm

显示所有进程的程序名,不含参数

10.17. tr

删除\t\n以外的控制字符

+

tr -d '[\000-\010][\013-\037]'

10.18. 把目录中的文件按时间重命名rename

n=0; ls -tr | while read i; do n=$((n+1)); mv -- "$i" "$(printf '%03d' "$n")"_"$i"; done

10.19. peco/percol 交互式的grep

10.19.1. percol

sudo pip install percol

10.19.2. peco

比percol更快

install-peco.sh
#!/usr/bin/env bash
# Usage: BINDIR=$HOME/bin/ bash install-peco.sh
set -o xtrace       # for debug output.  ( abbr. set -x )
set -o errexit      # for exit on error. ( abbr. set -e )
set -o pipefail     # errexit for pipe
set -o nounset      # exit when the script to use undeclared variables (abbr. set -u)

filename=peco_linux_amd64.tar.gz

latest_tag="$(curl -L --head https://github.com/peco/peco/releases/latest | grep -i location: | sed 's/^.*\/tag\/\([^\/]*\)\r$/\1/')"
uri_to_download="https://github.com/peco/peco/releases/download/${latest_tag}/${filename}"
bindir="${BINDIR:-"$HOME/bin/"}"

pushd "$(mktemp -d "/tmp/tmp.XXXXXXXXXX")"
    curl -O -L "$uri_to_download"
    tar xf "$filename"
    cp "${filename%%.*}/peco" "$bindir"
popd

if [[ ! -x "${bindir}/peco" ]]; then
    echo '"peco" was not successfully installed!' >&2
    exit 2
fi

10.20. fpp(PathPicker)从任意输出提取路径

10.21. tar

# 不保存路径,提高时间戳的精度
tar --transform 's/.*\///g' -cjvf ~/storage/downloads/audio.tar.bz2 -H posix

10.22. 从模板创建项目

10.23. 查看键盘输入的是什么键序列

sed -n l

10.24. GNU Datamash 命令行数据统计工具

可以进行分组求和、平均之类的操作。

11. 数字进制转换

11.1. 设置bc的输出精度

scale=10
700/12

11.2. dec to hex

echo 'obase=16; ibase=10; 64206' | bc

11.3. hex to dec

echo $((0x2dec))

12. 搜索man page

apropos

13. lsof

lsof是一个用来显示被打开的文件的强大而有用的工具。在Unix系统中,任何事物都是文件(everything is a file),pipe是文件,IP sockets是文件,unix sockets是文件,目录是文件,设备是文件,inodes是文件。

一些有用的例子:

当在lsof后边没有跟任何参数时,该命令将会列出当前系统中被所有进程打开的所有文件

lsof|nl     #nl命令打印出行号

下边这几个命令指出打开某文件的进程

lsof `which httpd`   #那个进程在使用apache的可执行文件
lsof /etc/passwd      #那个进程在占用/etc/passwd
lsof /dev/hda6         #那个进程在占用hda6
lsof /dev/cdrom       #那个进程在占用光驱

下边将会打印出占用httpd可执行文件的进程的进程号(仅仅是进程号,在编写shell脚本是有用)

lsof -t `which httpd`

显示出那些文件被以k打头的进程名的进程打开,以bash打头,和以init打头:

lsof -c k
lsof -c bash
lsof -c init

显示出那些文件被以courier打头的进程打开,但是并不属于用户`zahn`

lsof -c courier -u ^zahn

显示被zahn和apache打开的文件

lsof -u apache,zahn

显示那些文件被pid为30297的进程打开:

lsof +p 30297

显示所有在/tmp文件夹中打开的instance和文件的进程。但是symbol文件并不在列

lsof -D /tmp

显示所有打开的端口

lsof -i

显示所有打开80端口的进程

lsof -i:80

显示所有打开的端口和UNIX domain文件:

lsof -i -U

显示那些进程打开了到www.akadia.com的UDP的123(ntp)端口的链接:

14. network网络

14.1. 固定设备名称

由于网络设备驱动是并行加载的,因此如果有多张网卡,每次启动后,其名称可 能不同,导致配置错误。

可以用udev或者ifrename把名称固定下来:

  • udev

    创建/etc/udev/rules.d/10-network.rules,内容参照下面:

    SUBSYSTEM=="net", ATTRS{address}=="00:1e:58:48:33:08", NAME="lan"
    SUBSYSTEM=="net", KERNEL=="tap1", NAME="vpn"
    SUBSYSTEM=="net", KERNEL=="tap5", NAME="qemu"
    Note
    要确保使用的是小写的十六进制字母。
  • ifrename(包含在wireless_tools中)

    • 直接运行ifrename

      ifrename -i eth0 -n lan
    • 使用配置文件

      1. 创建配置文件/etc/iftab

        lan      mac 00:0C:6E:C6:94:81
        internet mac 00:0C:6E:C6:94:82
      2. 运行

        ifrename -c /etc/iftab

14.2. 查看系统使用的临时端口范围(Ephemeral Port Range)

cat /proc/sys/net/ipv4/ip_local_port_range

14.3. 查看一个端口被谁占用

lsof -i tcp:80

14.4. DNS

14.4.1. 目前可用的DNS有

Comodo Secure DNS
  1. 156.154.70.22

  2. 156.154.71.22

Google DNS
  1. 8.8.8.8

  2. 8.8.4.4

诺顿 DNS
  1. 198.153.194.1(可用速度较快)

  2. 198.153.192.1(已经不可用)

Open DNS
  1. 208.67.222.222

  2. 208.67.220.220

教育网段IPv6用户可以更改DNS为
  1. 2001:4860:4860::8888

  2. 2001:4860:4860::8844

香港
  1. 202.181.224.2

台湾
  1. 168.95.192.1

  2. 168.95.1.1

澳门大学
  1. 202.175.3.8

  2. 202.175.3.3

美国
  1. 208.151.69.65

  2. 205.252.144.228

  3. 202.181.202.140

日本
  1. 202.12.27.33

  2. 202.216.228.18

14.4.2. /etc/resolv.conf DNS配置

用DHCP的话,可以不设置,自动从DHCP服务器获取。

# opendns
nameserver 208.67.220.220
nameserver 208.67.222.222

# 台湾中华电信
nameserver 168.95.1.1

14.4.3. 用DHCP同时,使用静态DNS

如果既要用DHCP,又不想通过DHCP更新DNS设置,在 /etc/conf.d/dhcpcd 中,DHCPCD_ARGS中加入"-R"参数

DHCPCD_ARGS="-R -t 30 -h $HOSTNAME"
Note
在新版dhcpcd中,应该用"-C resolv.conf"代替"-R"参数

14.4.4. dns工具

dnsutils

14.4.5. 避免DNS污染

  1. 使用国外DNS

  2. rc.local下加入

    iptables -I INPUT -p udp -m udp --sport 53 -m u32 --u32 "0&0x0F000000=0x05000000 && 22&0xFFFF@16=0x5d2e0859,0xcb620741,0x0807c62d,0x4e10310f,0x2e52ae44,0xf3b9bb27,0xf3b9bb1e,0x9f6a794b,0x253d369e,0x9f1803ad" -j DROP
    iptables -I INPUT -p udp -m udp --sport 53 -m u32 --u32 "0&0x0F000000=0x05000000 && 22&0xFFFF@16=0x3b1803ad" -j DROP

14.5. iptables

14.5.1. port forwarding

iptables -t nat -I PREROUTING -p tcp --dport <EXTERNAL_PORT> -j DNAT --to <INTERNAL_IP>:<INTERNAL_PORT>
iptables -I FORWARD -p tcp -d <INTERNAL_IP> --dport <INTERNAL_PORT> -j ACCEPT [-s <EXTERNAL_IP>]

14.5.2. firewall

  • show rules:

    iptables [-t tables] [-L] [-nv] #tables defaults to filter
  • clean rules

    iptables [-t tables] [-FXZ]

14.5.3. 架设简单的网关

  1. 在 /etc/conf.d/iptables 中,加入

    IPTABLES_FORWARD=1
  2. 制定规则

    iptables -P FORWARD DROP
    iptables -A FORWARD -s 192.168.2.0/24 -j ACCEPT
    iptables -A FORWARD -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
    #iptables -t nat -A POSTROUTING -o eth1 -s 192.168.2.0/24 -j SNAT --to 10.19.78.5
    iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j MASQUERADE
    #iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -d 10.0.0.0/24 -o eth1 -j MASQUERADE

14.6. iproute

14.6.1. source based routing

echo "100 vpn" | sudo tee -a /etc/iproute2/rt_tables
sudo ip rule add from 172.31.0.0/24 table vpn
sudo ip route add default via 172.31.0.1 table vpn

14.6.2. port based routing

grep -q '^[[:space:]]*[[:digit:]]\+[[:space:]]\+VPN[[:space:]]*\(#.*\)\?$' /etc/iproute2/rt_tables || echo "1 VPN" | sudo tee -a /etc/iproute2/rt_tables
sudo /usr/sbin/ip route add default via 172.31.0.1 table VPN
sudo /usr/sbin/ip rule add from all fwmark 1 table VPN
# set mark
#sudo iptables -t mangle -A PREROUTING -p tcp -m multiport ! -d 172.31.0.0/23 ! --dports http,https,7709 -j MARK --set-mark 1
# 所有将去往eth0,又不在eth0网段,且不在允许端口范围内的报文将重定向
sudo /usr/sbin/iptables -t mangle -A OUTPUT      -p tcp -m multiport -o eth0 ! -d 192.168.0.0/16 ! --dports http,https,7709,ssmtp,pop3s -j MARK --set-mark 1
# change the source ip
sudo /usr/sbin/iptables -t nat    -A POSTROUTING -p tcp ! -s 172.31.0.0/24 -j MASQUERADE -o tap0

14.7. monitor网络监控

14.7.1. ntop

14.7.2. Cacti

Cacti 是一款基于 PHP 的网络流量监测工具,与 ntop 相比功能更强大。它通过 snmpget 获取数据,用 RRDtool 绘制图形。

cacti和ntop适合不同的场合,cacti适合监控分散在各地的服务器,treeview可以很好的组织视图,还有很多好用的插件,不光可以监控流量,还可以监控任何自己感兴趣的数据。抓取保存的rrd数据还可以做二次开发,或者直接在cacti里摆弄数据。相比指向ntop似乎就只能在网关上安装,适合监控内网的流量。

14.7.3. mrtg

14.7.4. iptraf

Cursor based console ip network monitor/sniffer

14.7.5. iftop

display bandwidth usage on an interface by host

14.8. USB联网线

增加一个 /etc/udev/rules.d/55-usb0.rules

ACTION=="add", SUBSYSTEM=="net", KERNEL=="usb0", RUN+="/sbin/ifconfig usb0 172.30.0.2 netmask 255.255.255.0"

14.9. firefox

14.9.1. cookies.sqlite to cookies.txt

#!/usr/bin/python

import sqlite3 as db
import sys

cookiedb = '/home/USENAME/.mozilla/firefox/PROFIL/cookies.sqlite'
targetfile = '/home/USERNAME/cookies.txt'
what = sys.argv[1]
connection = db.connect(cookiedb)
cursor = connection.cursor()
contents = "host, path, isSecure, expiry, name, value"

cursor.execute("SELECT " +contents+ " FROM moz_cookies WHERE host LIKE '%"
               +what+ "%'")

file = open(targetfile, 'w')
index = 0
for row in cursor.fetchall():
  file.write("%s\tTRUE\t%s\t%s\t%d\t%s\t%s\n" % (row[0], row[1],
             str(bool(row[2])).upper(), row[3], str(row[4]), str(row[5])))
  index += 1

print "Gesucht nach: %s" % what
print "Exportiert: %d" % index

file.close()
connection.close()

14.9.2. Use /dev/shm as cache

  1. open about:config

  2. 在右键菜单中new→string

  3. 新的键名为 browser.cache.disk.parent_directory

  4. 值为 /dev/shm

  5. 重启firefox,在/dev/shm下出现Cache目录证明设置成功

14.9.3. Firebug 插件

14.9.4. 优化sqlite数据库,提升firefox性能

Firefox 从 3.0 开始将书签、历史等信息存储到了 SQLite 数据库中,所以我们可以通过优化 SQLite 数据库来达到改善 Firefox 性能的目的。以下是操作步骤:

  1. 转到 Firefox 的 profile 目录,默认位于 ~/.mozilla/firefox/xxxxxxxx..default/;

  2. 若是针对单个的 SQLite 文件(如 places.sqlite)执行优化,则运行

    sqlite3 places.sqlite vacuum

    你也可以通过下列命令来对所有的 SQLite 文件执行优化:

    for s in *.sqlite; { sqlite3 $s vacuum; }
    Note
    如果在你的 Linux 系统上找不到 sqlite3,则需要先行安装。另外,在执行优化时,你也要关闭 Firefox。

14.9.5. scrapbook

先用sortxml.py把scrapbook.rdf处理为每个项目一行

每项一行
cat scrapbook.rdf | sed -n -e 'H' -e '/>/{s!^.*$!!;x;s!\n[ \t]*! !g;p;}'
找出所有目录编号与名称的对应关系
cat scrapbook.rdf | sed -n -e 'H' -e '/>/{s!^.*$!!;x;s!\n[ \t]*! !g;p;}' | \
sed -n -e '/^.*RDF:about="\([^"]*\)".*NS1:title="\([^"]*\)".*NS1:type="folder".*$/{s!!\1 \2!;p;}'
找出目录的层次关系。前面是当前项目,后面是父目录
cat scrapbook.rdf | sed -n -e '/^.*<RDF:Seq RDF:about="\([^"]*\)">.*$/{s!!\1!;h;}' -e '/^.*<RDF:li RDF:resource="\([^"]*\)"\/>.*$/{s!!\1!;G;s!\n! !;p;}'

14.9.6. 忽略插件版本检查

在 about:config 中,右键新建一个Boolean值, “extensions.checkCompatibility.<version>”,其中3.6.\*的version为3.6, 取值为false。

14.9.7. epubreader

epubreader支持opds,但其opds数据库需要经过md5验证,可以用脚本加入自己 需要的地址

  1. 准备好calibre2opds的数据库地址

    catelog
    小说xml http://dl.dropbox.com/u/????????/%E5%B0%8F%E8%AF%B4/_catalog/index.xml
    非小说xml http://dl.dropbox.com/u/????????/%E9%9D%9E%E5%B0%8F%E8%AF%B4/_catalog/index.xml
    Fiction xml http://dl.dropbox.com/u/????????/Fiction/_catalog/index.xml
    NonFiction xml http://dl.dropbox.com/u/????????/NonFiction/_catalog/index.xml
  2. 在firefox profile目录下,epub目录中(有epub.sqlite文件)执行

    cat catalog | while read t u; do echo "insert into catalog (name, start, search, language, code) values ('$t', '$u', '', '', '$(echo
    -n "${u}6sx4Al" | md5sum | sed -e 's/\s*-.*//')');"; done  | sqlite3 epub.sqlite

14.10. ThunderBird

从mailbox格式改为maildir
  1. 导出现有的邮件

    1. 全选邮件

    2. 另存为,保存到硬盘上

  2. 激活maildir支持

    1. go to preferences → advanced → configuration editor and look for “storeContractID”.

    2. change any occurrence of @mozilla.org/msgstore/berkeleystore;1 to @mozilla.org/msgstore/maildirstore;1

    3. 删除所有mailbox文件

    4. 退出thunder,并通过thunderbird -profilemanager重启thunderbird,创建新的profile

  3. 导入邮件

    把之前导出的邮件拖到thunderbird上即可

14.11. download tools

14.11.1. fatrat

Qt4 (C++) based download manager with support for HTTP, FTP, SFTP, BitTorrent, rapidshare and more

14.11.2. plowshare

可以下载megaupload、rapidshare、4shared等一系列网盘上的软件

14.11.3. wget

14.11.4. mldonkey

修正中文文件名变为下划线的问题

archlinux下,在/etc/conf.d/mldonkey中增加两行,把mldonkey启动时的语言改为中文即可

LANG=zh_CN.UTF8
LC_ALL=zh_CN.UTF8
命令行下查看下载情况
使用 Awk 实现(by bones7466)
echo -e "vd\nquit" | nc 127.0.0.1 4000 | awk '/\[(D|B)/ { start=index($0,$7); filename=substr($0,start,index($0,$(NF-7))-start-length(FS)); if($(NF-1) > 0) { printf("\033[0;31m%-3i\033[0m \033[0;36m%5.1f\033[0m\033[0;33m%%\033[0m \033[0;36m%5.1f\033[0m\033[0;32mKB/s\033[0m \033[0;36m%s\033[0m\n",(NR-9),$(NF-7),$(NF-1),filename); } else { printf("\033[0;31m%-3i\033[0m %5.1f\033[0;33m%%\033[0m %5.1f\033[0;32mKB/s\033[0m %s\n",(NR-9),$(NF-7),$(NF-1),filename); } }'

14.11.5. aria2

单页面浏览器界面

14.11.6. BaiduPCS-Go

遇到这个错:

获取目录下的文件列表: 遇到错误, 远端服务器返回错误, 代码: 4, 消息: No permission to do this operation

可能是APPID被封杀了。

config set -appid 266719
#!/usr/bin/env node
const http  = require('http'),
      BDUSS = '<Your BDUSS>'; // Enter your BDUSS here

var request = function(appid, callback) {
    http.get({
            host    : 'pcs.baidu.com',
            port    : 80,
            path    : '/rest/2.0/pcs/file?app_id=' + appid + '&method=list&path=%2F',
            method  : 'GET',
            headers : {
                'Cookie': 'BDUSS=' + BDUSS,
                'User-Agent': 'netdisk;1.0'
            }
    }, function(res) {
        if (res.statusCode == 200) {
            callback(null, appid);
        } else {
            callback(null, null);
        }
    }).on('error', function(err) {
        callback(err, null);
    });
};

for (var i=266000; i<267000; i++) { // BUG: Too large span may cause timeout errors
    request(i, function(err, appid) {
        if (appid) {
            console.log('AppID ' + appid + ' is avalible.');
        }
    });
}

14.12. misc

  • geoip

  • inetutils

包含ftp/telnet/rcp/talk等工具的软件包

14.13. network profile

14.13.1. 需要的包

netcfg

14.13.2. 设置

  • 在/etc/network.d下为每种网络配置编写一个文本文件

  • ethernet

    CONNECTION="ethernet"
    DESCRIPTION="A very basic ethernet profile, using dhcp"
    INTERFACE=eth0
    IP="dhcp"
    DHCP_TIMEOUT=10
  • wep wireless

    CONNECTION="wireless"
    DESCRIPTION="A simple WEP encrypted wireless connection"
    INTERFACE=wlan0
    SCAN="yes"
    SECURITY="wep"
    ESSID=MyNetwork
    KEY="1234567890"
    IP="dhcp"
  • wpa wireless

    CONNECTION="wireless"
    INTERFACE=wlan0
    SCAN="yes"
    SECURITY="wpa"
    ESSID=mynetwork
    KEY="SomePasskey"
    IP="dhcp"
    TIMEOUT=20

14.13.3. 增加启用eth0后的时间,避免"No connection"错误

/usr/lib/network/connections/ethernet :

    ip link set $INTERFACE up

    # 增加等待时间
    for ((i=0;i<10;++i)); do
      sleep 1

      if ip link show $INTERFACE|grep -q "NO-CARRIER"; then
        continue
      fi

      break
    done
    # 等待结束

    if ip link show $INTERFACE|grep -q "NO-CARRIER"; then
       err_append "No connection"
       return 1
    fi

14.13.4. 使用

  1. 直接使用

    netcfg [profile_name]
    netcfg-menu
  2. 指定启动时使用的profile

    在/etc/rc.conf中加入:

    NETWORKS=(home)
  3. 在启动时让用户选择profile

    在/etc/rc.conf中加入:

    NETWORKS=menu
  4. 启动时自动搜寻无线网络

    在/etc/rc.conf中加入:

    AUTO_NETWORKS=(auto-wireless wlan0)

14.14. anonymous匿名

14.14.1. jondo

代替原来的jap

www.jondos.de

14.15. delegate代理转换

把本机9050端口的socks代理转换为8080端口的http代理。

delegated -P8080 SERVER=http SOCKS=localhost:9050

14.16. privoxy

14.16.1. 跳过google.com的重定向,并自动通过代理访问google cache

# 对www.google.com的重定向进行decode,将http%3A%2F%2F改写为http://,以便下一条规则中可以用fast-redirects直接访问最终的页面
{\
 +redirect{s@(www.google.com/url\?sa=t&source=web&ct=html&cd=1&url=http)%3A%2F%2F@$1://@}\
 +fast-redirects{check-decoded-url}\
}
 www.google.com/url

# 通过代理访问google cache
{+forward-override{forward 127.0.0.1:6066}}
 /search\?q=cache:

14.17. openvpn

14.17.1. archlinux下的openvpn DAEMON启动脚本

/etc/rc.d/openvpn : 启动脚本,可以自动扫描/etc/openvpn/*.conf文件,为每个文件启用一个VPN

#!/bin/sh
DAEMON=/usr/sbin/openvpn
DESC="virtual private network daemon"
CONFIG_DIR=/etc/openvpn
test -x $DAEMON || exit 0
test -d $CONFIG_DIR || exit 0

start_vpn() {
if grep -q '^[ \t]*daemon' $CONFIG_DIR/$NAME.conf ; then
    # daemon already given in config file
    DAEMONARG=
else
    # need to daemonize
    DAEMONARG="--daemon ovpn-$NAME"
fi

echo -n " $NAME"
STATUS="OK"

# Check to see if it's already started...
if test -e /var/run/openvpn.$NAME.pid ; then
    STATUS="FAILED - Already running (PID file exists)"
else
    $DAEMON --writepid /var/run/openvpn.$NAME.pid \
        $DAEMONARG --cd $CONFIG_DIR \
        --config $CONFIG_DIR/$NAME.conf < /dev/null || STATUS="FAILED"
fi

echo -n "($STATUS)"
}

stop_vpn() {
kill `cat $PIDFILE` || true
rm $PIDFILE
}

case "$1" in
start)
echo -n "Starting $DESC:"

# autostart VPNs
for CONFIG in `cd $CONFIG_DIR; ls *.conf 2> /dev/null`; do
    NAME=${CONFIG%%.conf}
    start_vpn
done
echo "."
;;

stop)
echo -n "Stopping $DESC:"

for PIDFILE in `ls /var/run/openvpn.*.pid 2> /dev/null`; do
    NAME=`echo $PIDFILE | cut -c18-`
    NAME=${NAME%%.pid}
    stop_vpn
    echo -n " $NAME"
done
echo "."
;;

# We only 'reload' for running VPNs. New ones will only start with 'start' or restart'.
reload|force_reload)
echo -n "Reloading $DESC:"
for PIDFILE in `ls /var/run/openvpn.*.pid 2> /dev/null`; do
    NAME=`echo $PIDFILE | cut -c18-`
    NAME=${NAME%%.pid}
    # If openvpn is running under a different user than root we'll need to restart
    if egrep '^( |\t)*user ' $CONFIG_DIR/$NAME.conf > /dev/null 2>&1 ; then
        stop_vpn
        sleep 1
        start_vpn
        echo -n "(restarted)"
    else
        kill -HUP `cat $PIDFILE` || true
        echo -n " $NAME"
    fi
done
echo "."
;;

restart)
shift
$0 stop ${@}
sleep 1
$0 start ${@}
;;

cond-restart)
echo -n "Restarting $DESC:"
for PIDFILE in `ls /var/run/openvpn.*.pid 2> /dev/null`; do
    NAME=`echo $PIDFILE | cut -c18-`
    NAME=${NAME%%.pid}
    stop_vpn
    sleep 1
    start_vpn
done
echo "."
;;

*)
echo "Usage: $0 {start|stop|reload|restart|force-reload|cond-restart}" >&2
exit 1
;;
esac

exit 0

# vim:set ai sts=2 sw=2 tw=0:

14.18. 安装rtl8192cu

  • 内核自带驱动

  • sudo pacman -S networkmanager

  • sudo pacman -S network-manager-applet

  • 配置PolicyKit

    建立/etc/polkit-1/localauthority/50-local.d/10-networkmanager.pkla

    [Let Wheel Use NetworkManager]
    Identity=unix-group:wheel
    Action=org.freedesktop.NetworkManager.*
    ResultAny=yes
    ResultInactive=no
    ResultActive=auth_self_keep
  • 在/etc/rc.conf中,禁用network,改用networkmanager

    sudo /etc/rc.d/network stop
    sudo ip link set down eth0
    sudo ip link set down wlan0

14.19. 配置wireless无线网WPA2 AES

  1. 安装wpa_supplicant

  2. 生成配置文件

    wpa_passphrase mywireless secretpassphrase > /etc/wpa_supplicant.conf
    Note
    可以追加多个配置到同一个配置文件
    # allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel
    
    network={
            # 对于隐藏ssid的wpa2网络,需要加上scan_ssid才能找到
            scan_ssid=1
            ssid="mywireless"
            #psk="secretpassphrase"
            psk=b90e230f1f2f5361a9b2d3acf276745ee3c751c0724a3b0052d6df15ec420e69
    }

14.20. 架设wireless AP

14.20.1. 测试网卡是否支持master模式

  1. 查看有几块网卡

    ifconfig -a
  2. 使用iwconfig

    # 在wireless-tools包中
    sudo iwconfig wlan0 mode master

    如果看到下面提示,说明测试失败:

    Error for wireless request "Set Mode" (8B06) :
        SET failed on device wlan0 ; Invalid argument.
  3. 使用iw

    有些新的网卡用的是mac80211 framework,对于这些网卡的话, 用iwconfig来测试它是否支持master模式是行不通的。 因为他们是使用新的 nl80211接口在用户空间通信的,可以用iw试一下:

    # 在iw包中
    iw list

    如果在“Supported interface modes”中有“AP”就说明支持,否则不支持:

    Supported interface modes:
             * IBSS
             * managed
             * AP
             * AP/VLAN
             * monitor

14.20.2. 配置hostapd

  1. 使用最简配置进行测试

    #change wlan0 to your wireless device
    interface=wlan0
    driver=nl80211
    ssid=test
    channel=1

    测试hostapd

    sudo hostapd ./hostapd.conf

    这个信息表示hw_mode (a, b or g)设置不正确

    Hardware does not support configured mode
    wlan0: IEEE 802.11 Hardware does not support configured mode (2)
    Could not select hw_mode and channel. (-2)
    wlan0: Unable to setup interface.
    rmdir[ctrl_interface]: No such file or directory
  2. 了解所使用的设备的能力

    Encryption: wpa-psk + tkip
    Wireless Mode: g
    Normal for an environment that has to support semi legacy devices, that don't support ccmp or wpa2
    Encryption: wpa2-psk + ccmp
    Wireless Mode: g+n
    Normal for an environment that has only up to date hardware and software
    Encryption: wep
    Wireless Mode: b
    This is the works case scenario, as wep is broken and can be trivially cracked.  Don't consider this as anything more than keeping casual free loaders out.
  3. 正式配置

    1. Wireless Interface

      interface

      Tells hostapd what wireless interface to use

      bridge

      Set to a bridge if the wireless interface in use is part of a network bridge interface

      driver

      For our purposes, always nl80211

      If you only have 1 wireless interface, and it’s going to be bridged with a wired interface, a good example setup would be:

      interface=wlan0
      bridge=br0
      driver=nl80211
    2. Wireless Environment

      ssid

      Sets the name (SSID = service set identifier) of the network, wireless extensions/iwconfig incorrectly calls this "essid".

      hw_mode

      Sets the operating mode of the interface, and the allowed channels. Valid values depend on hardware, but are always a subset of a, b, g

      channel

      Sets the channel for hostapd to operate on. Must be a channel supported by the mode set in hw_mode, as well as allowed by your countries Wireless Regulatory rules.

      ssid=MyNetwork
      hw_mode=g
      channel=1
      Note
      hw_mode中,g是最常用的选项
    3. 802.11n Setting

      如果需要使用802.11n,可以设置下面的选项。否则可以忽略

      ieee80211n

      Set to 1 to enable 802.11n support, 0 to disable it

      ht_capab

      A list of the 802.11n features supported by your device

    4. Authentication and Encryption

      macaddr_acl

      This controls mac address filtering. Mac addresses are easily spoofed, so only consider the use of this to be augmenting other security measures you have in place.

      auth_algs

      This is a bit field where the first bit (1) is for open auth, the second bit (2) is for Shared key auth (wep) and both (3) is both.

      ignore_broadcast_ssid

      This enables/disables broadcasting the ssid.

      wpa

      This is a bitfield like auth_algs. The first bit enables wpa1 (1), the second bit enables wpa2 (2), and bothe enables both (3)

      wpa_psk/wpa_passphrase

      These establish what the pre-shared key will be for wpa authentication.

      wpa_key_mgmt

      This controls what key management algorithms a client can authenticate with.

      wpa_pairwise

      This controls wpa’s data encryption

      rsn_pairwise

      This controls wpa2’s data encryption

      First, scratch macaddr_acl and ignore_broadcast_ssid from your priorities as they only enhance security (and even then, only slightly). Also, WEP has been effectively broken now, so unless you HAVE to support wep, scratch that from your list. This just leaves wpa/wpa2. Per the draft standard, wpa2 is required for 802.11n, and as there are known attacks on wpa now, wpa2 is the recommended authentication and encryption suite to use. Fortunately, you can have both enabled at once. If Windows clients are going to be connecting, you should leave ccmp encryption out of the wpa_pairwise option, as some windows drivers have problems with systems that enable it.

      • A good starting point for a wpa & wpa2 enabled access point is:

        macaddr_acl=0
        auth_algs=1
        ignore_broadcast_ssid=0
        wpa=3
        wpa_passphrase=YourPassPhrase
        wpa_key_mgmt=WPA-PSK
        wpa_pairwise=TKIP
        rsn_pairwise=CCMP

If, alternately, you just want to support wpa2, you could use something like:

macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=YourPassPhrase
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

14.20.3. 配置dhcp

  1. 安装dnsmasq

  2. 配置/etc/dnsmasq.conf

    • Choosing Your Interfaces

      interface=eth1
      interface=eth2
    • Basic DHCP Setup

      dhcp-range=eth1,192.168.100.100,192.168.100.199,4h

14.21. dante socks代理软件

/etc/sockd.conf:

logoutput: syslog
internal: 172.31.1.1 port = 8080
external: eth0
method: none
client pass {
    from: 172.31.1.2/24 port 1-65535 to: 0.0.0.0/0
    log: error
}
pass {
    from: 172.31.1.2/24 to: 0.0.0.0/0 port 1-65535
    method: none
    log: error
}

14.22. pure-ftpd

14.22.1. virtual user

  • create system user and group

    groupadd ftpgroup
    useradd -g ftpgroup -d /dev/null -s /etc ftpuser
  • file format of /etc/pureftpd.passwd

    <account>:<password>:<uid>:<gid>:<gecos>:<home directory>:<upload bandwidth>:<download bandwidth>:<upload ratio>:<download ratio>:<max number of connections>:<files quota>:<size quota>:<authorized local IPs>:<refused local IPs>:<authorized client IPs>:<refused client IPs>:<time restrictions>
  • add new user

    pure-pw useradd joe -u ftpuser -d /home/ftpusers/joe
    # -d :: chroot
    # -D :: don't chroot
    # -r :: allow client host
    # -R :: deny client host
  • change user

    pure-pw usermod
  • delete user

    pure-pw userdel <login> [-f <passwd file>] [-m]
  • change password

    pure-pw passwd <login> [-f <passwd file>] [-m]
  • show user info

    pure-pw show <login> [-f <passwd file>]
  • commit change / convert passwd file to puredb

    no need to restart pure-ftpd

    pure-pw mkdb

14.23. inetutils中的ftpd

Ftpd authenticates users according to three rules.

  1. The login name must be in the password data base, /etc/passwd, and not have a null password. In this case a password must be provided by the client before any file operations may be performed.

  2. The login name must not appear in the file /etc/ftpusers.

  3. The user must have a standard shell returned by getusershell(3).

  4. If the user name is anonymous or ftp, an anonymous ftp account must be present in the password file (user ftp). In this case the user is allowed to log in by specifying any password (by convention an email address for the user should be used as the password).

In the last case, ftpd takes special measures to restrict the client’s access privileges. The server performs a chroot(2) to the home directory of the ftp user. In order that system security is not breached, it is recommended that the ftp subtree be constructed with care, following these rules:

  • ~ftp

    Make the home directory owned by root and unwritable by anyone.

  • ~ftp/bin

    Make this directory owned by root and unwritable by anyone (mode 555). The program ls must be present to support the list command. This program should be mode 111.

  • ~ftp/etc

    Make this directory owned by root and unwritable by anyone (mode 555). The files passwd and group must be present for the ls command to be able to produce owner names rather than numbers. The password field in passwd is not used, and should not contain real passwords. The file motd, if present, will be printed after a successful login. These files should be mode 444.

  • ~ftp/pub

    Make this directory mode 777 and owned by ftp. Guests can then place files which are to be accessible via the anonymous account in this directory.

14.24. tor

14.24.1. 如何获取Tor的缓存文件:

目前,可以从以下地址获取不定时更新的Tor缓存文件(任选一个链接即可,请注意使用防病毒软件检查安全性):

转换为unix格式再放到/var/lib/tor下

14.25. ipv6

14.25.1. gw6c

sudo yaourt -S gw6c
sudo gw6c

14.26. pptp vpn

14.26.1. 安装

pacman -S pptpclient

14.26.2. 配置

sudo pptpsetup --create hpatc --server dialtone.atc-hp.com --domain ATLAB --username HTan --password Welcome09

具体的配置在/etc/ppp下,其中,用户名和密码信息在/etc/ppp/chap-secrets中,服务器信息在/etc/ppp/peers下

pptpsetup生成的配置文件中,可能domain和用户名之间可能只有一个反斜杠,应该是两个反斜杠。

pptpsetup生成的配置文件没有引用/etc/ppp/options.pptp,因此可以自己往/etc/ppp/peers下的配置中加入:

require-mppe-128
refuse-pap
refuse-eap
refuse-chap
refuse-mschap

14.26.3. 自动增、删路由信息

Note
脚本必须有运行权限。而且脚本中用到的命令要用全路径,否则会出现command not found的情况 ./etc/ppp/ip-up.d/50-route.sh
#!/bin/bash -

#"ppp0" "" "38400" "15.178.196.108" "15.178.196.100" "hpatc"
if [ "$6" = "hpatc" ]; then
    # need full path here
    /sbin/route add -net 15.178.199.0/24 dev ${IFNAME} &>> /tmp/env
    /usr/sbin/iptables -t nat -A POSTROUTING -s 172.31.1.2/32 -d 15.178.199.0/24 -o ${IFNAME} -j MASQUERADE
    /usr/sbin/iptables -A FORWARD -i ${IFNAME} -m state --state RELATED,ESTABLISHED -j ACCEPT
fi
/etc/ppp/ip-down.d/50-route.sh
#!/bin/bash -

#"ppp0" "" "38400" "15.178.196.108" "15.178.196.100" "hpatc"
if [ "$6" = "hpatc" ]; then
    /sbin/route del -net 15.178.199.0/24
    /usr/sbin/iptables -t nat -D POSTROUTING -s 172.31.1.2/32 -d 15.178.199.0/24 -o ppp0 -j MASQUERADE
    /usr/sbin/iptables -D FORWARD -i ${IFNAME} -m state --state RELATED,ESTABLISHED -j ACCEPT
fi

14.26.4. 启动

# 正常启动
sudo pon hpatc
# enable debug
sudo pon hpatc debug dump logfd 2 nodetach

14.26.5. 停止

sudo poff

14.26.6. FAQ

  • LCP terminated by peer

    可以启动debug看原因。可能是/etc/ppp/chap-secrets中,DOMAIN与Username之间是一个反斜杠,应该是两个反斜杠

  • No auth is possible

    可能是chap-secrets中有错误,或者options.pptp中指定的验证方式和server不一致

14.27. Redhat上,vsftpd出现500 OOPS: cannot change directory

setsebool ftpd_disable_trans 1
# 加上-P参数的话,在重启后还生效
# setsebool -P ftpd_disable_trans 1
service vsftpd restart

14.28. tcpdump

14.28.1. 常用命令行

# 看报文内容
tcpdump -nnvvXS
# 看UPNP消息(部分)
tcpdump -nevvv -s 0 '(udp port 1900) or (tcp port 2869)'

14.28.2. 命令行参数

  • -i any : Listen on all interfaces just to see if you’re seeing any traffic.

  • -n : Don’t resolve hostnames.

  • -nn : Don’t resolve hostnames or port names.

  • -X : Show the packet’s contents in both hex and ASCII.

  • -XX : Same as -X, but also shows the ethernet header.

  • -v, -vv, -vvv : Increase the amount of packet information you get back.

  • -c : Only get x number of packets and then stop.

  • -s : Define the snaplength (size) of the capture in bytes. Use -s0 to get everything, unless you are intentionally capturing less.

  • -S : Print absolute sequence numbers.

  • -e : Get the ethernet header as well.

  • -q : Show less protocol information.

  • -E : Decrypt IPSEC traffic by providing an encryption key.

14.28.3. 常用条件

  • and/or/not : 条件组合

  • host : look for traffic based on IP address (also works with hostname if you’re not using -n)

    tcpdump host 1.2.3.4
  • src, dst : find traffic from only a source or destination (eliminates one side of a host conversation)

    tcpdump src 2.3.4.5
    tcpdump dst 3.4.5.6
  • net : capture an entire network using CIDR notation

    tcpdump net 1.2.3.0/24
  • proto : works for tcp, udp, and icmp. Note that you don’t have to type proto

    tcpdump icmp
  • port : see only traffic to or from a certain port

    tcpdump port 3389
  • src, dst port : filter based on the source or destination port

    tcpdump src port 1025
    tcpdump dst port 389
  • src/dst, port, protocol : combine all three

    tcpdump src port 1025 and tcp
    tcpdump udp and src port 53
  • portrange : see traffic to any port in a range

    tcpdump portrange 21-23
  • Packet Size Filter : only see packets below or above a certain size (in bytes)

    tcpdump less 32
    tcpdump greater 128

14.29. mintmproxy

可以对页面内容进行处理

14.30. socat 更强大的netcat

在BashOnWindows下,使用socat适配keeagent
# If MSYSGIT socket in keeagent is set as c:\Users/foo/Documents/ssh_auth_msysgit
SSH_AUTH_KEEAGENT_SOCK=/mnt/c/Users/foo/Documents/ssh_auth_msysgit
SSH_AUTH_KEEAGENT_PORT=`sed -r 's/!<socket >([0-9]*\b).*/\1/' ${SSH_AUTH_KEEAGENT_SOCK}`

#use socket filename structure similar to ssh-agent
ssh_auth_tmpdir=`mktemp --tmpdir --directory keeagent-ssh.XXXXXXXXXX`
SSH_AUTH_SOCK="${ssh_auth_tmpdir}/agent.$$"

socat UNIX-LISTEN:${SSH_AUTH_SOCK},mode=0600,fork,shut-down TCP:127.0.0.1:${SSH_AUTH_KEEAGENT_PORT},connect-timeout=2 2>&1 > /dev/null &

15. 时钟

15.1. 修改系统时间

date -s 月/日/年
date -s 时:分:秒
date -s "月/日/年 时:分:秒"
hwclock --systohc

15.2. time_t转换为日期/时间

date -d @1268727836
date -d "1970-01-01 1268727836 sec GMT"

15.3. ntp

15.3.1. server

  • packet name: openntpd

  • config: /etc/ntpd.conf

  • 在ntpd.conf中加入servers=210.72.145.44

  • 在rc.conf加入openntpd

15.3.2. 单独校时

openntp/ntp都提供了校时的功能。也可以使用ntpdate

  • packet name: ntpdate

  • 使用

# 中国授时中心,其网址是 http://www.ntsc.ac.cn/
sudo ntpdate 210.72.145.44

15.3.3. Redhat下时区不正确的问题

RHEL 6.3上,/etc/localtime的属性为777时会导致时区错误。

时区设置方法:

  1. tzselect 选择一遍时区

  2. 执行 tzdata-update 同步时区配置

  3. 手工执行 hwclock --systz 命令设置好系统时区

16. 格式转换

  • 文件名编码转换

    convmv

  • dos2unix/unix2dos

    archlinux在hd2u包中,由dos2unix执行双向的转换

  • 查看word文档

    wv包

  • 查看excel文档

    xlhtml

  • pdftotext pdfimage

    poppler包

  • chm

  • html → latex

    gnuhtml2latex

17. blue tooth

  1. 安装 bluez-utils bluez-libs dbus portmap

  2. rc.conf中启动portmap、bluetooth

  3. 安装p3nfs

  4. 用 hciconfig 查看可用设备

  5. sudo hciconfig hci0 up 启用设备

  6. hcitool scan 查看可以连接的蓝牙设备

  7. sdptool search 查看设备上支持的服务

  8. 把蓝牙设备绑定到rfcomm上

    sudo rfcomm bind rfcomm0 00:0E:6D:94:A1:2C 5

    解除绑定:

    sudo rfcomm release rfcomm0
  9. 对码

    passkey-agent 1234 00:0E:6D:94:A1:2C

    passkey-agent --default 1234

    同时

    sudo cat /dev/rfcomm0
  10. mount 蓝牙设备

    sudo p3nfsd -series60 -tty /dev/rfcomm0 -dir /media/nokia6600 -user username

    也可以设置p3nfsd的s位,就不需要用sudo

    sudo chmod +s /usr/bin/p3nfsd

18. system monitor 系统临控

  • bootchart

    可以看系统启动时哪个进程占用了多少时间

  • sar

    sysstat包

  • acpi

    pacman -S acpi acpid

    make sure acpid runs before hal in rc.conf. then just use 'acpi' at the cli for details

  • iotop

    用来监视磁盘 I/O 使用状况的 top 类工具

  • 监测硬盘健康状况

    hdsentinel

19. archlinux

19.1. package

customizing PKGBUILD requires 'customizepkg'.

19.2. pacman-color

NOTE 1: if you want to use yaourt as user,
      you could add some entries in sudoers file:
         user ALL=NOPASSWD: /usr/bin/pacman
         user ALL=NOPASSWD: /usr/bin/pacdiffviewer
         Please, use sudo very carefully.
NOTE 2: voting for favorite packages on AUR requires 'aurvote'.
NOTE 3: customizing PKGBUILD requires 'customizepkg'.
NOTE 4: for a full colorized output, install pacman-color and set PacmanBin in /etc/yaourtrc

pacman-color have owns config: /etc/pacman-color.conf
pacman's config is included in pacman-color.conf

you can change any color in '/etc/pacman.d/color.conf'

19.3. powerpill

A wrapper for pacman that speeds up package retrieval by using aria2c for concurrent/segmented downloads.

可以代替pacman

在yaourt中使用的方法:
  1. 在powerpill配置文件中屏蔽多余的消息

    1. 生成powerpill的缺省配置文件~/.config/powerpill/powerpill.conf

      powerpill --gen-conf
    2. 在powerpill配置中加入—​nomessages

      ADDITIONAL_POWERPILL_ARGUMENTS = '--nomessages'
  2. 在yaourt配置文件(/etc/yaourtrc或~/.yaourtrc)中指定使用powerpill

    PacmanBin /usr/bin/powerpill

19.4. reflector

可以对及时更新的镜像进行排序

reflector -h 24 -t 25 -o reflector_mirrorlist

19.5. PKGBUILD

19.5.1. svn版本的例子

pkgname=exiv2-svn
pkgver=643
pkgrel=1
pkgdesc="Exif and Iptc metadata manipulation library and tools."
url="http://home.arcor.de/ahuggel/exiv2/"
license="GPL"
depends=()
makedepends=(autoconf subversion)
conflicts=()
replaces=()
backup=()
install=
source=()
md5sums=()

build() {
  mkdir -p $startdir/src/$pkgname
  cd $startdir/src/$pkgname
  svn co -r643 svn://dev.robotbattle.com/exiv2/trunk .
  cd ./config && autoconf && ./configure && make && cd ..
  ./configure --prefix=/usr
  make || return 1
  make DESTDIR=$startdir/pkg install
}

19.6. 查询一个文件属于哪个包

pkgfile -s wait.h

19.7. pacaur

sudo pacman -S expac yajl git --noconfirm

mkdir -p /tmp/pacaur_install
cd /tmp/pacaur_install

curl -o PKGBUILD https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=cower
makepkg --skippgpcheck
sudo pacman -U cower*.tar.xz --noconfirm

curl -o PKGBUILD https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=pacaur
makepkg --skippgpcheck
sudo pacman -U pacaur*.tar.xz --noconfirm

20. snap

20.1. 在ArchLinux下安装

sudo yaourt -S snapd
sudo systemctl enable --now snapd.socket

21. cdrecord

package

cdrkit

常用命令
  1. 制作镜像

    mkisofs -r -J -o cd_image.iso /directory
  2. 验证镜像

    sudo modprobe loop
    sudo mount -t iso9660 -o ro,loop=/dev/loop0 cd_image.iso /media/cdrom
    sudo umount /media/cdrom
  3. 刻录

    wodim --devices
    wodim --scanbus
    cdrecord -scanbus
    cdrecord -devices
    cdrecord -v -eject speed=8 dev=__0,1,0__ test.iso
    cdrecord dev=/dev/cdrom driveropts=burnfree -v -data cd_image.iso
    
    #把wav文件刻录成音乐CD
    cdrecord dev=/dev/cdrom driveropts=burnfree -v -audio [wav files...]
  4. 把.bin/.cue格式转换为.iso格式

    sudo apt-get install bchunk

    转换命令

    bchunk image.bin image.cue image.iso

22. partition/mount

22.1. mount dd image

sudo mount dd-image.img /mnt/tmp -o loop,offset=??
Note
关键是要知道offset。
  • 如果可以访问制作镜像的源设备,可以用

    sudo fdisk -ul /dev/sd?

    查看一下,并把Start扇区x512作为offset。

  • 尝试offset

    for ((i=0; $i < 1000; i=$i+1 ))
    do
      sudo mount dd-image.img /mnt/tmp -o loop,offset=$(($i * 512)) && echo done $i && break
    done

    offset不超过1000*512的话,都可以试出来

22.2. automount

安装 ivman,并在启动时运行即可

22.3. create vfat partition

cfdisk /dev/sd[x]
# mkfs.vfat is in dosfstools package
mkfs.vfat /dev/sd[x]1

22.4. 查看磁盘的UUID

  • blkid

  • ls -l /dev/disk/by-uuid/

22.5. 修改磁盘的UUID

uuidgen
tune2fs /dev/hdaX -U numbergeneratedbyuuidgen
verification with
vol_id /dev/hdaX

one can use xargs or a variable and ; to make that a one liner

uuidgen | xargs tune2fs /dev/hdaX -U ; vol_id /dev/hdaX

22.6. 调整顺序不正确的分区表

现象

分区在分区表中的排列顺序与物理顺序不符, 'fdisk -l' 时会显示

Partition table entries are not in disk order
解决
  1. sudo fdisk /dev/sda

  2. 选x进行 "extra functionality"

  3. 选f "fix partition order"

  4. 选p "print the partition table" 查看调整后的结果

  5. 没有问题的话,选w "write table to disk and exit"

  6. 修改/etc/fstab以反映所作的改动

  7. 修改grub的menu.lst以反映所作的改动

22.7. 把primary分区调整到extended分区中

参考资料
Merge Primary Partition into Extended Partition - Ubuntu Forums

http://ubuntuforums.org/showthread.php?t=1032234

步骤
  1. sudo fdisk -lu /dev/sda 查看分区信息

    Disk /dev/sda: 160.0 GB, 160041885696 bytes
    255 heads, 63 sectors/track, 19457 cylinders, total 312581808 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Disk identifier: 0x3b85059c
    
       Device Boot      Start         End      Blocks   Id  System
       /dev/sda1   *          63    83891429    41945683+   7  HPFS/NTFS
       /dev/sda2        83891430   167782859    41945715    7  HPFS/NTFS
       /dev/sda3       167782860   208748609    20482875   83  Linux
       /dev/sda4       208748610   297893294    44572342+   5  Extended
       /dev/sda5       208748673   261184769    26218048+  83  Linux
       /dev/sda6       261184833   297893294    18354231   83  Linux
  2. sudo sfdisk -d /dev/sda 查看分区信息

    # partition table of /dev/sda
    unit: sectors
    
    /dev/sda1 : start=       63, size= 83891367, Id= 7, bootable
    /dev/sda2 : start= 83891430, size= 83891430, Id= 7
    /dev/sda3 : start=167782860, size= 40965750, Id=83
    /dev/sda4 : start=208748610, size= 89144685, Id= 5
    /dev/sda5 : start=208748673, size= 52436097, Id=83
    /dev/sda6 : start=261184833, size= 36708462, Id=83
  3. 腾出扩展分区的空间

    要建立扩展分区的话,必须有63扇区的空间,因此需要把扩展分区前的分区调小63扇区以上,空出相应的空间

    此操作可以用gparted或其它工具进行

    在例子中把sda2缩小了

    $ sudo fdisk -lu /dev/sda
    
    Disk /dev/sda: 160.0 GB, 160041885696 bytes
    255 heads, 63 sectors/track, 19457 cylinders, total 312581808 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Disk identifier: 0x3b85059c
    
       Device Boot      Start         End      Blocks   Id  System
       /dev/sda1   *          63    83891429    41945683+   7  HPFS/NTFS
       /dev/sda2        83891430   167766794    41937682+   7  HPFS/NTFS
       /dev/sda3       167782860   208748609    20482875   83  Linux
       /dev/sda4       208748610   297893294    44572342+   5  Extended
       /dev/sda5       208748673   261184769    26218048+  83  Linux
       /dev/sda6       261184833   297893294    18354231   83  Linux
    $ sudo sfdisk -d /dev/sda
    
    # partition table of /dev/sda
    unit: sectors
    
    /dev/sda1 : start=       63, size= 83891367, Id= 7, bootable
    /dev/sda2 : start= 83891430, size= 83875365, Id= 7
    /dev/sda3 : start=167782860, size= 40965750, Id=83
    /dev/sda4 : start=208748610, size= 89144685, Id= 5
    /dev/sda5 : start=208748673, size= 52436097, Id=83
    /dev/sda6 : start=261184833, size= 36708462, Id=83
  4. 把上面的sfdisk的结果记录到partition.txt中

  5. 调整partition.txt中的分区布局

    增加扩展分区,并把各分区放到适当的位置。

    Note
    可以调整分区的顺序,但不要改动分区的start、size、Id等值
    Note
    例子中,在sda3处增加了一个扩展分区,分区的start正好是扩展分区中第一个分区(sda5)的start减去63扇区,扩展分区的start+size等于最后一个分区(sda7)的start+size

    partition.txt:

    # partition table of /dev/sda
    unit: sectors
    
    /dev/sda1 : start=       63, size= 83891367, Id= 7, bootable
    /dev/sda2 : start= 83891430, size= 83875365, Id= 7
    /dev/sda3 : start=167782797, size=130110498, Id= 5
    /dev/sda4 : start=        0, size=        0, Id= 0
    /dev/sda5 : start=167782860, size= 40965750, Id=83
    /dev/sda6 : start=208748673, size= 52436097, Id=83
    /dev/sda7 : start=261184833, size= 36708462, Id=83
    sudo sfdisk /dev/sda < partition.txt
    Note
    好像用重定向时,有一个分区的位置偏移了一个扇区,逐行拷贝的话,刚开始也有同样的问题,后来不知怎样再重复了几次后就好了
  6. 调整/etc/fstab及/boot/grub/menu.lst

23. vmware

23.1. vmware server 序列号

98R01-YU2F0-2F7EJ-4C6CM
98R2N-YKQ45-24K50-4LJR9
98R05-YK741-2FQ54-4T714
9AR25-YKP61-26L70-4HKJR
98924-YK640-24P5K-48QLD

23.2. set virtual Ethernet adapter on linux host to run in promiscuous mode

根据网络连接方式,为用户开放对应的/dev/vmnetX的rw权限即可。

  • 新建一个组,把权限开放给这个组

    chgrp newgroup /dev/vmnet0
    chmod g+rw /dev/vmnet0

23.3. port forwarding

# Enable forwarding
echo '1' > /proc/sys/net/ipv4/ip_forward
# Flush the NAT table
iptables -t nat --flush
# Masquerade all traffic
iptables --table nat --append POSTROUTING -j MASQUERADE
# Enable forwarding on VMWare interfaces
iptables --append FORWARD --in-interface vmnet1 -j ACCEPT
iptables --append FORWARD --in-interface vmnet8 -j ACCEPT
iptables --append FORWARD --out-interface vmnet1 -j ACCEPT
iptables --append FORWARD --out-interface vmnet8 -j ACCEPT
# Mail Forwading
iptables -t nat -A PREROUTING -p tcp --dport 110 -j DNAT --to-destination 192.168.87.1
iptables -t nat -A PREROUTING -p tcp --dport 25 -j DNAT --to-destination 192.168.87.1
iptables -t nat -A PREROUTING -p tcp --dport 2525 -j DNAT --to-destination 192.168.87.1

23.4. vmware server中打开内建的vnc服务

在.vmx文件中增加以下内容:

RemoteDisplay.vnc.enabled = "TRUE"
RemoteDisplay.vnc.password = "vncpassword"
RemoteDisplay.vnc.port = "5900"

23.5. 在vmware player中使用共享目录

在.vmx文件中增加以下内容:

sharedFolder0.enabled = "TRUE"
sharedFolder0.present = "TRUE"
sharedFolder0.writeAccess = "TRUE"
sharedFolder0.readAccess = "TRUE"
sharedFolder0.hostPath = "H:\ghost\"
sharedFolder0.guestName ="Ghostdisk"
sharedFolder0.eXpiration = "never"
sharedFolder.maxNum = "1"

24. email

24.1. mutt

24.1.1. application/octet-stream 附件的自动识别

在.muttrc中加入

mime_lookup application/octet-stream

24.1.2. 转发时带上原来的附件

缺省情况下,mutt 是把邮件原文引在正文里,然后转发的,并且缺省不带有附件,而我们很多时候更喜欢把原来的整个邮件作为附件转发,这个可以通过在配置文件里加入下面两行来实现:

set mime_forward=yes
set mime_forward_rest=yes
Note
除了正常的yes/no外,这两个值都可以取值为ask-yes/ask-no

24.1.3. mailcap

# word
application/msword; wvHtml --charset=utf8 '%s' - | w3m -T text/html; nametemplate='%s.doc'; copiousoutput
# excel(xlhtml)
application/excel; xlhtml %s | w3m -dump -T text/html; nametemplate='%s.xls'; copiousoutput
# powerpoint(xlhtml)
application/powerpoint; ppthtml %s | w3m -dump -T text/html; nametemplate='%s.ppt'; copiousoutput

24.1.4. Header中的RFC 2047编码decode

#!/usr/bin/perl
use Encode;
undef $/; # We want to treat everything read from STDIN as one line
print decode("MIME-Header", <>)

24.1.5. 修正查看gb2312 html附件乱码的情况

这是由于w3m引起的。用w3m -I gbk就是正常的。

可以用 w3m -o auto_detect=0 也是可以的,或者在 $HOME/.w3m/config 下:

auto_detect 0

24.1.6. 邮件搜索工具

Note
都不支持中文

24.1.7. 垃圾邮件过滤

crm114

spamfilter.lua+osbf-lua crm114的lua port

24.1.8. 查询外部地址本

lbdb
  1. 查询abook

    ~/.lbdb/lbdbrc下,METHODS中加入m_abook,ABOOK_FILES中列出需要的abook文件即可

    METHODS="m_inmail m_abook"
    ABOOK_FILES="$HOME/.abook/addressbook $HOME/.abook/szse $HOME/.abook/ssscc"
  2. 查询ldap

    需要 Net::LDAP(3pm) Perl modules from CPAN

    • ~/.lbdb/ldap.rc

      %ldap_server_db = (
        'contacts' => ['localhost', 'ou=contacts, dc=tommy, dc=com',
      		       'cn mail', 'cn mail o',
      		       '${mail}', '${cn}', '${o}',
                     '1'],
      );
    • ~/.lbdb/lbdbrc

      METHODS="m_inmail m_ldap"
      LDAP_NICKS='contacts'
  3. mutt中加入

    set query_command="lbdbq '%s'"

24.1.9. 使用Header Cache

可以避免每次进入一个目录时找时间的扫描。

在muttrc中加入:

set header_cache=/path/to/hcache

24.1.10. limit当前发件人发出的邮件

由于mutt会错误解释<enter>,因此在脚本中把<enter>分两部分输出。

macro index ,l "<enter-command>unset wait_key<enter><pipe-message>(echo -n \"push '<limit> ~f \"; echo -n $(formail -r -x \"To:\"); echo \"'<en\"\"ter>\")>/tmp/mutttmp.rc<return><enter-command>source /tmp/mutttmp.rc<enter><enter-command>set wait_key<enter>"
macro index ,a "<limit>all<enter>"

24.2. dovecot

提供IMAP服务

24.2.1. 生成SSL证书

相关脚本和配置文件
  1. mkcert.sh

    #!/bin/sh
    
    # Generates a self-signed certificate.
    # Edit dovecot-openssl.cnf before running this.
    
    OPENSSL=${OPENSSL-openssl}
    SSLDIR=${SSLDIR-/etc/ssl}
    OPENSSLCONFIG=${OPENSSLCONFIG-dovecot-openssl.cnf}
    
    CERTDIR=$SSLDIR/certs
    KEYDIR=$SSLDIR/private
    
    CERTFILE=$CERTDIR/dovecot.pem
    KEYFILE=$KEYDIR/dovecot.pem
    
    if [ ! -d $CERTDIR ]; then
      echo "$SSLDIR/certs directory doesn't exist"
      exit 1
    fi
    
    if [ ! -d $KEYDIR ]; then
      echo "$SSLDIR/private directory doesn't exist"
      exit 1
    fi
    
    if [ -f $CERTFILE ]; then
      echo "$CERTFILE already exists, won't overwrite"
      exit 1
    fi
    
    if [ -f $KEYFILE ]; then
      echo "$KEYFILE already exists, won't overwrite"
      exit 1
    fi
    
    $OPENSSL req -new -x509 -nodes -config $OPENSSLCONFIG -out $CERTFILE -keyout $KEYFILE -days 365 || exit 2
    chmod 0600 $KEYFILE
    echo
    $OPENSSL x509 -subject -fingerprint -noout -in $CERTFILE || exit 2
  2. dovecot-openssl.cnf

    需要进行定制,特别是CN应设为和服务器地址一致

    [ req ]
    default_bits = 1024
    encrypt_key = yes
    distinguished_name = req_dn
    x509_extensions = cert_type
    prompt = no
    
    [ req_dn ]
    # country (2 letter code)
    #C=FI
    
    # State or Province Name (full name)
    #ST=
    
    # Locality Name (eg. city)
    #L=Helsinki
    
    # Organization (eg. company)
    #O=Dovecot
    
    # Organizational Unit Name (eg. section)
    OU=IMAP server
    
    # Common Name (*.example.com is also possible)
    CN=imap.example.com
    
    # E-mail contact
    [email protected]
    
    [ cert_type ]
    nsCertType = server
生成步骤

把mkcert.sh和dovecot-openssl.cnf放在一个目录下,

sudo ./mkcert.sh

24.3. mbox ⇒ maildir

mb2md

24.4. 取得fetchmailrc所需的sslfingerprint

# 显示服务器证书
openssl s_client -connect email.ssscc.com.cn:995 -showcerts

# 将上面得到的证书保存为cert.pem,然后就可以用下面的命令看到fingerprint
openssl x509 -in cert.pem -noout -md5 -fingerprint

# 直接取得服务器sslfingerprint。可从日志处看到服务器的fingerprint信息
fetchmail -v ssscc.com.cn

24.5. 打印procmaillog中的邮件主题,并处理其encoding

#!/usr/bin/perl
use utf8;
use Text::Iconv;
use MIME::Base64;
use POSIX qw(locale_h);

sub get_curr_encoding
{
    my $enc = setlocale(LC_CTYPE);

    if ($enc =~ /^.*\.([^.]*)$/)
    {
        return $1;
    }

    return "utf8";
}

binmode(STDOUT, ":encoding(" + get_curr_encoding() + ")");
while (<>)
{
    next unless /^ Subject: /;

    s/=\?([^?]+)\?B\?([^?]*)\?=/Text::Iconv->new($1, get_curr_encoding())->convert(decode_base64($2))/eg;

    print;
}

25. ssh

ssh

26. ldap

26.1. ldapvi

用文本编辑器编辑ldap内容

26.2. gq

图形界面的ldap client

27. 修复grub

find /boot/grub/menu.lst
root (hd0,0)
setup (hd0)

28. multimedia

28.2. 拷贝vcd中的文件

VCD盘中的文件不能直接拷贝。有几种方法:

  1. 直接运行vcdxrip(属于VCDImager的一部分),会把VCD上的内容RIP为mpg文件存到当前目录

  2. 用mencoder

    mencoder vcd//:2 -oac lavc -ovc lavc -o filename.avi
  3. 用cdfs

    安装了cdfs后,可以mount VCD盘,拷贝其中的内容

    mount -t cdfs -o ro /dev/cdrom /mnt/video

28.3. mencoder

-endpos [[hh:]mm:]ss[.ms]

在多长时间后停止,和-ss一起用的话,是从-ss算起

-ss [[hh:]mm:]ss[.ms]

seek to 时间

28.3.1. 截取音频流

mencoder 01-双声恨.avi -of rawaudio -oac mp3lame -ovc copy -o 01-双声恨.mp3
# 增大音量
mencoder 01-双声恨.avi -of rawaudio -oac mp3lame -ovc copy -o 01-双声恨.mp3 -lameopts vol=9

28.4. Extract VCD .DAT’s (in RIFF format) to mpeg format

  • require 'transcode'

  • tcextract -x mpeg2 -i input.dat > output.mpeg

28.5. Convert Mpeg to MP4

  • require 'avidemux'

  • 用avidemux切分视频并保存为x264格式

    while read name pos;
    do
      avidemux2_cli --run ~/.avidemux/custom/x264_aac_mp4.js --load mpeg/${name}.mpeg --rebuild-index --audio-map --begin 0 --end $pos --save mp4/${name}-讲解.mp4;
      avidemux2_cli --run ~/.avidemux/custom/x264_aac_mp4.js --load mpeg/${name}.mpeg --rebuild-index --audio-map --begin ${pos} --save mp4/${name}-示范.mp4;
    done < mpeg/job
  • x264_aac_mp4.js

    var app = new Avidemux();
    
    //** Video Codec conf **
    app.video.codec("X264","AQ=26","188 00 00 00 00 00 00 00 00 00 00 00 00 28 00 00 00 1e 00 00 00 3c 00 00 00 0a 00 00 00 33 00 00 00 04 00 00 00 01 00 00 00 28 00 00 00 19 00 00 00 fa 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 04 00 00 00 10 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 ");
    
    //** Audio **
    app.audio.reset();
    app.audio.scanVBR();
    app.audio.codec("aac",128,4,"80 00 00 00 ");
    app.audio.normalizeMode=0;
    app.audio.normalizeValue=0;
    app.audio.delay=0;
    app.audio.mixer("NONE");
    
    //** Container **
    app.setContainer("MP4");
    
    //End of script

28.6. 下载网上视频

28.7. Convert flv to DVD

  • require ffmpeg

  • Steps

    To convert them, use this handy script; as above, save it in a text file, make it executable, and run it. Note that it resizes the videos to 352×240, which is more or less the size they are on youtube (but more importantly is the resolution of “VCD on DVD”). There is really not much point in scaling them up, as the resolution sucks. Instead, let your DVD player do the scaling when you come to play your disc; that`s what it`s good at.

    !/bin/bash
    mkdir mpg
    for file in *.flv
    do
            output=`ls $file -1|cut -f1 -d”.”`
            ffmpeg -i $file -ab 56 -r 25 -ar 22050 -b 500 -s 352×240 $output.mpg
    done
    mv *.mpg mpg
    cd mpg

    Let it do it`s thing; once it`s done, you`ll have a folder named mpg which contains the mpg versions of the videos.

28.8. mpg to DVD

  • require tovid. In archlinux, wxgtk-2.6 is needed to provide wxpython 2.6 support.

  • Steps

    Now we need to build the DVD structure. For this, we`re going to use tovidgui, which is one of the applications bundled with tovid. Run it, and follow these steps:
    - Click “Add Menu”
    - Click “Add Video(s)”
    - Browse to, and select all, your newly created MPGs
    - Click on one of the videos on the left pane
    - Under video options, choose “352×240 VCD on DVD”
    - Click “Use these settings for all videos”
    - Click the big “Encode” button at the top
    - Click Start encoding
    
    Let it do it`s thing. Once it`s done, it`ll give you a makedvd command to run, which in turn invokes dvdauthor. Run it. Dvdauthor will create the dvd structure, which you can then run (using kaffeine or gxine) or burn to dvd (using k3b, gnomebaker, etc, etc).
    
    And that`s it. Of course, the titles on the dvd are going to suck, since you didn`t change them to anything. If you want to spend some time making your dvd look pretty, play around with the options in tovidgui, and you`ll be able to customize it to your heart`s desire.

28.10. geexbox

archlinux depends packages:

nasm cdrkit zisofs-tools

28.11. mplayer

  • 看AVI需要装avisynth

28.11.1. 配置

  • 字幕字体

    ln -s /path/to/font ~/.mplayer/subfont.ttf
  • 字幕编码

    ~/.mplayer/config 中加入

    subcp=gbk
  • 字幕大小

    ~/.mplayer/config 中加入

    subfont-autoscale=1
    subfont-text-scale=5
  • 禁用xscreen-saver

    在新版mplayer中,只支持暂停标准接口的屏保,不支持xscreen-saver,因此需要使用mplayer提供的heartbeat机制,让xscreen-saver暂时不激活。

    ~/.mplayer/config 中加入

    heartbeat-cmd="xscreensaver-command -deactivate"

28.11.2. 查看视频文件的信息

mplayer -identify -nosound -vc dummy -vo null "视频文件名"

28.11.3. 播放DVD的菜单

mplayer dvdnav://

28.12. xmms2

编译

如果编译avcodec插件出错,可能是相应的头文件在系统中的路径不一样,可以修改一下:

sed -i -e 's#avcodec.h#libavcodec/avcodec.h#' $srcdir/src/plugins/avcodec/avcodec.c

28.13. id3

28.13.1. 编码转换

mutagen
mid3iconv -e gbk *.mp3
find . -iname "*.mp3" -execdir mid3iconv -e gbk {} \;

28.14. moc

console下的音乐播放器

28.14.1. 修正乱码问题(法1)

MOC正常显示中文MP3的tag有两个条件:

  1. tag是用UTF-8编码的

  2. 不存在ID3 v1 tag(就是旧版的MP3 Tag信息)

# 转换tag编码
find . -iname "*.mp3" -execdir mid3iconv -e gbk {} \;
# 然后删除ID3 v1 tag
find . -iname '*.mp3' -exec mid3iconv --remove-v1 {} \;

28.14.2. 修正乱码问题(法2)

~/.moc/config中加入:

ID3v1TagsEncoding = GB18030
UseRCC            = yes

28.15. 证件照片背景色值

证件蓝底

R:60 G:140 B:220 或 C:85 M:40 Y:0 K:0

证件红底

R:255 G:0 B:0 或 C:0 M:100 Y:100 K:0

中华人民共和国出入境/护照照片的背景蓝色值

R:67 G:142 B:219

二代身份证和社保相的背景色值

R:255 G:255 B:255 即纯白色

28.16. imagemagick

28.16.1. 压缩照片大小

  • quality in 85

  • progressive (comprobed compression)

  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.

  • Strip any comment or exif tag

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg target.jpg

批量in-place修改(注意做好备份):

mogrify -strip -interlace Plane -gaussian-blur 0.05 -quality 85% *.jpg

28.16.2. 图像自动切边(切除与角落相同颜色的边框)

简单切边(纯色边)
convert stripes.gif  -trim +repage   stripes_trimmed.gif
如果知道边框的颜色,为了防止图像有些边没有边框,可以先用边框色加上一个1x1的边框,再行切边,保证不会意外切除
convert stripes.gif -bordercolor red -border 1x1 -trim +repage   stripes_trim_red.gif
对于扫描的文件,可以用-blur将独立的噪点去除,定位要切的范围,再进行切边
convert noisy.jpg -crop `convert noisy.jpg -virtual-pixel edge -blur 0x10 -fuzz 15% -trim -format '%wx%h%O' info:`   +repage   noisy_trimmed_2.jpg
对“从一到无穷大”的处理
  1. 切除固定的边距,把边上的杂点和页码尽量去掉

    for i in *.pbm ; do echo $i; convert $i -shave 40x70 -negate -colors 2 ${i%%.pbm}-shave.png; done
  2. 把前面处理过的文件进行自动切边

    for i in *-shave.png ; do echo $i; convert $i -crop `convert $i -virtual-pixel edge -blur 0x8 -fuzz 15% -trim -format '%wx%h%O' info:` +repage ${i%%-shave.png}.png; done
对“三体”的处理
  1. 切边+二值化

    for i in *.ppm ; do echo $i; convert $i -shave 90x60 -fuzz 15% -trim +repage -contrast-stretch 10%,16% -colors 2 ${i%%.ppm}.png; done

28.16.3. 修改大小

用-extent wxh 可以指定图像新的大小,通过加边框实现,对图像进行缩放

# 加上透明边框,加边框后大小为14x14,原图片居中
convert dwindle.png -compose Src -gravity center -extent 14x14 new.png

28.16.4. 拼图

montage *.jpg  -tile 22x2  -geometry 64x256+0+0 10-.jpg

将目录里的jpg文件按顺序拼成x轴22块,y轴2块的图 ,每个图块的大小为64X512像素,输出文件为10-.jpg

28.16.5. 合并图片

convert +append 1.jpg 2.jpg 3.jpg .... 0.jpg

把 1.jpg、2.jpg、3.jpg等多张图片沿“水平方向”( +append)拼成 0.jpg(最后一个文件名是拼出的成品)

convert -append 1.jpg 2.jpg 3.jpg .... 0.jpg

把 1.jpg、2.jpg、3.jpg等多张图片沿“垂直方向”( -append)拼成 0.jpg(最后一个文件名是拼出的成品)

可以分两步,第一步把小图拼成多个水平方向的长条,第二步把长条按垂直方向合并成一个大图。

28.16.6. 切割图片

convert -crop 128x128 1.jpg 0.jpg

把大图1.jpg按128x128分割成了多张小图0-1.jpg 0-2.jpg …​

convert -crop 128x64+6+7 1.jpg 0.jpg

从1.jpg 以座标 6,7 为起点切一片 128x64 的块生成 0.jpg

28.16.7. 切图

convert -crop 448x512+0+0 0.jpg 1.jpg

从0.jpg 以座标 0,0 为起点切一片 448x512 的块生成你要的 1.jpg,相当于右边剪裁掉64像素

28.16.8. 锐化

convert -sharpen 5 0.jpg 1.jpg

将0.jpg 锐化后生成1.jpg,锐化指数5,此数值越大,锐化度越高,图像细节损失越大

28.16.9. 替换颜色

# 把blue换为white
convert balloon.gif -fill white -opaque blue   balloon_white.gif
# 用rgb指定颜色
convert dwindle.png -fill 'rgb(127,159,127)' -opaque 'rgb(220,220,204)' new/dwindle.png

28.16.10. 减少颜色

# quantize参数控制使用哪种色彩空间,会影响到把哪些颜色看作是近似的
# 可以有  RGB CMY sRGB GRAY   YIQ YUV OHTA XYZ   HSL HSB HWB
convert colorwheel.png -quantize RGB +dither -colors 16 output.png

28.16.11. 变灰度图像

convert color.png -colorspace GRAY output.png
# 还可以控制最终使用的颜色数量
convert colorwheel.png -quantize GRAY +dither -colors 16 output.png

28.16.12. 把与左上角相连的颜色填充为指定把

convert IMG_0074.JPG -normalize -fuzz 15% -fill 'rgb(60,140,220)' -draw 'color 0,0 floodfill' fill.jpg

28.17. 打开coreldraw cdr文件

用sk1

28.18. 图片查看器

  1. pho

  2. feh

  3. GPicView

  4. xzgv

  5. gqview

28.19. pulseaudio

28.19.1. 安装

  1. 安装程序

    sudo pacman -S pulseaudio
  2. 把用户加入到pulse-access组

    gpasswd -a USERNAME pulse-access

28.19.2. 配置网络

  1. Server装入module-native-protocol-tcp模块

    /etc/pulse/default.pa:

    load-module  module-native-protocol-tcp
  2. /etc/hosts.allow中允许pulseaudio-native服务

    /etc/hosts.allow:

    pulseaudio-native: ALL
  3. 从server上把pulseaudio的cookie拷贝到client上

    cookie在server上的/var/run/pulse/.pulse-cookie, 可以拷贝到clinet上的/etc/pulse-cookie

    client上的cookie文件要正确设置owner和权限

    # chown pulse:pulse-access /etc/pulse-cookie
    # chmod 640 /etc/pulse-cookie
  4. 在client上指定cookie文件的路径

    /etc/pulse/client.conf:

### Cookie file
cookie-file = /etc/pulse-cookie
  1. 在client上指定pulseaudio的server

    /etc/pulse/client.conf:

## The default server to connect to
default-server = 192.168.0.5

28.19.3. 把windows的音频发送到linux上

28.20. 在Linux下录制demo video

Instructions for making demo video on linux, using the utility recordmydesktop. Recording is done with the command

recordmydesktop -windowid $(xwininfo | awk '/Window id:/ {print $4}') -device hw:1,0 -delay 2 --overwrite  -o out.ogv --full-shots

Click on the window to record and recording will start in 2 secs. hw:1,0 is the sound recording alsa device (obtained using arecord -l). The video file out.ogv is in theora format. It can be converted to MPEG4 and FLV as shown below. For avi:

mencoder out.ogv -ovc lavc -lavcopts vcodec=mpeg4:vpass=1 -oac ac3 -o out.avi
mencoder out.ogv -ovc lavc -lavcopts vcodec=mpeg4:vpass=2 -oac ac3 -o out.avi

For Flash video

mencoder out.ogv -o out.flv -of lavf -ovc lavc -oac mp3lame -lavcopts vcodec=flv:vbitrate=250:autoaspect:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:precmp=2:cmp=2:subcmp=2:preme=2:turbo  -srate 22050 -af lavcresample=22050

You can add -vf scale=320:240 for standard flash video resolution.

28.21. 可以下载Google音乐榜单的软件 gmbox

作者: http://li2z.cn/

28.22. 自动下载并以多种方式显示歌词的软件 lrcdis

28.23. mdf/mds文件切分为wav文件

mdfextract

28.24. dts/cue文件切换为wav文件

cue2tracks

    vorbis-tools: For OGG support
    flake: Alternative FLAC encoder
    mac: For APE support
    wavpack: For WavPack support
    shorten: For shorten support
    ttaenc: For True Audio Codec support
    lame: For MP3 support
    id3v2: For MP3 tagging support
    faac: For AAC in M4A support
    faad: For AAC in M4A support
cue2tracks -c wav -R -f gbk -o "%N-%t" CDImage.cue
cue2tracks -c wav -R -f gbk -o "%N-%t-%p" CDImage.cue

或者

28.25. 用ffmpeg转换音乐为mp3

ffmpeg -i name_file.aac -ab 192k -vn name_file.mp3
ffmpeg -i name_file.aac -vn -acodec libmp3lame name_file.mp3

Or

ffmpeg -i name_file.aac -vn -acodec libmp3lame -aq 6 name_file.mp3

Or

ffmpeg -i name_file.aac -vn -acodec libmp3lame -ar 44100 -ac 2 -ab 128000 name_file.mp3

29. vimperator

pentadactyl是vimperator的另一个分支

29.1. 用拼音过滤中文链接

29.3. 修正部分插件不兼容新liberator接口的问题

%s/liberator\.\(commandline\|commands\|options\|echo\|buffer\|mappings\|bookmarks\|globalVariables\)/\1/g

30. cpufreq

  1. Load CPU Frequency Driver

    add acpi-cpufreq to MODULES of /etc/rc.conf

    with the driver loaded, you can use cpufreq-info to see the current status.

  2. Scaling Governors (CPU Power Schemes)

    add cpufreq_ondemand or other cpufreq_* modules to MODULES of /etc/rc.conf. (can load more than one modules, but only one can be used at the same time)

  3. Configure and load frequency scaling daemon (optional)

    • edit /etc/conf.d/cpufreq

    • add cpufreq to DAEMONS list of /etc/rc.conf

31. subversion/svn

31.1. 使用vimdiff作为diff工具

$HOME/.subversion/config
[helpers]
diff-cmd = /home/matt/bin/diffwrap.sh
diffwrap.sh
#!/bin/sh

# Configure your favorite diff program here.
DIFF="/usr/bin/vimdiff"

# Subversion provides the paths we need as the sixth and seventh
# parameters.
LEFT=${6}
RIGHT=${7}

# Call the diff command (change the following line to make sense for
# your merge program).
$DIFF --left $LEFT --right $RIGHT

# Return an errorcode of 0 if no differences were detected, 1 if some were.
# Any other errorcode will be treated as fatal.
diffwrap.bat
@ECHO OFF

REM Configure your favorite diff program here.
SET DIFF="C:\Program Files\Funky Stuff\My Diff Tool.exe"

REM Subversion provides the paths we need as the sixth and seventh
REM parameters.
SET LEFT=%6
SET RIGHT=%7

REM Call the diff command (change the following line to make sense for
REM your merge program).
%DIFF% --left %LEFT% --right %RIGHT%

REM Return an errorcode of 0 if no differences were detected, 1 if some were.
REM Any other errorcode will be treated as fatal.

31.2. 能正确处理svn:externals的svncopy工具

31.3. 删除设置在单独文件上的svn:mergeinfo属性

svn propget -R svn:mergeinfo | grep -v "^/" | grep -v "^\." | cut "-d " -f1 | xargs svn propdel svn:mergeinfo

31.4. 找出在哪个版本删除的某一行

#!/bin/bash
file="$1"
REVISIONS=`svn log $file -q --stop-on-copy |grep "^r" | cut -d"r" -f2 | cut -d" " -f1`
for rev in $REVISIONS; do
    prevRev=$(($rev-1))
    difftext=`svn diff --old=$file@$prevRev --new=$file@$rev | tr -s " " | grep -v " -\ \- " | grep -e "$2"`
    if [ -n "$difftext" ]; then
        echo "$rev: $difftext"
    fi
done

31.5. 列出每个版本修改的内容

#!/bin/bash

# history_of_file
#
# Bendin on Stack Overflow: http://stackoverflow.com/questions/282802
#   Outputs the full history of a given file as a sequence of
#   logentry/diff pairs.  The first revision of the file is emitted as
#   full text since there's not previous version to compare it to.
#
# Dlink
#   Made to work in reverse order

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
        while read r
    do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
    done
    }
}

history_of_file $1

31.6. 补全远程目录

  • svn_completion_remote_paths.sh

#!/bin/bash
function complete_remote_paths() {
    word_to_complete=${COMP_WORDS[COMP_CWORD]}
    command_line=${COMP_LINE}

    # If the command line contains ^/ we should start completing
    if [[ "$command_line" ==  *^/* ]]; then
        # Create a base path for svn to use which only contains complete folder
        # names. Examples:
        # ^/bra => ^/
        # ^/branches/foo = ^/branches/
        basepath=$(echo "${word_to_complete}"|sed -re 's#[^/]+$##')

        # Generate a list of words to complete the command.
        COMPREPLY=($(compgen -W "$(get_remote_paths)" -- ${word_to_complete}))
    fi
}

function get_remote_paths() {
    # List all remote paths at given base path. Prepend the basepath to all
    # lines from svn ls in order to work with compgen.
    svn ls ${basepath} 2>/dev/null | sed -e 's#^#'$basepath'#'
}

# Add completion for svn command, use function for completing and don't add any
# extra whitespaces at the end of remote path.
complete -o nospace -o plusdirs -F complete_remote_paths svn

31.7. 确定创建分支的版本

svn log -r 1:HEAD --limit 1 --stop-on-copy

只取版本号:

svn log -r 1:HEAD --limit 1 --stop-on-copy --xml | sed -n -e '/^.*revision="\([0-9]\+\)".*$/{s//\1/;p}'

31.8. 找出在一个分支中修改过的文件

svn diff -r <创建分支的版本号>:HEAD --summarize [<url of the branch>]
svn diff -r $(svn log -r 1:HEAD --limit 1 --stop-on-copy --xml | sed -n -e '/^.*revision="\([0-9]\+\)".*$/{s//\1/;p}'):HEAD --summarize

31.9. 确定一个分支何时合并到trunk

  1. svn log 分支确认分支的生命周期

  2. 在trunk上svn pg svn:mergeinfo确认分支已经合并到trunk

  3. 通过svn log 分支找出最后一次修改的revision

  4. 在trunk上svn log -g,找出分支上最后一次修改的revision合并到trunk的哪个版本

32. awesome

32.2. 设置墙纸

需要xwininfo(在xorg-utils包中)

32.3. 设置窗口为slave

 { rule       = { class = "Pidgin" },
   properties = { tag   = tags[S][N] },
   callback   = awful.client.setslave },

32.4. sdcv+xsel实现查字典

-- {{{ sdcv lookup dictionary. need xsel and sdcv and stardict-oxford-gb
sdcv_frame = nil
sdcv_old_word = ""
globalkeys = awful.util.table.join(
    globalkeys,
    awful.key({ modkey }, "d", function ()
        local f = io.popen("xsel -o")
        local new_word = f:read("*a")
        f:close()

        if sdcv_frame ~= nil and sdcv_old_word ~= new_word then
            naughty.destroy(sdcv_frame)
            sdcv_frame = nil
        end
        sdcv_old_word = new_word

        -- stardict-oxford-gb
        local f  = io.popen("sdcv -n --utf8-input --utf8-output -u '牛津英汉双解美化版' "..new_word)
        fc = f:read("*all")
        f:close()

        sdcv_frame = naughty.notify({ text = fc, timeout = 10, width = 320 })
    end)
)
-- }}}

需要安装sdcv、xsel、stardict-oxford-gb-formated。其中,stardict-oxford-gb-formated的PKGBUILD如下:

# Maintainer: zhengyi

pkgname=stardict-oxford-gb-formated
pkgver=2.4.2
pkgrel=1
pkgdesc="English Chinese dictionary Oxford-gb-formated for Stardict"
license=('GPL')
depends=('stardict')
url="http://stardict.sourceforge.net"
source=(http://prdownloads.sourceforge.net/stardict/${pkgname}-${pkgver}.tar.bz2)
arch=('i686' 'x86_64')

build() {
    cd $startdir/src/${pkgname}-$pkgver
    mkdir -p $startdir/pkg/usr/share/stardict/dic/
    install -m 644 oxford-gb-formated.dict.dz   $startdir/pkg/usr/share/stardict/dic/
    install -m 644 oxford-gb-formated.idx       $startdir/pkg/usr/share/stardict/dic/
    install -m 644 oxford-gb-formated.ifo       $startdir/pkg/usr/share/stardict/dic/
}


md5sums=('c71b174f6c2aeebbf4deeab365e837ff')

33. X

33.2. 命令行改变分辨率

xrandr可以列出支持的分辨率,用"xrandr -s 1024x768"即可马上改变分辨率

还可以用于改变屏幕的方向

33.3. 修正屏幕偏移

可以用xvidtune生成正确的ModeLine,并放到 Section "Monitor" 中。

X可能会使用从ddc中获得的modeline信息,而不是上面指定的信息,这时候,可以为上述ModeLine另起一个名字(如"my1680x1050"),然后在 Section "Screen" 中的 Section "Display" 中的 Modes 上使用my1680x1050代替原来的1680x1050,这样就会用用户指定的modeline而不是从ddc中获得的modeline了

34. XML

xml

35. password manage

35.1. password generate

36. PDF相关

  • pdfcrop

    裁边

    有两个同名的版本:

  • pdftk

  • pdfsam

    合并和分割

  • apvlv

    A PDF Viewer which behaves like Vim

36.1. 合并多个PDF

安装gs及pdftk

gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=combinedpdf.pdf -dBATCH 1.pdf 2.pdf 3.pdf

36.2. HTML ⇒ PDF

htmldoc

37. 文本格式化

37.1. asciidoc

可选:

source-highlight

37.1.1. 插件

37.1.3. archlinux中修改PKGBUILD加入vim插件的方法

asciidoc在make的过程中会检测有没有安装vim,从而决定是否安装相应的vim插件。在archlinux的PKGBUILD中,由于不是在真实环境下进行make install,因此asciidoc会认为没有安装vim,从而不会安装vim插件,需要把PKGBUILD中的build()改为:

build() {
  mkdir -p "$pkgdir/usr/share/vim"
  cd "$srcdir/$pkgname-$pkgver"
  ./configure --prefix=/usr --sysconfdir=/etc || return 1
  sed -i -e 's!vimdir = /etc/vim!vimdir = /usr/share/vim!' Makefile
  make install DESTDIR="$pkgdir" || return 1
}

38. CUPS

可以到 http://www.openprinting.org/printer_list.cgi 查找打印机的资料,下载合适的驱动或PPD文件

38.1. 打印文件格式

  • 中文文本文件

    需要安装 paps ,可以把UTF-8文本转换成PS,可以直接打印到打印机上

  • 图片文件

    需要安装 netpbm

    cat xxx.jpg | imagetops > xxx.ps

38.2. HP3005打印机安装

  1. Device选“AppSocket/HP JetDirect”

  2. Device URI: socket://IP地址

  3. PPD文件: http://www.linuxprinting.org/foomatic-db/db/source/PPD/HP/HP_LaserJet_P3005.ppd

38.3. 小册子打印

psutils mpage

39. 硬盘相关

39.1. 修改Linux卷标

uuidgen
tune2fs /dev/hdaX -U numbergeneratedbyuuidgen
#verification with
vol_id /dev/hdaX

#one can use xargs or a variable and ; to make that a one liner

uuidgen | xargs tune2fs /dev/hdaX -U ; vol_id /dev/hdaX

39.2. Linux下修改vfat卷标

  1. 安装mtools

  2. 在/etc/mtools.conf中加入驱动器号与/dev/sd*的映射关系

    drive i: file="/dev/sda2"
  3. 查看目前的卷标

    sudo mlabel -s i:
  4. 修改为新的卷标

    sudo mlabel i:Label

39.3. Linux下修改卷标

  • swap

    swaplabel -L <label> /dev/XXX
  • ext2/3/4

    e2label /dev/XXX <label>
  • btrfs

    btrfs filesystem label /dev/XXX <label>
  • reiserfs

    reiserfstune -l <label> /dev/XXX
  • jfs

    jfs_tune -L <label> /dev/XXX
  • xfs

    xfs_admin -L <label> /dev/XXX
  • fat/vfat

    dosfslabel /dev/XXX <label>  # dosfstools package
    mlabel -i /dev/XXX ::<label>  # mtools package; converts label to uppercase
  • ntfs (ntfsprogs package)

    ntfslabel /dev/XXX <label>

39.4. Linux下修改vfat的序列号

  1. 与修改vfat卷标一样配置好mtools.conf

  2. 修改序列号,其中,序列号是8位16进制

    sudo mlabel -N XXXXXXXX i:

39.5. 磁盘加密

39.5.1. 需要的module

modprobe dm-crypt
modprobe aes-i586

39.5.2. 创建加密分区

  1. 准备好新分区(例如sda7)

  2. 用随机数填充新分区(可选)

    sudo dd if=/dev/urandom of=/dev/sda7
  3. 创建加密分区

    sudo cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda7
    Note
    在格式化时需要输入口令
    Note

    关于加密方式

    this article will use XTS-AES as encryption algorithm because it was standardized as IEEE P1619 Standard for Cryptographic Protection of Data on Block-Oriented Storage Devices and it is quite secure, however the XTS mode is still flagged as "experimental" in the Linux kernel, so if you want something less secure but more proven, you should go with the CBC-ESSIV mode. The XTS mode is supported by Linux 2.6.24 upwards (ISO of Arch 2008.06 upwards).

    The XTS mode uses two keys of the same size, therefore available sizes (using XTS-AES) are 256 (128 \* 2), 384 (192 \* 2) and 512 (256 \* 2).

  4. 映射加密分区

    sudo cryptsetup luksOpen /dev/sda7 data
    Note
    加密分区会被映射到/dev/mapper/data
  5. 格式化加密分区

    sudo mkfs.ext3 /dev/mapper/data
  6. 挂载加密分区

    sudo mount /dev/mapper/data /media/mount_point

39.5.3. 创建加密文件

dd if=/dev/urandom of=testfile bs=1M count=10
sudo modprobe loop
sudo losetup /dev/loop0 testfile

39.5.4. 常用操作

卸载分区

只要你有足够的权限,你就可以使用dmsetup命令,你可以显示设备映射,观看哪个设备是可用的,即便并没有被挂载。从这种意义上看,这个设备在一定程度上已经被解密了。为了防止出现以上情况,你可以运行以下命令以正确卸载设备:

sudo umount /media/mount_point && sudo cryptsetup luksClose data
在卸载分区后重新加载分区
sudo cryptsetup luksOpen /dev/sda7 data
sudo mount /dev/mapper/data /media/mount_point
添加删除密钥

你可以为一个加密分区添加多个密钥或者删除这些密钥

  • 添加密钥需要在终端输入:

    sudo cryptsetup luksAddKey /dev/HARDDISK
  • 删除密钥则在终端输入:

    sudo cryptsetup luksDelKey /dev/HARDDISK

39.5.5. 加密SWAP分区

  1. 在/etc/crypttab中添加

    swap /dev/sdaX SWAP "-c aes-xts-plain -h whirlpool -s 512
  2. 把/etc/fstab中swap的行改为

    /dev/mapper/swap swap swap defaults 0 0

39.5.6. 自动加载

启动时自动加载

在系统启动时自动加载,在启动过程中会询问加密盘的密码。

  1. 在/etc/crypttab中添加

    data /dev/sda7 none luks,check=ext2,retry=5
    Note
    在启动的时候,你需要输入加密设备的密码才能开机。你有最多5次机会输入密码,如果超过5次输入密码错误,系统将会不挂载加密设备启动。进入系统以后,你仍然可以手动的挂载它。
  2. 在/etc/fstab中添加

    # CryptoDevices
    /dev/mapper/data /media/mount_point auto defaults 0 0
在登录时自动加载

在用户登录时使用用户的登录密码加载加密盘。无须单独输入加密盘的密码。

需要的软件

pam_mount

步骤
  1. 安装pam_mount

  2. 把pam_mount加入到/etc/pam.d/下适当的service配置文件中

    对于console登录,应该加入到login中。

    对于slim登录,应该加入到slim中。

    Note
    archlinux中的slim缺省是没有加入PAM支持的,需要把PKGBUILD中的make改为make USE_PAM=1,或用aur上的slim-pam包
    auth        optional    pam_mount.so			(1)
    session     optional    pam_mount.so                    (2)
    1. 在auth部分,pam_mount.so必须放在所有sufficient的模块前

    2. 把pam_mount也加入到session部分

  3. 在pam_mount配置文件中配置要mount的加密盘的信息

    Note
    配置文件在/etc/security/pam_mount.conf.xml。不需要/etc/crypttab支持
        <volume user="tht" fstype="crypt" path="/dev/sda7" mountpoint="/media/private" />

39.5.7. Windows下的程序

FreeOTFE

39.5.8. 创建与FreeOTFE兼容的加密盘

dd if=/dev/urandom of=disk.vol bs=25M count=1
losetup /dev/loop0 disk.vol
sudo cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/loop0
sudo cryptsetup luksOpen /dev/loop0 myMapper
sudo losetup /dev/loop1 /dev/mapper/myMapper
mkdosfs /dev/loop1
mount /dev/loop1 ./test_mountpoint
...
umount ./test_mountpoint
losetup -d /dev/loop1
sudo cryptsetup luksClose myMapper
losetup -d /dev/loop0

39.5.9. saftly umount

  1. 这个方法好像不行,可能只针对硬盘?

#!/bin/bash
echo "Sync and Flush cache"
hdparm -f /dev/sda
sleep 2
echo ""
echo "Now Drive to Stand-by"
hdparm -y /dev/sda
  1. 这个方法可能可以

sync; sync; sync
pumount -l sdc1
sdparm -C stop /dev/sdc1
  1. 参考上面的方法,这样可以把U盘的灯灭掉

sync; sync; sync
pumount -l sdc1
sdparm -C eject /dev/sdc1
sudo apt-get install eject

# Then udisks works just fine
udisks --unmount /dev/sda
udisks --eject /dev/sda

40. vim

vim

41. 文件管理器

41.1. mc

skins

把ini文件放到~/.local/share/mc/skins/下,在~/.config/mc/ini文件中,把skins设 为skin文件名即可。

solarized配色

42. wine

42.1. 安装软件

可以用winetricks安装.net framework等一系列软件

42.2. office 2003

安装
  1. 执行winecfg配置,将richedit20.dll, richedit32.dll 和 msxml3.dll添加为默认库,即native(Windows)

  2. 下载安装richedit30.exe

  3. 下载安装msxml3.msi

    wine msiexec /i msxml3.msi
  4. 安装office

运行
cd ~/.wine/drive_c/Program Files/Microsoft Office/OFFICE11
LC_ALL=zh_CN.UTF8 wine WINWORD
相关问题
  1. 输入法问题

    在word中无法使用微软拼音输入法。

  2. 中英文切换问题

    输入中文的时候使用输入法,在输入英文的时候务必ctrl-space变为全英文输入状态,否则会将版式搞乱。总之,在非中文输入状态下,就ctrl-space吧!这样不会乱。

  3. 多选问题

    如果只按方向键就处于多选状态的话,就点一下左shift再点一下右shift即可。

43. 加速Java程序

需要

  1. 开启 OpenGL 3D 加速的显卡

  2. Sun Java version 5 及更高版本

export _JAVA_OPTIONS='-Dawt.useSystemAAFontSettings=on -Dsun.java2d.opengl=true'

44. LAMP环境搭建

44.1. 安装

pacman -S apache php mysql

44.2. 配置Apache

  1. 注释掉/etc/httpd/conf/httpd.conf中的"LoadModule unique_id_module"

    #LoadModule unique_id_module        modules/mod_unique_id.so
  2. 可选:有需要的话,把httpd加入到rc.conf的DAEMONS中,以便自动启动

  3. 可选:允许通过 http://localhost/~user 访问 ~/public_html

    1. 在/etc/httpd/conf/extra/httpd-userdir.conf中加入

      UserDir public_html

      以及

      <Directory /home/*/public_html>
        AllowOverride FileInfo AuthConfig Limit Indexes
        Options MultiViews Indexes SymLinksIfOwnerMatch ExecCGI
        <Limit GET POST OPTIONS PROPFIND>
          Order allow,deny
          Allow from all
        </Limit>
        <LimitExcept GET POST OPTIONS PROPFIND>
          Order deny,allow
          Deny from all
        </LimitExcept>
      </Directory>
    2. 保证apache对 ~/public_html 目录有读权限

      chmod o+x ~
      chmod o+x ~/public_html

44.3. 配置PHP

  1. 让apache载入PHP模块

    在/etc/httpd/conf/httpd.conf中加入

    LoadModule php5_module modules/libphp5.so
    Include conf/extra/php5_module.conf
  2. 可选:增加对.phtml文件的支持

    在/etc/httpd/conf/extra/php5_module.conf中加入

    DirectoryIndex index.php index.phtml index.html
  3. 可选:载入libGD模块

    在/etc/php/php.ini中加入

    extension=gd.so
  4. 加入额外的DocumentRoot

    如果DocumentRoot不在/home/下,需要把它加入到/etc/php/php.ini

    open_basedir = /home/:/tmp/:/usr/share/pear/:/path/to/documentroot
  5. 测试

    在重启httpd后,在/svr/http或~/public_html下加入一个文件test.php

    <html>
    <head>
    <title>PHP Test Page</title>
    </head>
    <body>
    This is Arch Linux, running PHP.
    <?php
      phpinfo();
    ?>
    </body>
    </html>

    可以通过 http://localhost/test.php 或 http://localhost/~myname/test.php 来访问

44.4. 配置mysql

  1. 在PHP中增加mysql支持

    在/etc/php/php.ini中添加

    extension=mysql.so
  2. 可选:在rc.conf的DAEMONS中加入mysql以便让mysql自动启动

44.5. mysql基本用法

44.5.1. 创建database

mysqladmin -u root create likecan

45. 与windows mobile手机同步

  1. opensync

    msynctool multisync-gui

  2. synce

45.1. 安装

  • opensync

    需要0.3版本以上

    libopensync-plugin-python libopensync-plugin-file-unstable msynctool-unstable

    会自动安装 libopensync-unstable

    Note
    编译libopensync-plugin-python时,可能要把cmake/modules/FindOpenSync.cmake中的opensync-1.0改为libopensync,把cmake/modules/FindPythonLibs.cmake中的python25及2.5改为python26和2.6
  • synce

    sync-engine synce-odccm synce-hal

    Note
    编译sync-engine时,需要在PKGBUILD中增加"sed -i -e 's/opensync-1\.0/libopensync/g' synce-install-plugins.py",把opensync-1.0改为libopensync

45.2. 启动

  1. 放开odccm端口

    缺省的本地IP为169.254.2.2

    sudo iptables -A INPUT -d 169.254.2.2 -m multiport -p tcp --dports 990,5679 -j ACCEPT
  2. 启动odccm

    测试时可以用明确调用

    sudo odccm -f

    安装了 synce-hal 之后,不需要自己启动 odccm,会被hal自动启动

  3. 启动sync-engine

    sync-engine
    #用 sync-engine -d 可以在后台运行

45.3. 使用

45.3.1. 建立 partnership

  1. 列出现有的 partnership

    一个手机上只能有最多2个partnership

    list_partnerships.py
  2. 创建 partnership

    create_partnership.py “Linux desktop” “Contacts,Calendar”
    # "Linux desktop"可以是少于20字节的字符串
    # 后面的要同步的项目可以是 Contacts,Calendar,Tasks,Files 四者的组合
  3. 选择要用的 partnership

    select_partnership.py

45.3.2. 建立同步关系

  1. 建立同步group

    msynctool –addgroup pda-sync
  2. 将要同步的插件加入到group中

    msynctool –addmember pda-sync synce-plugin

46. 防病毒软件 virus

46.1. antivir

46.1.1. 概述

AntiVir 是个德国的杀毒软件,有linux版,且免费版本功能也不错. 还可以用来杀windows分区下的病毒,很适合windows根本无法启动的时候,用linux光盘或者U盘启动,进行杀毒.还可以做个杀毒启动U盘备用,嘿嘿.

升级病毒库:

sudo antivir –update

为防止误删有用文件,需要创建一个隔离区:

mkdir /path/quarantine

升级完成,开始扫描:

antivir -s -z -v –moveto=/path/quarantine /media/sda1
antivir -s -z -v –moveto=/path/quarantine /media/sda2

需要扫描什么目录都可以,挂载了windows分区,也就可以扫描windows的病毒了.效果还是不错的.

46.2. 用法

用法:

antivir [参数] [路径[\*.扩展名]] [*.扩展名]

参数有:

--help .......... 显示帮助文本 (缩写: -h 或 -?)
--scan-mode=<mode> 可供使用的扫描模式有“extlist(扩展名列表)”,“smart(智能)”,“all(全部扩展名)”:
在extlist模式下,antivir根据文件的扩展名决定是否对其进行扫描,
在smart模式下,antivir根据文件的名字或者内容决定是否对其进行扫描,
在all模式下,antivir扫描所有的文件。
--allfiles ...... 等价于--scan-mode=all
--version ....... 显示版本信息
--info .......... 显示所有可以识别的模式。(译注:这句话很笼统,观察了该选项的输出,发现所谓的可以识别的模式包括支持的压缩包的格式、文件类型,可以识别的病毒等)
--update ........ update antivir
--update ........ 升级。(译注:包括病毒库和程序文件)
--check ......... used with --update to check for updates
--check ......... 和选项--update一同使用,用于检查有无可用更新
--temp=<dir> .... 设定存放临时文件的目录
--pid-dir=<dir> . 设定存放PID文件的目录
--home-dir=<dir> 指定可执行文件、病毒库文件和key文件的存放位置
-C <filename> ... 设定配置文件的名称
-s .............. 扫描子目录
--scan-in-archive 扫描压缩文件
-z .............. 等价于--scan-in-archive (scan in archives, too)
--archive-max-size=N, --archive-max-recursion=N, --archive-max-ratio=N, --archive-max-count=N
设定反拒绝服务的阈值:避免扫描符合以下条件的压缩包:禁止扫描超过指定大小,或者超过指定递归层级,或者超过指定压缩率,或者压缩包内含超过指定个数的文件。前3个选项的N如果取0,则意味着没有限制。(译注:病毒可以产生一个超级难解开的压缩包,然后抛给病毒扫描器,借此消耗系统的内存或CPU,从而导致扫描器进程响应缓慢甚至崩溃,病毒得以脱身。这种超级难解开的压缩包有一些共同特征,它可能非常大,或者N层递归压缩,或者压缩比率非常高,或者压缩包的某个压缩层级里含有异常多的文件。通过给扫描器设定一定的阈值,可以防止这种攻击)
--scan-in-mbox .. 扫描邮件目录(可能很耗时!)
--heur-macro .... 激活宏病毒启发
--heur-nomacro .. 禁用宏病毒启发
--heur-level=N .. 设定启发式级别,0为关闭,1-3=低启发-高启发
-nolnk .......... 不追踪符号链接
-onefs .......... 跟踪链接,但不跨越不同的文件系统
-noboot ......... 不检查引导记录
-nombr .......... 不检查主引导记录
-nobreak ........ 不理会Ctl-C和Ctrl-Break
-nodef ......... 不检查指定的文件类型
-cf<filename> ... 激活循环冗余校验检查,并指定数据库名
-cv ............. 计算整个文件长度的循环冗余校验值(默认只计算头16k的内容)
-cn ............. 插入新文件名到数据库中
-cu ............. 重新计算循环冗余校验值,并更新数据库
-v .............. 彻底扫描(较慢,并且可能有误报)
-nopack ......... 不在文件包内扫描
-e [-del | -ren] 如果能修复,那么修复感染文件
如果使用了[-del]选项,则无法修复的文件将被删除
如果使用了[-ren]选项,则无法修复的文件将被重命名
-ren ............ 重命名感染文件
-del ............ 删除感染文件
--moveto=<dir> .. 隔离感染文件
-dmdel .......... 删除含有可疑宏病毒的文档
-dmdas .......... 如果文档中有一个宏可疑,那么删除该文档中所有的宏
-dmse ........... 如果发现宏病毒,则设定退出码为101
-r1 ............. 仅记录感染和警报
-r2 ............. 并且记录所有扫描过的路径
-r3 ............. 并且记录所有扫描过的文件
-r4 ............. 选择详细记录模式
-rs ............. 选择单行信息模式
-rf<filename> ... 命名日志文件
%d = 日, %m = 月, %y = 年 (日月年均为2位数字)
-ra ............. 向已经存在的日志文件追加新数据
-ro ............. 覆盖已经存在的日志文件
-q .............. 静默模式
-lang[:|=]DE .... 使用德文界面
-lang[:|=]EN .... 使用英文界面
-once ........... 1天内只运行一次
-if<dateiname> .. 使用指定的ini文件
--with-<type> ... 同时检测其它恶意软件(不是病毒,但并非用户想要的)
类型包括"dial(拨号程序)", "joke(玩笑程序)", "game(游戏)",等
--with-alltypes代表所有恶意软件类型
--without-<type> 含义同--with-<type>选项,但作用相反----不检查该类型的恶意软件
--alltypes ...... 等价于--with-alltypes (此选项已作古)
--alert-urls=<yes|no> 为每个警报打印URL,以便获得进一步的信息
--warnings-as-alerts 如果发现一个感染文件,并已经发出警报,则以相应退出码退出
--exclude=<file> 排除文件或目录
--log-email=<addr> 同时以email形式发出扫描报告
@<rspfile> ...... 从<rspfile>文件中读取参数

每个选项各占独立一行

退出码列表:

0: 正常返回,无任何发现及错误。
1: 发现感染文件或引导记录
2: 在内存中发现警报
3: 发现可疑文件
100: 仅显示帮助文本(而未进行任何扫描)就退出了。(译注:见于执行antivir --help后)
101: 在一个文档文件中发现一个宏病毒
102: 选项-once已激活,今天已经运行过antivir了
200: 内存不足,程序异常终止
201: 未发现指定的响应文件
202: 在指定的响应文件中发现另一个@<rsp>选项
203: 无效选项
204: 无效目录
205: 无法创建日志文件
210: 找不到必须的dll文件
211: 自检失败,程序异常终止
212: 无法读取antivir.vdf文件
213: 初始化时出现错误
214: 无法找到key文件

47. FAQ

  1. could not found /dev/loop*

    modprobe loop
  2. vim不能访问剪贴板

    未打开xterm_clipboard开关。用“vim --version”,看到“-xterm_clipboard”。要换为打开此开关的版本。如archlinux中可以安装gvim,其相应的vim就打开了该开关。

48. windows下访问ext2

49. Synergy

多机器间共享键盘和鼠标

50. hardware/driver 硬件及驱动

50.1. alsa

cat /proc/asound/cards
lsmod|grep '^snd' | column -t

51. rubygems版本太低

sudo gem update --system

52. 设置启动分辨率

用hwinfo找出当前支持的分辨率,及对应的模式号,以 vga=0x0368 的形 式加到/boot/grub/menu.lst的kernel行。

sudo hwinfo --framebuffer

53. 启动时让console使用显示器的物理分辨率(使用uvesafb)

  1. 安装v86d

  2. 在启动参数中(一般在/boot/grub/menu.lst)去掉framebuffer相关的参数( 如vga=xxx)

  3. 禁用KMS,对于intel显卡,可在grub的启动参数中加入“i915.modeset=0”

  4. uvesafb的参数可以在/etc/modprobe.d/uvesafb.conf中设置

  5. 在mkinitcpio.conf中加入v86d

    HOOKS="base udev 915resolution v86d ..."
  6. 重新生成initramfs

    sudo mkinitcpio -p kernel26

54. 启动时显示splash

  1. 安装splashy-full

  2. 在grub的启动项加入 “quiet splash” 参数

  3. 在/etc/rc.conf中加入

    SPLASH="splashy"
  4. 在/etc/mkinitcpio.conf的HOOKS的最后加入splashy

  5. 重新生成initramfs

    sudo mkinitcpio -p kernel26
    NOTE

    在splashy配置变更后(如使用不同的theme),必须重新生成initramfs

    NOTE

    可以安装splashy-themes获得更多的theme

55. Unicode字符

55.1. 部分字符

?

U+25B6

?

U+266B

?

U+2669

U+2586

55.2. 在各种环境下输入unicode

  • The RichEdit control on Microsoft Windows (as used in for example WordPad) supports the following input method: one first enters the character`s hexadecimal code, then immediately presses Alt + x. For example, entering f1 and then pressing the combination will produce the character ?. The code must not be preceded by any digit or letters a-f as they will be treated as part of the code to be converted. This also works on Microsoft Word 2002/2003 for Windows.

  • In the Vim editor, the user first types Ctrl-V u, then types in the hexadecimal number of the symbol or character desired, and it will be converted into the symbol. (On Microsoft Windows, Ctrl-Q may be required instead of Ctrl-V.[1])

  • In Emacs, M-x ucs-insert.

  • In Mac OS X and in Mac OS 8.5 and later: one chooses the Unicode Hex Input keyboard layout. Holding down the Option key, one then types the four-digit hex Unicode code point. On releasing the Option key; the equivalent character will appear.[2]

  • On Microsoft Windows, if the registry key HKEY_CURRENT_USER\Control Panel\Input Method\EnableHexNumpad has a string value of "1", holding down Alt and pressing the "plus" on the numeric keypad, followed by the hex code, will work.[3]

  • In GTK+, 先按CTRL+SHIFT+U,再输入hexadecimal代码,回车

56. putty

56.1. 正确传入<F3>等键

配置中,Terminal-Keyboard中,应选Xterm R6

56.2. 让putty+tmux/screen+vim显示256色

两种方法:

  1. putty中把终端改为xterm-256color

  2. 用tmux -2启动tmux

56.3. 通过另一台服务器中转(multihop)

  1. Configure public key authentication for the intermediate host and make sure it works.

  2. Start putty and on the “Session” page of the “Putty Configuration Dialog” that appears, fill in the host name and user name for the final destination host.

  3. Switch to the Connection –> Proxy page, select “Local” as the proxy type enter the following as the local proxy command: plink.exe intermediate.proxy.host -l username -agent -nc %host:%port

  4. Save the session.

56.4. kitty

支持z-modem、支持alt键

57. tmux

57.1. 获得当前session名称

tmux display-message -p '#S'

57.2. true color

58. synchronizer 文件同步

59. udev

59.1. 编写udev规则

  1. 列出要编写的设备的情况

    将会逐层列出设备的属性,可以从中挑选写规则用的属性。

    udevadm info -a -p $(udevadm info -q path -n /dev/sdd)

60. NFS

60.1. 在systemd下自动mount

fstab

172.31.0.192:/mnt/main/containers/garden/home   /home/username     nfs     tcp,noauto,x-systemd.automount,timeo=14 0 0

60.2. NFSv3

fstab

172.31.0.192:/mnt/main/containers/garden/home   /home/user     nfs     user,vers=3,tcp,noauto,x-systemd.automount,timeo=2,exec 0 0

61. 安全相关

61.1. PolicyKit

用于定义和管理应用的权限。

  • 安装polkit-use-wheel-group可以让wheel组的用户具备root权限

  • pkaction 可以列出系统中已定义的动作

  • 可于/etc/polkit-1/localauthority/50-local.d/中加入.pkla文件来定义权 限。每个.pkla文件可以定义一到多个权限

  • .pkla文件为ini格式,每节可以包

62. 字体

62.1. zsh中,用到的几个特殊字符

echo "\u00b1 \u0246 \u16A0 \u229D \u2630 \u2632 \u2699 \u26a1 \u2718 \u27a6 \u33D1 \ue0a0 \ue0a1 \ue0a2 \ue0b0 \ue0b1 \ue0b2 \ue0b3 \u2460 \u2461"

结果为

&#x00b1 &#x0246 &#x16A0 &#x229D &#x2630 &#x2632 &#x2699 &#x26a1 &#x2718 &#x27a6 &#x33D1 &#xe0a0 &#xe0a1 &#xe0a2 &#xe0b0 &#xe0b1 &#xe0b2 &#xe0b3

判断一个字体中是否包含特定字符:

hb-shape /usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf `echo -ne "\u2007"`
找出目录下所有包含特定字符的字体文件
find . -name "*.ttf" | while read f; do hb-shape "$f" ? | grep -vq "notdef" && echo "$f"; done
find . -name "*.ttf" | while read f; do hb-shape "$f" `echo -ne "\u2632"` | grep -vq "notdef" && echo "$f"; done

63. 标准

⚠️ **GitHub.com Fallback** ⚠️