sudo and su

10:54

Sudo is a standard way to give users some administrative rights without giving out the root password. Sudo is very useful in a multi user environment with a mix of server and workstations. Simply call the command with sudo:

sudo /etc/init.d/dhcpd restart            # Run the rc script as root
sudo -u sysadmin whoami                   # Run cmd as an other user

Configuration

Sudo is configured in /etc/sudoers and must only be edited with visudo. The basic syntax is (the lists are comma separated):

user hosts = (runas) commands          # In /etc/sudoers
  • users
    one or more users or %group (like %wheel) to gain the rights
  • hosts
    list of hosts (or ALL)
  • runas
    list of users (or ALL) that the command rule can be run as. It is enclosed in ( )!
  • commands
    list of commands (or ALL) that will be run as root or as (runas)

Additionally those keywords can be defined as alias, they are called User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for larger setups. Here a sudoers example:

cat /etc/sudoers
# Host aliases are subnets or hostnames.Host_Alias   DMZ     = 212.118.81.40/28
Host_Alias   DESKTOP = work1, work2

# User aliases are a list of users which can have the same rights
User_Alias   ADMINS  = colin, luca, admin
User_Alias   DEVEL   = joe, jack, julia
Runas_Alias  DBA     = oracle,pgsql

# Command aliases define the full path of a list of commands
Cmnd_Alias   SYSTEM  = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/init.d/
Cmnd_Alias   PW      = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root # Not root pwd!
Cmnd_Alias   DEBUG   = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap

# The actual rules
root,ADMINS  ALL     = (ALL) NOPASSWD: ALL    # ADMINS can do anything w/o a password.
DEVEL        DESKTOP = (ALL) NOPASSWD: ALL    # Developers have full right on desktops
DEVEL        DMZ     = (ALL) NOPASSWD: DEBUG  # Developers can debug the DMZ servers.

# User sysadmin can mess around in the DMZ servers with some commands.
sysadmin     DMZ     = (ALL) NOPASSWD: SYSTEM,PW,DEBUG
sysadmin     ALL,!DMZ = (ALL) NOPASSWD: ALL   # Can do anything outside the DMZ.
%dba         ALL     = (DBA) ALL              # Group dba can run as database user.

# anyone can mount/unmount a cd-rom on the desktop machines
ALL          DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom

The su utility requests appropriate user credentials via PAM and switches to that user ID (the default user is the superuser). A shell is then executed.

PAM is used to set the policy su(1) will use. In particular, by default only users in the wheel group can switch to UID 0 (root). This group requirement may be changed by modifying the pam_group

section of /etc/pam.d/su. See pam_group for details on how to modify this setting.
By default, the environment is unmodified with the exception of USER, HOME, and SHELL. HOME and SHELL are set to the target login’s default values. USER is set to the target login, unless the target login has a
user ID of 0, in which case it is unmodified. The invoked shell is the one belonging to the target login. This is the traditional behavior of su. Resource limits and session priority applicable to the original user’s login class (see login.conf(5)) are also normally retained unless the target login has a user ID of 0.

The options are as follows:

  • -f
    If the invoked shell is csh(1), this option prevents it from reading the “.cshrc” file.
  • -l
    Simulate a full login. The environment is discarded except for HOME, SHELL, PATH, TERM, and USER. HOME and SHELL are modified as above. USER is set to the target login. PATH is set to /bin:/usr/bin. TERM is imported from your current environ- ment. Environment variables may be set or overridden from the
    login class capabilities database according to the class of the target login. The invoked shell is the target login’s, and su will change directory to the target login’s home directory. Resource limits and session priority are modified to that for the target account’s login class.
  • -
    (no letter) The same as -l.
  • -m
    Leave the environment unmodified. The invoked shell is your login shell, and no directory changes are made. As a security precaution, if the target user’s shell is a non-standard shell (as defined by getusershell(3)) and the caller’s real uid is non- zero, su will fail.
  • -s
    Set the MAC label to the user’s default label as part of the user credential setup. Setting the MAC label may fail if the MAC label of the invoking process is not sufficient to transition to the user’s default MAC label. If the label cannot be set, su will fail.
  • -c
    class Use the settings of the specified login class. Only allowed for the superuser.

The -l (or -) and -m options are mutually exclusive; the last one specified overrides any previous ones.

If the optional args are provided on the command line, they are passed to the login shell of the target login. Note that all command line arguments before the target login name are processed by su itself, everything
after the target login name gets passed to the login shell.

By default (unless the prompt is reset by a startup file) the superuser prompt is set to # to remind one of its awesome power.

