Linux Shell --常用命令

经典面试题

1. leetcode192 统计词频

写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。
为了简单起见,你可以假设:
words.txt只包括小写字母和 ’ ’ 。
每个单词只由小写字母组成。
单词间由一个或多个空格字符分隔。
示例:
假设 words.txt 内容如下:
the day is sunny the the
the sunny is is
你的脚本应当输出(以词频降序排列):
the 4
is 3
sunny 2
day 1

cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -t ' ' -k 1rn | awk '{print $2" "$1}'

ssh登录 The authenticity of host 192.168.0.xxx can’t be established. 的问题

加参数,

ssh  -o StrictHostKeyChecking=no -p22 dedong@49.52.10.245
Warning: Permanently added '49.52.10.245' (ECDSA) to the list of known hosts.
# ssh登陆脚本
#!/usr/bin/expect -f
set port 22
set user ***	
set host *.*.*.*
set password ***
set timeout -1

spawn ssh -o StrictHostKeyChecking=no -p$port $user@$host
expect "*assword:*"
send "$password\r"
interact
expect eof



tmux

运维系列(14)-- tmux快速上手指南


pip install 镜像

-i http://pypi.douban.com/simple --trusted-host pypi.douban.com

AWK

三十分钟学会AWK

awk 自学练习

运维系列(18)-- AWK统计最大值、最小值、平均值、总和使用实例及入门详解


查找文件

find / -name file.txt

grep

grep -rn "with engine.conn" *
grep -n "with engine.conn" *
grep -n 'with engine.conn' ./customs *.py
find -type f -name '*.py'|xargs grep -n 'with engine.conn'

* : 表示当前目录所有文件,也可以是某个文件名
-r 是递归查找
-n 是显示行号
-R 查找所有文件包含子目录
-i 忽略大小写
下面是一些有意思的命令行参数:
grep -i pattern files :不区分大小写地搜索。默认情况区分大小写,
grep -l pattern files :只列出匹配的文件名,
grep -L pattern files :列出不匹配的文件名,
grep -w pattern files :只匹配整个单词,而不是字符串的一部分(如匹配‘magic’,而不是‘magical’),
grep -C number pattern files :匹配的上下文分别显示[number]行,
grep pattern1 | pattern2 files :显示匹配 pattern1 或 pattern2 的行,
grep pattern1 files | grep pattern2 :显示既匹配 pattern1 又匹配 pattern2 的行。
这里还有些用于搜索的特殊符号:
< 和 > 分别标注单词的开始与结尾。
例如:
grep man * 会匹配 ‘Batman’、‘manic’、‘man’等,
grep ‘<man’ * 匹配‘manic’和‘man’,但不是‘Batman’,
grep ‘<man>’ 只匹配‘man’,而不是‘Batman’或‘manic’等其他的字符串。
‘^’:指匹配的字符串在行首,
‘$’:指匹配的字符串在行尾,


上传下载文件

# 下载
scp [-r] jianxiang@49.52.10.181:/home/jianxiang/customs_code/debug/exports/2018-10-19.xlsx /Users/ddlee/Downloads/

# 上传:
scp -r htmltitle.cpp(文件名) root@139.59.250.52:/root/htmltitle 

sed替换文本

sed "s/CODE_TS is not null/CODE_TS like '8483%' or CODE_TS like '8409%'/g" oracle_scheduler.py

命令格式1:sed ‘s/原字符串/新字符串/’ 文件
命令格式2:sed ‘s/原字符串/新字符串/g’ 文件
这两种命令格式的区别在于是否有个“g”。没有“g”表示只替换第一个匹配到的字符串,有“g”表示替换所有能匹配到的字符串,“g”可以认为是“global”(全局的)的缩写,没有“全局的”结尾就不要替换全部,这样就好记啦。命令可以使用正则表达式来处理。如下图,第一个命令只是将第一个“b”替换成了“B”,其他的都没有替换;而第二个命令将全文中的数字都替换成了“好的”。


查看内存

free -k(-m ...)

查看进程/杀进程

linux下杀死进程(kill)的N种方法

ps -h
ps -ef | grep /bin/zsh | awk '{print $2}' | xargs kill -9

设置定时任务

crontab 详细用法 定时任务


more/less/cat/head/tail

Linux中cat、more、less、tail、head命令的区别


查看文件夹大小

Linux:

du -h --max-depth=1

Mac:

du -hd1

查看存储容量:

df -hl

linux 内存清理/释放命令

