linux 常用命令 ln/cat/echo/grep/sed/tar/wc/find/ssh/scp/strace/strings/dd/chrt/iostat/rotatelogs/dstat

ln、cat、echo 的常用example:

ln -s [需要被链接的source] [需要新创建的快捷方式target]

 注意,source要写绝对路径!
 
cat > filename << EOF  // 新建&覆盖文件 或者 Ctrl+D 结束
cat >> filename <<EOF  // 追加到文件末尾 append
cat -n filename  // 显示行号

echo "some text" > filename
echo ‘some text’ >> filename
echo > finenamme   # warning!写入空,即清空文件!

单引号与双引号的区别,双引号可以展开变量,可用于某些需要转义的特殊字符(例如创建带空格的文件夹),而单引号内的文字只能解释为字符串:

i5@localhost:~$s=sometext
i5@localhost:~$echo "$s"
sometext
i5@localhost:~$echo '$s'
$s
i5@localhost:~$mkdir "a test folder"

grep 的常用 example:

grep -H -n -i "somestr" a.txt  // 使用 -H 选项可以显示文件名,使用 -n 选项可以显示行号, -i 忽略大小写

// -A n 表示显示匹配行以及其后的 n 行;-B n 表示显示匹配行以及之前的 n 行。例如,在匹配行的前后分别额外显示两行:
grep -A 2 -B 2 -H -n  "somestr" a.txt
grep -E -w 'vivek|raj[0-9]' a.txt  // -E 表示使用正则表达式(--extended-regexp), 匹配 vivek 或者 raj0 至 raj9; -w 表示全字匹配
grep -r "some string"  // 在当前目录下查找所有的文件包含字符串 "some string" 的文件

要注意第一点的是,grep -r 与 通配符的配合。 grep -r 不能够接通配符,但是能够接正则表达式。
例如,要搜索 libxxx.so.xxx 这种文件,不能够用 grep -r "lib*.so.*"
因为 "." 表示匹配任何字符, "*" 在正则表达式中是表示一个或者多个的之前的模式的意思。
因此,需要写成如下形式(反斜杠是转义的意思,其他需要转义的字符: * . ? + $ ^ [ ] ( ) { } | \ /):
grep -r "lib.*\.so\."
grep -E "ab[cde]?" file.txt  # 匹配 ab/abc/abd/abe, 如果使用 ? 需要加上 -E 选项
grep -E '[1-9]{2,3}'  # 匹配两个或者三个 1-9 的数字,例如 11, 12, 123 等等

注意: grep 默认使用 Basic Regular Expressions,即 {, }, (, ), |, +, ? loose their meaning and are treated as normal characters of string and need to be escaped(转义) if they are to be treated as special characters.
如果希望默认把那些字符当作特殊字符,使用 grep -E or egrep 即可。

[ ]: Matches any one of a set characters 例如: [0-9, a-z, @] 等等
. (dot): Matches any one character
*: zero or more occurrences of the previous character
?: The preceding pattern match 0/1 time. (grep -E)
{2,3}: Matches 2 or 3 times of preceding pattern. (grep -E)
+: Matches 1 or more times of preceding pattern. (grep -E)
a | b: Matches a or b. (grep -E), 如果想 match a&b,使用串联多个grep即: grep a fineName | grep b

^: The pattern following it must occur at the beginning of each line
^ with [ ] : The pattern must not contain any character in the set specified(取反)
$: The pattern preceding it must occur at the end of each line
\ (backslash): Ignores the special meaning of the character following it.(转义)

sed 的常用 example:

最常用的,字符串替换:

sed 's/123/456/' aaa.txt  // 将第一个匹配的123替换为456,不会修改文件,除非加上 -i 选项
sed -i 's/123/456/g' aaa.txt  // 替换文件中所有匹配的123,global,直接修改文件
sed -i 's/123/456/2' aaa.txt  // 替换第二个匹配的 123,直接修改文件

sed -i 's/123/456/gI' aaa.txt  // 加上 I 标识表示不区别大小写
sed -i 's_123_456_gI' aaa.txt  // 如果匹配的字符串中包含/等特殊字符,可以用其他字符替换/,例如本例的_(也可以换成其他任意字符)。