ENVIRONMENT
Environment variables used by su:

  • HOME
    Default home directory of real user ID unless modified as specified above
  • PATH
    Default search path of real user ID unless modified as specified above.
  • TERM
    Provides terminal type which may be retained for the substituted user ID.
  • USER
    The user ID is always the effective ID (the target user ID) after an su unless the user ID is 0 (root).
  • FILES
    /etc/pam.d/su PAM configuration for su.

EXAMPLES

su man -c catman

Runs the command catman as user man. You will be asked for man’s password unless your real UID is 0.
su man -c ‘catman /usr/share/man /usr/local/man /usr/X11R6/man’ Same as above, but the target command consists of more than a single word and hence is quoted for use with the -c option being
passed to the shell. (Most shells expect the argument to -c to be a single word). su -c staff man -c, catman /usr/share/man /usr/local/man /usr/X11R6/man Same as above, but the target command is run with the resource limits of the login class staff. Note: in this example, the first -c option applies to su while the second is an argument to the shell being invoked.

su -l foo   #Simulate a login for user foo.
su - foo    #Same as above.
su -        #Simulate a login for root.

经典*nix命令

10:50
id              #显示用户的uid,gid,groups信息
echo $LOGNAME   #显示登录的用户名
bc              #计算表达式,输入2+3 回车计算出5; quit 退出
df -k           #以K字节显示文件系统使用情况

一行命令杀进程inetd
Kill 命令

kill -1 `ps -e | grep inetd |awk '{print $1}'`
netstat -a | grep bat #检查 batserv 程序是否处于监听状态。

more 显示文件的时候,想退出按 q 键,到最前按 g< 键,h 键显示帮助,到最后按 G

env         #查看环境变量
uname -a    #查看本机型号
hostname    #显示主机名
domainname  #显示主机域名

存储, 压缩文件

tar -zcvf
tar -cvf target.tar sourcefilelist  #打包
tar -xvf target.tar                 #解包
tar -tvf target.tar                 #查看包内文件目录结构
compress .tar                       #文件压缩为.z
uncompress .z文件                   #解压缩文件
file                                #查看当前目录下所有文件的格式 file * | grep commands
which 程序名                        #查看命令文件的位置,这个是一个单独的文件
type 程序名                         #查看命令文件的位置,这个是bash内置命令
script                              #从键入script开始,所有终端显示内容将被输入到一个文件里(默认为typescript),直至 exit 或者 Ctrl+D 退出script环境。这在希望记录大段输入以及输出内容时很有用。
compress filename                   #压缩文件
compressdir directory-name          #压缩目录
uncompress filename             #反压缩文件
uncompressdir directory-name        #反压缩目录

搜索含有某个指令的脚本:

find /etc 2>/dev/null | xargs grep 'awk ' 2>/dev/null