在Linux系统下,我们一般不需要去释放内存,因为系统已经将内存管理的很好。但是凡事也有例外,有的时候内存会被缓存占用掉,导致系统使用SWAP空间影响性能,此时就需要执行释放内存(清理缓存)的操作了。

Linux系统的缓存机制是相当先进的,他会针对dentry(用于VFS,加速文件路径名到inode的转换)、Buffer Cache(针对磁盘块的读写)和Page Cache(针对文件inode的读写)进行缓存操作。但是在进行了大量文件操作之后,缓存会把内存资源基本用光。但实际上我们文件操作已经完成,这部分缓存已经用不到了。这个时候,我们难道只能眼睁睁的看着缓存把内存空间占据掉么?

所以,我们还是有必要来手动进行Linux下释放内存的操作,其实也就是释放缓存的操作了。

要达到释放缓存的目的,我们首先需要了解下关键的配置文件/proc/sys/vm/drop_caches。这个文件中记录了缓存释放的参数,默认值为0,也就是不释放缓存。他的值可以为0~3之间的任意数字,代表着不同的含义:

0 – 不释放
1 – 释放页缓存
2 – 释放dentries和inodes
3 – 释放所有缓存

知道了参数后,我们就可以根据我们的需要,使用下面的指令来进行操作。

首先我们需要使用sync指令,将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延迟的块 I/O 和读写映射文件。否则在释放缓存的过程中,可能会丢失未保存的文件。

  1. 同步指令
sync

1.清理前内存使用情况

free -m

2.开始清理

echo 1 > /proc/sys/vm/drop_caches

3.清理后内存使用情况

free -m

tar [-cxtzjvfpPN] 压缩、解压缩命令详解

参数:
-c :建立一个压缩文件的参数指令(create 的意思);
-x :解开一个压缩文件的参数指令!
-t :查看 tarfile 里面的文件! 特别注意,在参数的下达中, c/x/t 仅能存在一个!不可同时存在! 因为不可能同时压缩与解压缩。
-z :是否同时具有 gzip 的属性?亦即是否需要用 gzip 压缩?
-j :是否同时具有 bzip2 的属性?亦即是否需要用 bzip2 压缩?
-v :压缩的过程中显示文件!这个常用,但不建议用在背景执行过程!
-f :使用档名,请留意,在 f 之后要立即接档名喔!不要再加参数!    例如使用『 tar -zcvfP tfile sfile』就是错误的写法,要写成    『 tar -zcvPf tfile sfile』才对喔!
-p :使用原文件的原来属性(属性不会依据使用者而变)
-P :可以使用绝对路径来压缩!
-N :比后面接的日期(yyyy/mm/dd)还要新的才会被打包进新建的文件中!
–exclude FILE:在压缩的过程中,不要将 FILE 打包!

范例一:将整个 /etc 目录下的文件全部打包成为 /tmp/etc.tar

[root@linux ~]# tar -cvf /tmp/etc.tar /etc<==仅打包,不压缩!
[root@linux ~]# tar -zcvf /tmp/etc.tar.gz /etc<==打包后,以 gzip 压缩
[root@linux ~]# tar -jcvf /tmp/etc.tar.bz2 /etc<==打包后,以 bzip2 压缩
# 特别注意,在参数 f 之后的文件档名是自己取的,我们习惯上都用 .tar 来作为辨识。
# 如果加 z 参数,则以 .tar.gz 或 .tgz 来代表 gzip 压缩过的 tar file ~
# 如果加 j 参数,则以 .tar.bz2 来作为附档名啊~
# 上述指令在执行的时候,会显示一个警告讯息:
# 『tar: Removing leading `/" from member names』那是关於绝对路径的特殊设定。

范例二:查阅上述 /tmp/etc.tar.gz 文件内有哪些文件?

[root@linux ~]# tar -ztvf /tmp/etc.tar.gz
# 由於我们使用 gzip 压缩,所以要查阅该 tar file 内的文件时,
# 就得要加上 z 这个参数了!这很重要的!

范例三:将 /tmp/etc.tar.gz 文件解压缩在 /usr/local/src 底下

[root@linux ~]# cd /usr/local/src
[root@linux src]# tar -zxvf /tmp/etc.tar.gz
# 在预设的情况下,我们可以将压缩档在任何地方解开的!以这个范例来说,
# 我先将工作目录变换到 /usr/local/src 底下,并且解开 /tmp/etc.tar.gz ,
# 则解开的目录会在 /usr/local/src/etc 呢!另外,如果您进入 /usr/local/src/etc
# 则会发现,该目录下的文件属性与 /etc/ 可能会有所不同喔!