关于 sed 的详细应用,见链接:http://blog.csdn.net/gw569453350game/article/details/46633567

tar 的常用example:

# 压缩打包
tar pczf myarchive.tar.gz /home/guowei/mydocuments
	[p] 这个选项表示 “preserve”,它指示 tar 在归档文件中保留文件属主和权限信息。如果不需要保存属性可省略之。
	[c] 表示创建。要创建文件时不能缺少这个选项。
	[z] z 选项启用 gzip 压缩。
	[f] file 选项告诉 tar 创建一个归档文件;如果没有这个选项 tar 会把打包好的文件输出发送到标准输出,那屏幕会是一堆乱码;或者打印compressed data not written to a terminal.
	
	如果要保存绝对路径则加上 -P 选项。否则默认都是相对路径。解压的时候都是相对于当前路径的,不能解压到绝对路径中。如果要保持用户和组信息,需要加 --ower 和 --group, 例如:
	
tar -cpPvf orocos.tar /opt/orocos --owner=0 --group=0  # 这里只能用 UID 和 GID 数字。


Linux doesn’t use internally owners and groups names but numbers - UIDs and GIDs. Users and groups names are mapped from contents of /etc/passwd and /etc/group files for convenience of user. see link: http://unix.stackexchange.com/questions/61004/force-the-owner-and-group-for-the-contents-of-a-tar-file

如果要修改打包的路径,加上 -C 选项:
http://stackoverflow.com/questions/18681595/tar-a-directory-but-dont-store-full-absolute-paths-in-the-archive

# 解压,unpack
tar xzvf myarchive.tar.gz
	[x] x 表示提取,提取 tar 文件时这个命令不可缺少。
	[z] z 选项告诉 tar 要解压的归档文件是 gzip 格式; 如果是bzip2则使用 -j

如果解压的时候要保持用户和权限信息,需要加 sudo 和 -p 选项。

# 列出压缩包中的内容
tar -jtvf xxx.tar
	[t] t 表示列出的意思。

wc 的常用example:

wc 命令用来完成文本统计工作,通过使用不同的选项,它可以统计文件中的字节数(-c),字符数(-m),单词数(-w)与行数(-l)

// 统计somestr出现的次数(行数)
grep  -i "somestr" a.txt | wc -l  

find 的常用example:

find -L ./ -iname "*somestr?.*"   # 以文件名查找,通配符,大小写无关, 查找所有软连接

find ./ -name "*somestr?.*" -or -name "anothername"  #多个文件,通配符,[默认不 follow 链接]