说明:

  • find /etc 查找/etc 目录下的所有文件,并显示文件名
  • 2>/dev/null 把所有的错误信息,如权限错误,不能访问等重定向倒看不到的虚拟设备,只显示有用信息。(1 代表"标准输出”,2 代表“标准错误输出”)
  • | 把前一个命令的输出以管道的方式传给后面的命令
  • xargs 对输入的每一个参数,循环执行后面的命令
  • grep 'awk'在指定文件中查找字符串,这里的输入文件时 xargs 命令传过来的,每次处理一个 find 输出的文件名
find . | xargs grep "abc" #全文检索,打印出来包含关键字的文件名和行数据

find . -exec grep -l "string" {} \;             #全文检索,只显示包含关键字的文件名
find . -name *.cpp grep -l "字符串" {} \;       #切换用户并使用该用户的环境配置:su - user
#删除一些旧的文件,但是遇到windows的长文件名时的删除方法
find ./ -mtime +300 | awk -F \0 '{printf("\"%s\"\n",$0)}' | xargs -n 1 rm -f
#查找某个目录下的具有包含某个字符串的文件并删除:
find .  -type f -exec grep "232" {} \; -exec rm {} \;
find .  -type f -exec grep -q "123" {} \; -exec rm {}\;
#删除当前计算机系统日期前2天产生的所有文件,包括子目录下所有目录和文件:
find . -type d -atime +2 -exec /bin/rm -r '{}' 2>/dev/null \
find . -type f -atime +2 -exec /bin/rm -r '{}' 2>/dev/null \
grep 字符串  *                          #在当前目录(不包括子目录)里搜索文件内容
find . | xargs grep aaa                 #在当前目录(包括子目录)里搜索文件内容
find . | xargs grep typedef.*TIASTRU    #同时包含词"typedef"和"TIASTRU"
find . -exec grep -l "string" {} \;     #在当前目录全文查找string串
find . -name file1.c

正则表达式

  • .* 匹配任意字符
  • .. 匹配2个字符
  • abc?(2|9)1 ?匹配0或1个2或9
  • abc*([0–9]) *匹配0或多个0-9
  • abc+([0–9]) +匹配1或多个0-9
  • no@(one|ne) @严格匹配one和ne
  • no!(thing|where) !不匹配thing或where

unix上查看本地的ip地址和网卡信息:

hostname        #显示机器名
cat /etc/hosts
netstat -in
chmod +x filename           #增加执行属性
rm -f file                  #删除文件
rm -rf directory            #删除文件夹
cd a*                       #就可以进入比如:appp的文件夹
ps -x                       #查看属于自己的进程
ps -ef | grep ap*           #查找以ap开头的进程
uname -a                    #显示操作系统os类型
ls -Rl | more     #以分页方式列出目录下所有文件子目录

查看系统中的使用者:

who or finger
su username       #进入其他帐号
who am i

vi模式下

vi *.sql                            #假如vi编辑多个文件,用:n切换下一个文件
ESC + :!sh or :!ksh                 #执行外部命令
ESC + :20,24 w file                 #将文件20-24行放到file文件中
vi -R                               #只读打开文件
q!                                  #离开并放弃保存
wq                                  #离开并保存
w                                   #保存但不离开
ESC+:232                            #代表跳到252行
ESC+:/banner                        #代表跳到查找包含banner词的行,用 n 还可继续查
ESC+: r                             #vi嵌入外部文件 r 文件路径
ESC+:! ls                           #vi执行外部命令
man ls                              #在线帮助man+命令
mv                                  #移动或更改文件、目录名称
pwd                                 #当前目录
cat/more  cat file1 | more
kill PID                            #杀死进程
df          #查看磁盘中可以使用的自由空间
df -t       #查看使用百分比例
diff           #比较两个文件

more 或 vi 向下翻页用 CTRL+D,向上翻页用CTRL+B

l -rt           #显示最近更新的文件

unix默认shell采用ksh
在命令行下,使用时先按“ESC”键

  • j 向后查找
  • k 向前查找
  • / 查找关键字,回车匹配查找,按n显示下一个满足条件命令行,该功能类似vi中操作

用 ESC+k 或 j 上翻或下翻显示历史命令的时候,如何编辑命令呢
k 上翻,l 光标后移,x 删除光标所在的字符,向上箭头把光标移到最后,i 输入新字符

关机

shutdown -y 0
sprintf(szYhtId, "%08s", szTemp);       #字符串不够8位左补0:不要忘了s
szYhtid = atoi(yhtid);                  #转换为INT类型

本地工作站与远端工作站之间文件传输必须拥有远端工作站之帐(号及密码,才可进行传输工作)
执行格式:ftp hostname or ftp ip_address
Example :

ftp doc                 #与远端工作站 doc ,进行文件传输
Name (doc:user-name): 输入帐号
Password (doc:user-name): 输入密码

FTP 命令

  • help 列出 ftp 文件传输,可使用之任何命令。
  • !ls 列出本地工作站,目前目录下之所有文件名。
  • !pwd 列出本地工作站,目前所在之工作目录位置。
  • ls 列出远端工作站目前目录下之所有文件名。
  • dir 列出远端工作站目前目录下之所有文件名(略同於 UNIX 的 ls -l 指令).
  • dir . | more 同上,但每页会暂停(可能不适用 Unix 以外的 ftp)。
  • pwd 列出远端工作站目前所在之目录位置。
  • cd dir1 更改远端工作站之工作目录位置至 dir1 之下。
  • get file1 将远端工作站之文件 file1 ,拷贝到本地工作站中。
  • put file2 将本地工作站之文件 file2 ,拷贝到远端工作站中。
  • mget *.c 将远端工作站中,副文件名为 c 之所有文件,拷贝到本地工作站中。
  • mput *.txt 将本地工作站中,副文件名为 txt 之所有文件,拷贝远端工作站中。
  • prompt 切换交谈式指令(使用 mput/mget 时不用每个文件皆询问yes/no)。
  • quit 结束 ftp 工作。
  • bye 结束 ftp 工作。
  • lcd 切换本地目录

注:
1. 从PC与工作站间的文件传输也可通过在 PC端的 FTP指令进行文件传输,指令用法与上所述大致相同。
2. ![cmd[args]] 在本地机中执行交互shell、exit回到ftp环境,如!ls *.zip

例:

ftp -n -i -v << !
open 172.10.1.11
user test test
prompt
as
quote type b 9
lcd /home/usr/test/yht
cd /home/test/test
mput *
bye
!

注:prompt指设置交互提示,这里关闭

« Previous Page