Linux usage Tips

Source: Internet
Author: User
Tags perl interpreter

This article describes the Linux usage techniques that are accumulated in peacetime.

Hidden properties of the file's properties file
    • lsattr: List hidden properties of a file
    • chattr: Modify hidden properties of a file

      [[email protected] ~]# chattr [+-=][ASacdistu] FileName+ : Add one attribute- : Remove one attribute= : Set to be the only attributes that the files have

Important Options

    • A: You can only append the contents of a file, but you cannot modify or delete it
    • I: File cannot be deleted, renamed, Cannot create a link to it, cannot write to file
Special permissions for Files Suid/sgid/sticky Bit

If a suid or Sgid bit is set on an executable file, the file owner (set suid) or the group (with Sgid set) will have the permissions when the files are executed.

Example: An ordinary user cannot turn on the HTTPD service because the HTTPD service needs to use port 80, and the port below 1024 is only available to the root user. If we set the owner of the httpd executable to root and set the SUID bit at the same time, the HTTPD service can also be turned on by ordinary users.

If you set the sticky bit for a directory, only the owner of the file can delete the file. In a Linux system, the/tmp directory defaults to this bit:

drwxrwxrwt 12 root root 16384 Mar 6 09:04 tmp/

The main use methods are as follows:

SUID

    • For files: Run with the permissions of the file owner
    • For directory: Cannot set suid to directory

Set SUID:

chmod u+s FILE chmod 4755 FILE

SGID

    • For files: Run with permissions for the group to which the file belongs
    • For directories: Files in the directory inherit the properties of the directory

Set Sgid:

chmod g+s FILE/DIR chmod 2771 FILE/DIR

Sticky

    • For file: Cannot set sticky bit on file
    • For directories: For files in this directory, only their owners can delete them.

Set Sticky:

chmod o+t DIR chmod 1777 DIR

Set special permissions with letters:

u+s g+s o+t

Special permissions are represented by numbers:

4 for SUID2 for SGID1 for Sticky
Special Permissions for Scripts

It is important to note that script files such as Shell, Python, and Perl cannot be set suid bits because they are actually run by bash, Python, and Perl interpreter. For the script file to have a function similar to suid, we need a shell, which can set the Suid/sgid bit, the shell really works or the script.

For example, we have a script /home/jh/bin/myscript.sh , the owner is a normal user, but the script inside the operation requires root permission, now we use C language to write this shell, the name is called transeuid.c :

/** author: JH Gao <[email protected]>* Create Date: 2012-06-05* Function: transmit euid and egid to other scripts* since shell/python/... scripts can‘t get suid permission in Linux*/#include <stdio.h>#include <stdlib.h>#include <unistd.h>#define BUFFSIZE 1024/** usually euid is the uid who run the program* but when stick is setted to the program* euid is the uid or the program‘s owner*/int main(int argc, char *argv[]) {    char *cmd = "/home/jh/bin/myscript.sh";    char *pars[] = {"/home/jh/bin/myscript.sh", "par1", "par2"};    /* set uid and gid to euid and egid */    setuid(geteuid());    setgid(getegid());    if (execvp(cmd, pars)) {        printf("error");        free(cmd);        exit(1);    }    free(cmd);}

Compile this program, set the desired user to this program, then set SUID, then you can execute the script or command with this user's privileges:

$ gcc -t transeuid transeuid.c$ sudo chown root transeuid$ sudo chmod +s transeuid$ ./transeuid ......DO SOMETHING

But it is important to note that this gimmick has great security implications.

/etc/fstab file error What to do

At this point, the system does not start normally, you can start to enter single user mode, while the root directory "/" is read-only, you can use the following command to re-mount "/" to "Read and write":

[[email protected]]# mount -n -o remount,rw /-n : mount but do not change /etc/mtab-o : options
partprobe– do not restart using the new partition table

partprobe: reinitializes the kernel in memory of the partition table. After you change the partition settings, you are prompted to restart to change the partition table in the kernel, and you can eliminate the restart by using Partprobe.

Ubuntu system switching between GDM and KDM

If you have both GNOME and KDE installed, there are times when you need to switch between GDM and KDM:

sudo dpkg-reconfigure gdm
Increase swap space
    • Create a new partition or a new file
    • Write special tags with the Mkswap tool
    • Add a new record to the/etc/fstab
    • Activate swap partition, command swapon-a or Swapon [Swapfile]
    • Check the status of the swap partition with the Swapon-s command

Example:

dd if=/dev/zero of=/swapfile bs=1M count=100mkswap /swapfilevi /etc/fstab ...swapon -a
One NIC binds multiple IPs

Example:

The system is CentOS, the NIC is eth0, if only 1 additional IP is set, the file is created
/etc/sysconfig/network-scripts/ifcfg-eth0:0
, set the IP information in the file.

If you need to set up an IP segment, create the file ifcfg-ethX-rangeX :

IFCFG-ETH0-RANGE0:

DEVICE=eth0-range0BOOTPROTO=staticHWADDR=08:00:27:24:C2:72ONBOOT=yesIPADDR_START=192.168.56.20IPADDR_END=192.168.56.30NETMASK=255.255.255.0
Lsof

The lsof command can list all open files. The most common function of this command is to find the "lost" space.

For example, we use the DF command to see the/home partition with only 1 G left, but the result of the du command is that there should be 5G.
, this situation is often caused by the deletion of some files, but the file handles of the deleted files have not been released.
With the command

lsof | grep -i deleted

See which files have been deleted but the file handle has not been released, kill or restart the response process will be able to retrieve the "lost" space.

Lsof can sometimes recover files that have been mistakenly deleted, please google for specific methods.

Directory length