范例四:在 /tmp 底下,我只想要将 /tmp/etc.tar.gz 内的 etc/passwd 部分解开而已

[root@linux ~]# cd /tmp
[root@linux tmp]# tar -zxvf /tmp/etc.tar.gz etc/passwd
# 我可以透过 tar -ztvf 来查阅 tarfile 内的文件名称,如果单只要一个文件,
# 就可以透过这个方式来下达!注意到! etc.tar.gz 内的根目录 / 是被拿掉了!

范例五:将 /etc/ 内的所有文件备份下来,并且保存其权限!

[root@linux ~]# tar -zxvpf /tmp/etc.tar.gz /etc
# 这个 -p 的属性是很重要的,尤其是当您要保留原本文件的属性时!

范例六:在 /home 当中,比 2005/06/01 的文件才选择备份

[root@linux ~]# tar -N "2005/06/01" -zcvf home.tar.gz /home

范例七:我要备份 /home, /etc ,但除去 /home/dmtsai

[root@linux ~]# tar --exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc

范例八:将 /etc/ 打包后直接解开在 /tmp 底下,而不产生文件

[root@linux ~]# cd /tmp
[root@linux tmp]# tar -cvf - /etc | tar -xvf -
# 这个动作有点像是 cp -r /etc /tmp 啦~依旧是有其有用途的!
# 要注意的地方在於输出档变成 - 而输入档也变成 - ,又有一个 | 存在~
# 这分别代表 standard output, standard input 与管线命令啦!

关闭防火墙,开放特定端口

开放端口
永久的开放需要的端口

sudo firewall-cmd --zone=public --add-port=5000/tcp --permanent
sudo firewall-cmd --reload

之后检查新的防火墙规则

firewall-cmd --list-all

关闭防火墙
由于只是用于开发环境,所以打算把防火墙关闭掉

//临时关闭防火墙,重启后会重新自动打开
systemctl restart firewalld
//检查防火墙状态
firewall-cmd --state
firewall-cmd --list-all
//Disable firewall
systemctl disable firewalld
systemctl stop firewalld
systemctl status firewalld
//Enable firewall
systemctl enable firewalld
systemctl start firewalld
systemctl status firewalld

Linux如何查看端口

1.使用 lsof 命令来查看某一端口是否开放。查看端口可以这样来使用,我就以80端口为例:
sudo lsof -i:8080
如果有显示说明已经开放了,如果没有显示说明没有开放
2.netstat -aptn执行看看,是否监听在0.0.0.0:3306
3.
netstat -nupl (UDP类型的端口)
netstat -ntpl (TCP类型的端口)
4.telnet ip  端口号   方式测试远程主机端口是否打开
  1. lsof -i:端口号
    用于查看某一端口的占用情况,比如查看8000端口使用情况,lsof -i:8000
lsof -i:8000
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
lwfs    22065 root    6u  IPv4 4395053      0t0  TCP *:irdmi (LISTEN)

可以看到8000端口已经被轻量级文件系统转发服务lwfs占用

  1. netstat -tunlp |grep 端口号
    用于查看指定的端口号的进程情况,如查看8000端口的情况,netstat -tunlp |grep 8000
# netstat -tunlp 
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      4814/rpcbind        
tcp        0      0 0.0.0.0:5908                0.0.0.0:*                   LISTEN      25492/qemu-kvm      
tcp        0      0 0.0.0.0:6996                0.0.0.0:*                   LISTEN      22065/lwfs          
tcp        0      0 192.168.122.1:53            0.0.0.0:*                   LISTEN      38296/dnsmasq       
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      5278/sshd           
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      5013/cupsd          
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      5962/master         
tcp        0      0 0.0.0.0:8666                0.0.0.0:*                   LISTEN      44868/lwfs          
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      22065/lwfs
# netstat -tunlp | grep 8000
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      22065/lwfs   
参数含义
-t (tcp) 仅显示tcp相关选项
-u (udp)仅显示udp相关选项
-n 拒绝显示别名,能显示数字的全部转化为数字
-l 仅列出在Listen(监听)的服务状态
-p 显示建立相关链接的程序名

监控网络链接数

监控java线程数:
ps -eLf | grep java | wc -l

监控网络客户连接数:
netstat -n | grep tcp | grep 侦听端口 | wc -l

>pids=`ps ux | grep app.py | grep -v grep | awk -F' ' '{print $2}'`
>for i in ${pids}; do     kill ${i}; done
>pids=`netstat -nlp | grep :5000 | awk '{print $7}' | awk -F"/" '{print $1}'`

sort(按照指定列排序)