find ./ -type f -exec grep -i "some content" {} \;   #注意,{}+空格+\: 空格一个也不能错; 搜索普通文件(f:普通文件,d:文件夹),并且查找其中大小无关字符串 "some content"
find ./* -exec touch {} \;  # 修改时间戳,例如make的时候,警告:XXX文件的修改时间在将来1.4e+09问题。

find ./ -type f | xargs grep "some conten"  # 同上,可用于查找系统中包含某些字符串的文件,很方便。
# 查找多个文件,find 与或非: -o 或;-a 与;-not 非

find . -maxdepth 1 -type f | xargs grep 'XXX'  # 指定目录深度

# 还有两个比较有用的选项:
-print   # print the full file name on the standard output, followed by a newline.
-print0  # print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses).

比较完整的 find 例子: http://alvinalexander.com/unix/edu/examples/find.shtml

ssh 和 scp

ssh username@192.168.1.5
// 远程拷贝,-r 可用于复制目录
scp -r /paht/to/file username@192.168.1.5:/paht/to/file
scp -P portNum ...    # 如果ssh端口号不是默认的22, 需要加上 -P 选项!scp 用的就是 ssh 的端口号

strace 简介

strace 常用来跟踪进程执行时的系统调用和所接收的信号,
可以跟踪到一个进程产生的系统调用,包括参数,返回值,执行消耗的时间,
因此可以用来debug,或者作为性能分析的工具。

// 例子:
$  strace ls
execve("/bin/ls", ["ls"], [/* 21 vars */]) = 0
brk(0)                                  = 0x8c31000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap2(NULL, 8192, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb78c7000
access("/etc/ld.so.preload", R_OK)      = -1 
...
// 以上每一行都是一条系统调用,等号左边是系统调用的函数名及其参数,右边是该调用的返回值

$ strace -e open ls  // 只显示 open 系统调用的信息
$ strace -e trace=open,read ls /home  // 显示指定的多个系统调用 open,read
$  sudo strace -p 1725  // 指定进程的 pid
$ strace -c ls /home  // -c 统计每一系统调用的所执行的时间,次数和出错的次数等
$ strace -ttT ls  // -tt 在输出中的每一行前加上时间信息,微秒级(前); -T 显示每一调用所耗的时间(后尖括号),如下:
22:00:40.313902 close(1)                = 0 <0.000007>
22:00:40.313951 munmap(0x7f95eb276000, 4096) = 0 <0.000013>
22:00:40.313988 close(2)                = 0 <0.000005>
22:00:40.314061 exit_group(0)           = ?
22:00:40.314239 +++ exited with 0 +++

strings

输出文件中可打印的字符,包括可执行文件,函数库等二进制文件;可用于查看可执行文件中的写死的文件路径,打开的文件名等等信息,亦可用于逆向工程。还有 ltrace、nm 等命令可查看可执行程序 (没有strip过的) 中的函数信息。

strings a.out  // 打印 可执行文件 中的字符串
strings -f a.out  // 在每一个字符串前面加上文件名,这个很有用,例如如下find例子:
find ./lib -name "*.so*" | xargs strings -f | grep "blabla~"  // 找到 所有 .so 动态库中包含 "blabla" 字符串的库,并显示文件名。

dd

不同于 cp 是在文件系统层面的复制,dd命令是更low-level的复制(字节层面的复制,可以复制文件,分区表,其他数据等等),因此dd一般用来创建和备份镜像文件。

example:

# 将一个硬盘备份至另一个硬盘,见下文释义:
dd if=/dev/sda of=/dev/sdb bs=32K conv=noerror,sync
// 注意,这里的 bs 大小对拷贝速度有很大影响,一般取 bs=8M/128K/32K/4K 等等。默认好像是 512 Byte(不加任何suffixes表示Byte), see "man dd"

// man 手册中推荐查看进度的拷贝方法:
$ dd if=/dev/zero of=/dev/null& pid=$!
$ kill -USR1 $pid; sleep 1; kill $pid

// 截断文件
dd if=/dev/null of=/file/to/truncate seek=1 bs=123456  # truncate file to 123456 bytes  // dd --help可知,seek=N 表示跳过of文件中的N个bs的数据块,因此这条命令表示截断文件为123456 bytes大小。

Here, ‘if’ stands for input file , ‘of’ stands for output file and ‘bs’ stands for the block size (number of bytes to be read/write at a time). The conversion parameter ‘noerror’ allows the tool to continue to copy the data eventhough it encounter any errors. The sync option allows to use synchronized I/O.

The above command will copy all the data from the disk /dev/sda to /dev/sdb. ‘dd’ doesn’t know anything about the filesystem or partitions- it will just copy everything from /dev/sda to /dev/sdb. So, this will clone the disk with the same data on same partition.

关于dd显示进度:

watch -n 5 pkill -USR1 ^dd$  // 正则表达式匹配 ^dd$ 的 pid,然后发送信号

link: http://linoxide.com/linux-command/linux-dd-command-create-1gb-file/

chrt 修改进程的调度策略

// 获得各个调度策略的最大最小优先级:
guowei@localhost:~$ chrt -m
SCHED_OTHER min/max priority	: 0/0
SCHED_FIFO min/max priority	: 1/99
SCHED_RR min/max priority	: 1/99
SCHED_BATCH min/max priority	: 0/0
SCHED_IDLE min/max priority	: 0/0

// 修改进程 1234 的调度策略为 fifo, 优先级为 99(rt), top中查看显示的优先级就是RT
guowei@localhost:~$ sudo chrt -f -p 99 1234

ref link: https://linux-tips.com/t/how-to-use-chrt-command/268

iostat 查看磁盘io状态

iostat -xd 3
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00     2.67    0.00    0.67     0.00    14.67    44.00     0.00    0.00    0.00    0.00   0.00   0.00
vdb               0.00     7.00    0.00    8.67     0.00    62.67    14.46     0.03    3.38    0.00    3.38   0.15   0.13
rrqm/s:每秒这个设备相关的读取请求有多少被Merge了(当系统调用需要读取数据的时候,VFS将请求发到各个FS,如果FS发现不同的读取请求读取的是相同Block的数据,FS会将这个请求合并Merge)
wrqm/s:每秒这个设备相关的写入请求有多少被Merge了。
rsec/s:The number of sectors read from the device per second.
wsec/s:The number of sectors written to the device per second.
rKB/s:The number of kilobytes read from the device per second.
wKB/s:The number of kilobytes written to the device per second.
avgrq-sz:平均请求扇区的大小,The average size (in sectors) of the requests that were issued to the device.
avgqu-sz:是平均请求队列的长度。毫无疑问,队列长度越短越好,The average queue length of the requests that were issued to the device.   
await:每一个IO请求的处理的平均时间(单位是毫秒)。这里可以理解为IO的响应时间,一般地系统IO响应时间应该低于5ms,如果大于10ms就比较大了。
这个时间包括了队列时间和服务时间,也就是说,一般情况下,await大于svctm,它们的差值越小,则说明队列时间越短,反之差值越大,队列时间越长,说明系统出了问题。
svctm:表示平均每次设备I/O操作的服务时间(以毫秒为单位)。如果svctm的值与await很接近,表示几乎没有I/O等待,磁盘性能很好。
如果await的值远高于svctm的值,则表示I/O队列等待太长,系统上运行的应用程序将变慢。
%util: 在统计时间内所有处理IO时间,除以总共统计时间。例如,如果统计间隔1秒,该设备有0.8秒在处理IO,而0.2秒闲置,那么该设备的%util = 0.8/1 = 80%,
所以该参数暗示了设备的繁忙程度,一般地,如果该参数是100%表示磁盘设备已经接近满负荷运行了(当然如果是多磁盘,即使%util是100%,因为磁盘的并发能力,所以磁盘使用未必就到了瓶颈)。

lsof 查看打开的文件
因为linux中一切皆文件,所以可以查看tcp/udp连接

sudo lsof -i
COMMAND     PID            USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
p1 1143            root   13u  IPv4 1101832590      0t0  UDP *:43461 
p2 1143            root   19u  IPv4 1101845599      0t0  UDP *:41040 

通过管道rotate日志,将终端日志下如文件

# 安装
sudo apt-get install apache2-utils
# 重定向,并设置日志格式
my_prog.exe 2>&1 | rotatelogs -n 5 /var/log/uap/my_prog.log.%Y-%m-%d-%H_%M_%S 5M

link: http://xstarcd.github.io/wiki/sysadmin/rotatelogs.html

dstat cpu/磁盘/网络监控工具
安装

sudo apt-get install dstat
dstat 是一个可以取代vmstat,iostat,netstat和ifstat这些命令的多功能产品
dstat  # 默认查看
dstat  --disk-util  # 查看磁盘使用率

常用插件
--disk-util	显示某一时间磁盘的忙碌状况
--freespace	显示当前磁盘空间使用率
--proc-count	显示正在运行的程序数量
--top-bio	显示块I/O最大的进程
--top-cpu	显示CPU占用最大的进程
--top-io	显示正常I/O最大的进程
--top-mem	显示占用最多内存的进程

netstat 查看tcp/udp的连接

sudo netstat -a  # 查看所有连接
sudo netstat -t -a  # 查看tcp连接

tcpdump

tcpdump -D  # 查看可用的interface
sudo tcpdump -i eth0 port 80  # dump 端口 80 的数据, To specify a port that is either source or destination
sudo tcpdump dst port 514  # destination port, or tcpdump src port 8443
sudo tcpdump -ni eth4 -U -vv "tcp port 46224 and tcp[tcpflags] & (tcp-syn|tcp-ack) != 0"  # -U 立即显示, -n 不需要dns查询ip
sudo tcp -ni eth4 host 3.68.127.13  # filter by IP or host, will listen to both source and destination
sudo tcpdump -ni eth4 -U -vvv host 3.68.127.13 -w - | tee test.pcap | sudo tcpdump -r -  # stdout 显示并写文件
# 然后可以将 test.pcap 用 wireshark 打开分析
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值