The length of the directory is never 0, because it always contains. and.. Two items. The length of a symbolic connection is the number of characters that its pathname contains, and the length is not 0 because there is at least one character in the path name.

Create a folder named "-F"

To create a folder named "-F", the use of commands will mkdir -f inevitably fail, and you mkdir -- -f can create a success.

The difference between Su and SU in a "CD-" switch between the two most recently used directories

Executing su The modern shell inherits the current shell environment, Su-simulates the actual root login session

Quick Erase History
export HISTSIZE=0
Bash in the $Related parameters
    • $0-Indicates the current file name
    • $*-Separates all parameters with a space, forming a string
    • [email protected]-Separates all parameters with a space, forming a string combination. $*differs from the expression when "" refers to "$*" a string that "[email protected]" contains more than one string
    • $#-Number of arguments passed to the process
    • $?-The execution result of the previous command, 0 if there is no error
    • $$-PID of this command
Bash techniques, variable names that are combined by the contents of a variable into another variable

EXAMPLE:

A_B_C_D="something"t1="B"t2="_D"eval echo \$A_${t1}_C${t2};
Bash command Line input tips

Use Ctrl+R to search for previously used commands
Use Ctrl+W Delete current single time
Use Ctrl+U Delete as forward

Xargs

Xargs is powerful, with -l{} the ability to specify the location of the parameter:

cat hosts | xargs -I{} ssh [email protected]{} hostname
Write a secure bash script

The most common ones are:

    • set -e, the script exits when an error occurs
    • set -uExit when Bash discovers that there are no initialized variables

More information: Write a robust bash script

Tar package files listed in the specified list
cat yourlist.lst/etc/fstab/home/admin/bin/somefile.sh/home/mysql/somefile...tar cvzf xxx.tar.gz -T yourlist.lst
Specify a DNS server to query the domain name records
dig @8.8.8.8 www.google.com
The most important parameters to note for the sort command are-K and-s:
-s, --stable              stabilize sort by disabling last-resort comparison

Stable indicates that the final order depends on the original order.

$ cat a.txtaABb$ sort -f a.txtaAbB$ sort -f -s a.txtaABb

example,-f means case-insensitive, and-s indicates that the order depends on the order of the original file

-k, --key=POS1[,POS2]              start a key at POS1 (origin 1), end it at POS2 (default end of line).

So just sort the second column should write:

sort -k1,1

For more tips on sort, refer to
Sort Files like A Master with the Linux Sort Command (Bash)

The use of Man

The man page may have several sections, such as this:

$ man -aw man/usr/share/man/man1/man.1.gz/usr/share/man/man7/man.7.gz

There are 2 sections. It is also often seen in the man page similar to:

SEE ALSO   epoll_create(2), epoll_create1(2), epoll_ctl(2), epoll_wait(2)

The numbers inside the brackets refer to section. Different sections represent different categories of content:

MANUAL SECTIONSThe standard sections of the manual include:1      User Commands2      System Calls3      C Library Functions4      Devices and Special Files5      File Formats and Conventions6      Games et. Al.7      Miscellanea8      System Administration tools and DeamonsDistributions customize the manual section to their specifics,which often include additional sections.

View 7th section:

man 7 man
MPlayer character Playback:
mplayer -vo aa xxx.avi 用无颜色的字符播放;mplayer -vo caca xxx.avi 用有颜色的ASCII字符播放;mplayer -vo matrixiew xxx.avi 用类似黑客帝国里面的终端播放!
Custom Endpoint Auto-complete

For example, I want to ssh, Ping, myscript these three commands automatically complete parameters, where the parameter name is written in the/tmp/my_word_list file, we can do the .bashrc following settings:

function _my_cmpl() {    local my_cmpl_words cur    COMPREPLY=()    cur="${COMP_WORDS[COMP_CWORD]}"    my_cmpl_words=`cat /tmp/my_word_list`    COMPREPLY=( $( compgen -W "$my_cmpl_words" -- "$cur" ) )}complete -F _my_cmpl ssh ping myscript
SSH Save session

vi/home/User name/.ssh/config (no new one), add the following:

jHost *jControlMaster autojControlPath /tmp/%[email protected]%h:%p

Save exit. Once you log in to the server and then log in to the same server in the new terminal, you don't have to lose the password.

SSH over the wall

SSH over the crab wall, if you have a server outside the wall, and you can ssh to it without a password,
You can use SSH to do port forwarding to realize the flip of the wall.
Plus the switchy on Chrome or the Autoproxy plugin on Firefox will be free to surf the web.

Use the local 7001 port as the forwarding gate:

ssh -qTfnN -D 7001 [email protected]_SERVER
The first parameter calls a function as a function name
func_eval() {    TYPE=`type $1 | head -1 | awk ‘{print $NF}‘`    if [ $? -gt 0 ]; then        echo "ERROR call function: $1 ... failed"    elif [ "$TYPE" == "function" ]; then        eval $*    else        echo "ERROR invalid function: $1 ..."        exit 1    fi}
The most understandable and efficient way to work with files on a row-by-line basis:
while read LINEdo     echo "$LINE" >> $OUTFILE     # do somethingdone < $INPUTFILE
Get the length of a string represented by a variable:
`echo ${#VAR}`
${PAGER:-more}

Shell command ${PAGER:-more}
This means that if the shell variable pager is already defined and its value is not NULL, its value is used, otherwise the string more is used.

$$Represents the PID of the current process.

Resources:

    • Http://www.quora.com/Linux/What-are-some-time-saving-tips-that-every-Linux-user-should-know
    • http://article.yeeyan.org/view/58906/257928
    • http://www.skorks.com/2010/05/sort-files-like-a-master-with-the-linux-sort-command-bash/

Linux usage Tips

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.