file.txt 文本如下:

110,1|1,10 
110,1|2,101 
110,3|1,103 
110,4|1,16 
110,5|1,12 
112,1|1,10 
112,1|2,101 
112,2|1,103 
110,6|1,11 
104,2|1,34 
112,3|1,103 
112,4|1,16 
112,6|1,11 
113,1|1,30 
110,2|1,103 
112,5|1,12

Linux 命令:

sort -t , -k 1n,1 -k 3rn,3 file.txt

排序结果:

104,2|1,34 
110,2|1,103 
110,3|1,103 
110,1|2,101 
110,4|1,16 
110,5|1,12 
110,6|1,11 
110,1|1,10 
112,2|1,103 
112,3|1,103 
112,1|2,101 
112,4|1,16 
112,5|1,12 
112,6|1,11 
112,1|1,10 
113,1|1,30

结果说明:
1.-t 指定文本分隔符
2.-k 指定排序列
3.-n 按数字进行排序
4.-r 翻转排序结果 上面的例子为按第一行正排序,按第三行反排序;


添加用户

Ubuntu 18.04下用户的创建、修改权限及删除用户的方法


用户获得sudo使用权

处理这个问题很简单,但应该先理解其原理再操作
首先要明白root的密码一般用户是不应改知道的,但一般用户有时可能要用到root的一些权限。
这里就有了一个 /etc/sudoers文件,用来保存一些用户,使这些用户可以通过sudo命令来暂时获取root的权限。这些用户使用sudo时输入的密码是当前用户密码,而不是root密码。还可一在sudoers文件里限制一般用户的权限,这样就有了安全保证。

现在要让jack用户获得sudo使用权
1.切换到超级用户root
$su root
2.查看/etc/sudoers权限,可以看到当前权限为440
$ ls -all /etc/sudoers
-r–r----- 1 root root744 6月 8 10:29/etc/sudoers
3.更改权限为777
$chmod 777 /etc/sudoers
4.编辑/etc/sudoers
$vi /etc/sudoers
5.在root ALL=(ALL:ALL) ALL 下面添加一行
jack ALL=(ALL)ALL
然后保存退出。
第一个ALL是指网络中的主机,我们后面把它改成了主机名,它指明jack可以在此主机上执行后面的命令。
第二个括号里的ALL是指目标用户,也就是以谁的身份去执行命令。
最后一个ALL当然就是指命令名了。
具体这里不作说明
6.把/etc/sudoers权限改回440
$chmod 440 /etc/sudoers
7.操作完成,切换到jack用户测试一下


Linux常用命令全拼

 pwd:	print work directory	#打印当前目录 显示出当前工作目录的绝对路径
 ps: 		process status 		#(进程状态,类似于windows的任务管理器) 
 ps -auxf 	 #显示进程状态

 df: 		disk free 	#显示磁盘可用空间数目信息及空间结点信息。换句话说,就是报告在任何安装的设备或目录中,还剩多少自由的空间。
du: 		Disk usage 
rpm:	RedHat Package Management	#是RedHat的发明之一 
mkdir:Make Directory(创建目录)
rmdir:	Remove Directory  #(删除目录)
rm:	Remove	#(删除目录或文件)
cat: 		concatenate 	#连锁
cat file1file2>>file3 	#把文件1和文件2的内容联合起来放到file3中

insmod: 	install module 	# 载入模块
ln -s : 	link -soft 	# 创建一个软链接,相当于创建一个快捷方式
touch 
man: 	Manual 
su:		Swith user	#(切换用户)
cd:		Change directory  
ls:		List files  
mkfs: 	Make file system  
fsck:	File system check  
uname: Unix name 
cp: 		Copy file 
ln: 		Link files 
fg: 		Foreground 
bg: 		Background 
chown: Change owner 
chgrp: 	Change group
chmod: Change mode  
umount: Unmount 

dd: 		本来应根据其功能描述“Convert an copy”命名为“cc”,但“cc”已经被用以代表“CComplier”,所以命名为“dd”
tar:	Tape archive (磁带档案)
ldd:	List dynamic dependencies  
insmod:Install module  
rmmod:Remove module  
lsmod:List module 
文件结尾的"rc"(如.bashrc、.xinitrc等):Resource configuration 
Knnxxx /Snnxxx(位于rcx.d目录下):K(Kill);S(Service);
nn(执行顺序号);xxx(服务标识)
.a(扩展名a):Archive,static library  
.so(扩展名so):Shared object,dynamically linked library  
.o(扩展名o):Object file,complied result of C/C++ source file  
dpkg:Debian package manager 
apt:Advanced package tool(Debian或基于Debian的发行版中提供)

部分Linux命令缩写
bin = Binaries (二进制文件)
/dev = Devices (设备)
/etc = Etcetera (等等)
/lib = LIBrary  
/proc = Processes 
/sbin = Superuser Binaries (超级用户的二进制文件)
/tmp = Temporary (临时)
/usr = Unix Shared Resources 
/var = Variable (变量) 

GRUB = GRand Unified Bootloader 
IFS= Internal Field Seperators 
LILO = LInux LOader 

PS = Prompt String     
Tcl = Tool Command Language  
Tk = ToolKit 
VT = Video Terminal 
YaST = Yet Another Setup Tool
apache = "a patchy" server 
apt = Advanced Packaging Tool 
ar = archiver 
as = assembler

awk = "Aho Weiberger and Kernighan"三个作者的姓的第一个字母
bash = Bourne Again SHell 
cal = Calendar (日历)
cat = Catenate (链接)
cd = Change Directory 
chgrp = Change Group 
chmod = Change Mode 
chown = Change Owner 
chsh = Change Shell 
cmp = compare  
cobra = Common Object Request BrokerArchitecture 
comm = common 
cpio = CoPy In and Out
cpp = C Pre Processor 
cron = Chronos 希腊文时间
cups = Common Unix Printing System 
cvs = Current Version System 
daemon = Disk And Execution MONitor 
dc = Desk Calculator 
dd = Disk Dump (磁盘转储)
df = Disk Free 
diff = Difference 
dmesg = diagnostic message 
du = Disk Usage 
ed = editor 
egrep = Extended GREP 
elf = Extensible Linking Format 
elm = ELectronic Mail 
emacs = Editor MACroS 
eval = EVALuate 
ex = EXtended 
exec = EXECute (执行)
fd = file descriptors 
fg = ForeGround
fgrep = Fixed GREP 
fmt = format 
fsck = File System ChecK 
fstab = FileSystem TABle 
gawk = GNU AWK 
gpg = GNU Privacy Guard 
groff = GNU troff 
hal = Hardware Abstraction Layer 
ksh = Korn SHell 
lex = LEXical analyser 
lisp = LISt Processing = Lots of IrritatingSuperfluous Parentheses 
ln = Link
lpr = Line PRint 
ls = list 
lsof = LiSt Open Files 
m4 = Macro processor Version 4 
man = MANual pages 

mc = Midnight Commander 
mkfs = MaKe FileSystem 
mknod = Make Node 
motd = Message of The Day 
mtab = Mount TABle 
nl = Number of Lines 
nm = names 
nohup = No HangUP 
nroff = New ROFF 
od = Octal Dump 
passwd = Passwd
pg = pager 
pico = PIne's message COmposition editor 
pine = "Program for Internet News &Email" = "Pine is not Elm" 
ping = 拟声 又 = Packet Internet Grouper 
pirntcap = PRINTer CAPability 
popd = POP Directory
pr = pre 
printf = Print Formatted 
ps = Processes Status 
pty = pseudo tty 
pushd = PUSH Directory 
pwd = Print Working Directory 
rsh, rlogin, rvim中的
r = Remote 
rxvt = ouR XVT 
seamoneky = 我
sed = Stream Editor 
seq = SEQuence 
shar = Shell ARchive 
slrn = S-Lang rn 
ssh = Secure Shell
ssl = Secure Sockets Layer 
stty = Set TTY 
su = Substitute User 
svn = SubVersion 
tar = Tape ARchive 
tcsh = TENEX C shell  
tee = T (T形水管接口) 
telnet = TEminaL over Network 
termcap = terminal capability 
terminfo = terminal information 
tr = traslate 
troff = Typesetter new ROFF 
tsort = Topological SORT 
tty = TeleTypewriter 
twm = Tom's Window Manager 
tz = TimeZone 
udev = Userspace DEV 
ulimit = User's LIMIT 
umask = User's MASK 
uniq = UNIQue
i = VIsual = Very Inconvenient 
vim = Vi IMproved 
wall = write all 
wc = Word Count   
wine = WINE Is Not an Emulator 
xargs = eXtended ARGuments 
xdm = X Display Manager 
xlfd = X Logical Font Description 
xmms = X Multimedia System 
xrdb = X Resources DataBase 
xwd = X Window Dump 
yacc = yet another compiler compiler 
Fish = the Friendly Interactive SHell 
su = Switch User 
MIME = Multipurpose Internet Mail Extensions 
ECMA = European Computer ManufacturersAssociation 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值