This commit is contained in:
KayGuoWhu 2015-05-19 08:40:06 +08:00
commit c2b2b27bee
18 changed files with 1565 additions and 425 deletions

View File

@ -1,117 +0,0 @@
translating by wwy-hust
Guake 0.7.0 Released A Drop-Down Terminal for Gnome Desktops
================================================================================
Linux commandline is the best and most powerful thing that fascinates a new user and provides extreme power to experienced users and geeks. For those who work on Server and Production, they are already aware of this fact. It would be interesting to know that Linux console was one of those first features of the kernel that was written by Linus Torvalds way back in the year 1991.
Terminal is a powerful tool that is very reliable as it does not have any movable part. Terminal serves as an intermediate between console and GUI environment. Terminal themselves are GUI application that run on top of a desktop environment. There are a lot of terminal application some of which are Desktop Environment specific and rest are universal. Terminator, Konsole, Gnome-Terminal, Terminology, XFCE terminal, xterm are a few terminal emulators to name.
You may get a list of most widely used Terminal Emulator follow the below link.
- [20 Useful Terminals for Linux][1]
Last day while surfing web, I came across a terminal namely guake which is a terminal for gnome. Though this is not the first time I have learned about Guake. Id known this application nearly one year ago but somehow I could not write on this and later it was out of my mind until I heard it again. So finally the article is here. We will be taking you to Guake features, installation on Debian, Ubuntu and Fedora followed by quick testing.
#### What is Guake? ####
Guake is a Drop Down Terminal for Gnome Environment. Written from scratch mostly in Python and a little in C this application is released under GPLv2+ and is available for Linux and alike systems. Guake is inspired by a console in computer game Quake which slides down from the top by pressing a specially Key (Default is F12) and then slides-up when the same key is pressed.
Important to mention that Guake is not the first of this kind. Yakuake which stands for Yet Another Kuake, a terminal emulator for KDE Desktop Environment and Tilda which is a GTK+ terminal Emulator are also inspired by the same slide up/down console of computer game Quake.
#### Features of Guake ####
- Lightweight
- Simple Easy and Elegant
- Functional
- Powerful
- Good Looking
- Smooth integration of terminal into GUI
- Appears when you call and disappear once you are done by pressing a predefined hot key
- Support for hotkeys, tabs, background transparency makes it a brilliant application, must for every Gnome User.
- Extremely configurable
- Plenty of color palette included, fixed and recognized
- Shortcut for transparency level
- Run a script when Guake starts via Guake Preferences.
- Able to run on more than one monitor
Guake 0.7.0 was released recently, which brings numerous fixes as well as some new features as discussed above. For complete Guake 0.7.0 changelog and source tarball packages can be found [Here][2].
### Installing Guake Terminal in Linux ###
If you are interested in compiling Guake from source you may download the source from the link above, build it yourself before installing.
However Guake is available to be installed on most of the distributions from repository or by adding an additional repository. Here, we will be installing Guake on Debian, Ubuntu, Linux Mint and Fedora systems.
First get the latest software package list from the repository and then install Guake from the default repository as shown below.
---------------- On Debian, Ubuntu and Linux Mint ----------------
$ sudo apt-get update
$ apt-get install guake
----------
---------------- On Fedora 19 Onwards ----------------
# yum update
# yum install guake
After installation, start the Guake from another terminal as:
$ guake
After starting it, use F12 (Default) to roll down and roll up the terminal on your Gnome Desktop.
Seems very beautiful specially the transparent background. Roll down… Roll up… Roll down… Roll up…. run command. Open another tab run command… Roll up… Roll down…
![Guake Terminal in Action](http://www.tecmint.com/wp-content/uploads/2015/05/Guake.png)
Guake Terminal in Action
If your wallpaper or working windows color dont match you may like to change your wallpaper or reduce the transparency of the Guake terminal color.
Next is to look into Guake Properties to edit settings as per requirements. Run Guake Preferences either by running it from Application Menu or by running the below command.
$ guake --preferences
![Guake Terminal Properties](http://www.tecmint.com/wp-content/uploads/2015/05/Guake-Properties.png)
Guake Terminal Properties
Scrolling Properties..
![Guake Scrolling Settings](http://www.tecmint.com/wp-content/uploads/2015/05/Guake-Scrolling.png)
Guake Scrolling Settings
Appearance Properties Here you can modify text and background color as well as tune transparency.
![Appearance Properties](http://www.tecmint.com/wp-content/uploads/2015/05/Appearance-Properties.png)
Appearance Properties
Keyboard Shortcuts Here you may edit and Modify Toggle key for Guage Visibility (default is F12).
![Keyboard Shortcuts](http://www.tecmint.com/wp-content/uploads/2015/05/Keyboard-Shortcuts.png)
Keyboard Shortcuts
Compatibility Setting Perhaps you wont need to edit it.
![Compatibility Setting](http://www.tecmint.com/wp-content/uploads/2015/05/Compatibility-Setting.png)
Compatibility Setting
### Conclusion ###
This Project is not too young and not too old, hence has reached certain level of maturity and is quiet solid and works out of the box. For someone like me who need to switch between GUI and Console very often Guake is a boon. I dont need to manage an extra window, open and close frequently, use tab among a huge pool of opened applications to find terminal or switch to different workspace to manage terminal now all I need is F12.
I think this is a must tool for any Linux user who makes use of GUI and Console at the same time, equally. I am going to recommend it to anyone who want to work on a system where interaction between GUI and Console is smooth and hassle free.
Thats all for now. Let us know if there is any problem in installing and running. We will be here to help you. Also tell us yours experience about Guake. Provide us with your valuable feedback in the comments below. Like and share us and help us get spread.
--------------------------------------------------------------------------------
via: http://www.tecmint.com/install-guake-terminal-ubuntu-mint-fedora/
作者:[Avishek Kumar][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.tecmint.com/author/avishek/
[1]:http://www.tecmint.com/linux-terminal-emulators/
[2]:https://github.com/Guake/guake/releases/tag/0.7.0

View File

@ -1,72 +0,0 @@
How to make a file immutable on Linux
================================================================================
Suppose you want to write-protect some important files on Linux, so that they cannot be deleted or tampered with by accident or otherwise. In other cases, you may want to prevent certain configuration files from being overwritten automatically by software. While changing their ownership or permission bits on the files by using chown or chmod is one way to deal with this situation, this is not a perfect solution as it cannot prevent any action done with root privilege. That is when chattr comes in handy.
chattr is a Linux command which allows one to set or unset attributes on a file, which are separate from the standard (read, write, execute) file permission. A related command is lsattr which shows which attributes are set on a file. While file attributes managed by chattr and lsattr are originally supported by EXT file systems (EXT2/3/4) only, this feature is now available on many other native Linux file systems such as XFS, Btrfs, ReiserFS, etc.
In this tutorial, I am going to demonstrate how to use chattr to make files immutable on Linux.
chattr and lsattr commands are a part of e2fsprogs package which comes pre-installed on all modern Linux distributions.
Basic syntax of chattr is as follows.
$ chattr [-RVf] [operator][attribute(s)] files...
The operator can be '+' (which adds selected attributes to attribute list), '-' (which removes selected attributes from attribute list), or '=' (which forces selected attributes only).
Some of available attributes are the following.
- **a**: can be opened in append mode only.
- **A**: do not update atime (file access time).
- **c**: automatically compressed when written to disk.
- **C**: turn off copy-on-write.
- **i**: set immutable.
- **s**: securely deleted with automatic zeroing.
### Immutable Attribute ###
To make a file immutable, you can add "immutable" attribute to the file as follows. For example, to write-protect /etc/passwd file:
$ sudo chattr +i /etc/passwd
Note that you must use root privilege to set or unset "immutable" attribute on a file. Now verify that "immutable" attribute is added to the file successfully.
$ lsattr /etc/passwd
Once the file is set immutable, this file is impervious to change for any user. Even the root cannot modify, remove, overwrite, move or rename the file. You will need to unset the immutable attribute before you can tamper with the file again.
To unset the immutable attribute, use the following command:
$ sudo chattr -i /etc/passwd
![](https://farm9.staticflickr.com/8613/16152651317_076a65cf50_b.jpg)
If you want to make a whole directory (e.g., /etc) including all its content immutable at once recursively, use "-R" option:
$ sudo chattr -R +i /etc
### Append Only Attribute ###
Another useful attribute is "append-only" attribute which forces a file to grow only. You cannot overwrite or delete a file with "append-only" attribute set. This attribute can be useful when you want to prevent a log file from being cleared by accident.
Similar to immutable attribute, you can turn a file into "append-only" mode by:
$ sudo chattr +a /var/log/syslog
Note that when you copy an immutable or append-only file to another file, those attributes will not be preserved on the newly created file.
### Conclusion ###
In this tutorial, I showed how to use chattr and lsattr commands to manage additional file attributes to prevent (accidental or otherwise) file tampering. Beware that you cannot rely on chattr as a security measure as one can easily undo immutability. One possible way to address this limitation is to restrict the availability of chattr command itself, or drop kernel capability CAP_LINUX_IMMUTABLE. For more details on chattr and available attributes, refer to its man page.
--------------------------------------------------------------------------------
via: http://xmodulo.com/make-file-immutable-linux.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/nanni

View File

@ -1,63 +0,0 @@
zBackup A versatile deduplicating backup tool
================================================================================
zbackup is a globally-deduplicating backup tool, based on the ideas found in rsync. Feed a large .tar into it, and it will store duplicate regions of it only once, then compress and optionally encrypt the result. Feed another .tar file, and it will also re-use any data found in any previous backups. This way only new changes are stored, and as long as the files are not very different, the amount of storage required is very low. Any of the backup files stored previously can be read back in full at any time.
### zBackup Features ###
Parallel LZMA or LZO compression of the stored data
Built-in AES encryption of the stored data
Possibility to delete old backup data
Use of a 64-bit rolling hash, keeping the amount of soft collisions to zero
Repository consists of immutable files. No existing files are ever modified
Written in C++ only with only modest library dependencies
Safe to use in production
Possibility to exchange data between repos without recompression
### Install zBackup in ubuntu ###
Open the terminal and run the following command
sudo apt-get install zbackup
### Using zBackup ###
zbackup init initializes a backup repository for the backup files to be stored.
zbackup init [--non-encrypted] [--password-file ~/.my_backup_password ] /my/backup/repo
zbackup backup backups a tar file generated by tar c to the repository initialized using zbackup init
zbackup [--password-file ~/.my_backup_password ] [--threads number_of_threads ] backup /my/backup/repo/backups/backup-`date +%Y-%m-%d'`
zbackup restore restores the backup file to a tar file.
zbackup [--password-file ~/.my_backup_password [--cache-size cache_size_in_mb restore /my/backup/repo/backups/backup-`date +%Y-%m-%d'` > /my/precious/backup-restored.tar
### Available Options ###
- -non-encrypted -- Do not encrypt the backup repository.
- --password-file ~/.my_backup_password -- Use the password file specified at ~/.my_backup_password to encrypt the repository and backup file, or to decrypt the backup file.
- --threads number_of_threads -- Limit the partial LZMA compression to number_of_threads needed. Recommended for 32-bit architectures.
- --cache-size cache_size_in_mb -- Use the cache size provided by cache_size_in_mb to speed up the restoration process.
### zBackup files ###
~/.my_backup_password Used to encrypt the repository and backup file, or to decrypt the backup file. See zbackup for further details.
/my/backup/repo The directory used to hold the backup repository.
/my/precious/restored-tar The tar used for restoring the backup.
/my/backup/repo/backups/backup-`date +%Y-%m-%d'` Specifies the backup file.
--------------------------------------------------------------------------------
via: http://www.ubuntugeek.com/zbackup-a-versatile-deduplicating-backup-tool.html
作者:[ruchi][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://www.ubuntugeek.com/author/ubuntufix

View File

@ -1,3 +1,5 @@
Translating by goreliu ...
5 Interesting Command Line Tips and Tricks in Linux Part 1
================================================================================
Are you making most out of the Linux? There are lots of helpful features which appears to be Tips and Tricks for many of Linux Users. Sometimes Tips and Tricks become the need. It helps you get productive with the same set of commands yet with enhanced functionality.
@ -112,4 +114,4 @@ via: http://www.tecmint.com/5-linux-command-line-tricks/
[a]:http://www.tecmint.com/author/avishek/
[1]:http://www.tecmint.com/history-command-examples/
[2]:http://www.tecmint.com/check-linux-disk-usage-of-files-and-directories/
[2]:http://www.tecmint.com/check-linux-disk-usage-of-files-and-directories/

View File

@ -1,3 +1,5 @@
translating by wwy-hust
How to Serve Git Repositories Using Gitblit Tool in Linux
================================================================================
Hi friends, today we'll be learning how to install Gitblit in your Linux Server or PC. So, lets check out what is a Git, its features and steps to install Gitblit. [Git is a distributed revision control system][1] with an emphasis on speed, data integrity, and support for distributed, non-linear workflows. It was initially designed and developed by Linus Torvalds for Linux kernel under the terms of the GNU General Public License version 2 development in 2005, and has since become the most widely adopted version control system for software development.
@ -98,4 +100,4 @@ via: http://linoxide.com/linux-how-to/serve-git-repositories-gitblit/
[a]:http://linoxide.com/author/arunp/
[1]:http://git-scm.com/
[2]:http://gitblit.com/
[2]:http://gitblit.com/

View File

@ -0,0 +1,193 @@
10 Amazing and Mysterious Uses of (!) Symbol or Operator in Linux Commands
================================================================================
The `'!'` symbol or operator in Linux can be used as Logical Negation operator as well as to fetch commands from history with tweaks or to run previously run command with modification. All the commands below have been checked explicitly in bash Shell. Though I have not checked but a major of these wont run in other shell. Here we go into the amazing and mysterious uses of `'!'` symbol or operator in Linux commands.
### 1. Run a command from history by command number. ###
You might not be aware of the fact that you can run a command from your history command (already/earlier executed commands). To get started first find the command number by running history command.
$ history
![Find Last Executed Commands with History Command](http://www.tecmint.com/wp-content/uploads/2015/05/history-Command.gif)
Now run a command from history just by the number at which it appears, in the output of history. Say run a command that appears at number 1551 in the output of history command.
$ !1551
![Run Last Executed Commands by Number ID](http://www.tecmint.com/wp-content/uploads/2015/05/Run-Commands-By-number.gif)
And, it runs the command ([top command][1] in the above case), that was listed at number 1551. This way to retrieving already executed command is very helpful specially in case of those commands which are long. You just need to call it using **![Number at which it appears in the output of history command]**.
### 2. Run previously executed command as 2nd last command, 7th last command,etc. ###
You may run those commands which you have run previously by their running sequence being the last run command will be represented as -1, second last as -2, seventh last as -7,….
First run history command to get a list of last executed command. It is necessary to run history command, so that you can be sure that there is no command like `rm command > file` and others just to make sure you do not run any dangerous command accidentally. And then check Sixth last command, Eight last command and Tenth last command.
$ history
$ !-6
$ !-8
$ !-10
![Run Last Executed Commands By Numbers](http://www.tecmint.com/wp-content/uploads/2015/05/3.gif)
Run Last Executed Commands By Numbers
### 3. Pass arguments of last command that we run to the new command without retyping ###
I need to list the content of directory /home/$USER/Binary/firefox so I fired.
$ ls /home/$USER/Binary/firefox
Then I realized that I should have fired ls -l to see which file is executable there? So should I type the whole command again! No I dont need. I just need to carry the last argument to this new command as:
$ ls -l !$
Here `!$` will carry arguments passed in last command to this new command.
![Pass Arguments of Last Executed Command to New](http://www.tecmint.com/wp-content/uploads/2015/05/4.gif)
Pass Arguments of Last Executed Command to New
### 4. How to handle two or more arguments using (!) ###
Lets say I created a text file 1.txt on the Desktop.
$ touch /home/avi/Desktop/1.txt
and then copy it to /home/avi/Downloads using complete path on either side with cp command.
$ cp /home/avi/Desktop/1.txt /home/avi/downloads
Now we have passed two arguments with cp command. First is /home/avi/Desktop/1.txt and second is /home/avi/Downloads, lets handle them differently, just execute `echo [arguments]` to print both arguments differently.
$ echo “1st Argument is : !^”
$ echo “2nd Argument is : !cp:2”
Note 1st argument can be printed as `“!^”` and rest of the arguments can be printed by executing `“![Name_of_Command]:[Number_of_argument]”`.
In the above example the first command was cp and 2nd argument was needed to print. Hence `“!cp:2”`, if any command say xyz is run with 5 arguments and you need to get 4th argument, you may use `“!xyz:4”`, and use it as you like. All the arguments can be accessed by `“!*”`.
![Handle Two or More Arguments](http://www.tecmint.com/wp-content/uploads/2015/05/5.gif)
Handle Two or More Arguments
### 5. Execute last command on the basis of keywords ###
We can execute the last executed command on the basis of keywords. We can understand it as follows:
$ ls /home > /dev/null [Command 1]
$ ls -l /home/avi/Desktop > /dev/null [Command 2]
$ ls -la /home/avi/Downloads > /dev/null [Command 3]
$ ls -lA /usr/bin > /dev/null [Command 4]
Here we have used same command (ls) but with different switches and for different folders. Moreover we have sent to output of each command to /dev/null as we are not going to deal with the output of the command also the console remains clean.
Now Execute last run command on the basis of keywords.
$ ! ls [Command 1]
$ ! ls -l [Command 2]
$ ! ls -la [Command 3]
$ ! ls -lA [Command 4]
Check the output and you will be astonished that you are running already executed commands just by `ls` keywords.
![Run Commands Based on Keywords](http://www.tecmint.com/wp-content/uploads/2015/05/6.gif)
Run Commands Based on Keywords
### 6. The power of !! Operator ###
You can run/alter your last run command using `(!!)`. It will call the last run command with alter/tweak in the current command. Lets show you the scenario
Last day I run a one-liner script to get my private IP so I run,
$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/
Then suddenly I figured out that I need to redirect the output of the above script to a file ip.txt, so what should I do? Should I retype the whole command again and redirect the output to a file? Well an easy solution is to use `UP` navigation key and add `'> ip.txt'` to redirect the output to a file as.
$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/ > ip.txt
Thanks to the life Savior `UP` navigation key here. Now consider the below condition, the next time I run below one-liner script.
$ ifconfig | grep "inet addr:" | awk '{print $2}' | grep -v '127.0.0.1' | cut -f2 -d:
As soon as I run script, the bash prompt returned an error with the message `“bash: ifconfig: command not found”`, It was not difficult for me to guess I run this command as user where it should be run as root.
So whats the solution? It is difficult to login to root and then type the whole command again! Also (UP Navigation Key) in last example didnt came to rescue here. So? We need to call `“!!”` without quotes, which will call the last command for that user.
$ su -c “!!” root
Here su is switch user which is root, `-c` is to run the specific command as the user and the most important part `!!` will be replaced by command and last run command will be substituted here. Yeah! You need to provide root password.
![The Power of !! Key](http://www.tecmint.com/wp-content/uploads/2015/05/7.gif)
The Power of !! Key
I make use of `!!` mostly in following scenarios,
1. When I run apt-get command as normal user, I usually get an error saying you dont have permission to execute.
$ apt-get upgrade && apt-get dist-upgrade
Opps error…dont worry execute below command to get it successful..
$ su -c !!
Same way I do for,
$ service apache2 start
or
$ /etc/init.d/apache2 start
or
$ systemctl start apache2
OOPS User not authorized to carry such task, so I run..
$ su -c 'service apache2 start'
or
$ su -c '/etc/init.d/apache2 start'
or
$ su -c 'systemctl start apache2'
### 7. Run a command that affects all the file except ![FILE_NAME] ###
The `!` (Logical NOT) can be used to run the command on all the files/extension except that is behind `'!'`.
A. Remove all the files from a directory except the one the name of which is 2.txt.
$ rm !(2.txt)
B. Remove all the file type from the folder except the one the extension of which is pdf.
$ $ rm !(*.pdf)
### 8. Check if a directory (say /home/avi/Tecmint)exist or not? Printf if the said directory exist or not. ###
Here we will use `'! -d'` to validate if the directory exist or not followed by Logical AND Operator `(&&)` to print that directory does not exist and Logical OR Operator `(||)` to print the directory is present.
Logic is, when the output of `[ ! -d /home/avi/Tecmint ]` is 0, it will execute what lies beyond Logical AND else it will go to Logical OR `(||)` and execute what lies beyond Logical OR.
$ [ ! -d /home/avi/Tecmint ] && printf '\nno such /home/avi/Tecmint directory exist\n' || printf '\n/home/avi/Tecmint directory exist\n'
### 9. Check if a directory exist or not? If not exit the command. ###
Similar to the above condition, but here if the desired directory doesnt exist it will exit the command.
$ [ ! -d /home/avi/Tecmint ] && exit
### 10. Create a directory (say test) in your home directory if it does not exist. ###
A general implementation in Scripting Language where if the desired directory does not exist, it will create one.
[ ! -d /home/avi/Tecmint ] && mkdir /home/avi/Tecmint
Thats all for now. If you know or come across any other use of `'!'` which is worth knowing, you may like to provide us with your suggestion in the feedback. Keep connected!
--------------------------------------------------------------------------------
via: http://www.tecmint.com/mysterious-uses-of-symbol-or-operator-in-linux-commands/
作者:[Avishek Kumar][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.tecmint.com/author/avishek/
[1]:http://www.tecmint.com/12-top-command-examples-in-linux/

View File

@ -0,0 +1,182 @@
How to set up a Replica Set on MongoDB
================================================================================
MongoDB has become the most famous NoSQL database on the market. MongoDB is document-oriented, and its scheme-free design makes it a really attractive solution for all kinds of web applications. One of the features that I like the most is Replica Set, where multiple copies of the same data set are maintained by a group of mongod nodes for redundancy and high availability.
This tutorial describes how to configure a Replica Set on MonoDB.
The most common configuration for a Replica Set involves one primary and multiple secondary nodes. The replication will then be initiated from the primary toward the secondaries. Replica Sets can not only provide database protection against unexpected hardware failure and service downtime, but also improve read throughput of database clients as they can be configured to read from different nodes.
### Set up the Environment ###
In this tutorial, we are going to set up a Replica Set with one primary and two secondary nodes.
![](https://farm8.staticflickr.com/7667/17801038505_529a5224a1.jpg)
In order to implement this lab, we will use three virtual machines (VMs) running on VirtualBox. I am going to install Ubuntu 14.04 on the VMs, and install official packages for Mongodb.
I am going to set up a necessary environment on one VM instance, and then clone it to the other two VM instances. Thus pick one VM named master, and perform the following installations.
First, we need to add the MongoDB key for apt:
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
Then we need to add the official MongoDB repository to our source.list:
$ sudo su
# echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
Let's update repositories and install MongoDB.
$ sudo apt-get update
$ sudo apt-get install -y mongodb-org
Now let's make some changes in /etc/mongodb.conf.
auth = true
dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongod.log
logappend=true
keyFile=/var/lib/mongodb/keyFile
replSet=myReplica
The first line is to make sure that we are going to have authentication on our database. keyFile is to set up a keyfile that is going to be used by MongoDB to replicate between nodes. replSet sets up the name of our replica set.
Now we are going to create our keyfile, so that it can be in all our instances.
$ echo -n "MyRandomStringForReplicaSet" | md5sum > keyFile
This will create keyfile that contains a MD5 string, but it has some noise that we need to clean up before using it in MongoDB. Use the following command to clean it up:
$ echo -n "MyReplicaSetKey" | md5sum|grep -o "[0-9a-z]\+" > keyFile
What grep command does is to print MD5 string with no spaces or other characters that we don't want.
Now we are going to make the keyfile ready for use:
$ sudo cp keyFile /var/lib/mongodb
$ sudo chown mongodb:nogroup keyFile
$ sudo chmod 400 keyFile
Now we have our Ubuntu VM ready to be cloned. Power it off, and clone it to the other VMs.
![](https://farm9.staticflickr.com/8729/17800903865_9876a9cc9c.jpg)
I name the cloned VMs secondary1 and secondary2. Make sure to reinitialize the MAC address of cloned VMs and clone full disks.
![](https://farm6.staticflickr.com/5333/17613392900_6de45c9450.jpg)
All three VM instances should be on the same network to communicate with each other. For this, we are going to attach all three VMs to "Internet Network".
It is recommended that each VM instances be assigned a static IP address, as opposed to DHCP IP address, so that the VMs will not lose connectivity among themselves when a DHCP server assigns different IP addresses to them.
Let's edit /etc/networks/interfaces of each VM as follows.
On primary:
auto eth1
iface eth1 inet static
address 192.168.50.2
netmask 255.255.255.0
On secondary1:
auto eth1
iface eth1 inet static
address 192.168.50.3
netmask 255.255.255.0
On secondary2:
auto eth1
iface eth1 inet static
address 192.168.50.4
netmask 255.255.255.0
Another file that needs to be set up is /etc/hosts, because we don't have DNS. We need to set the hostnames in /etc/hosts.
On primary:
127.0.0.1 localhost primary
192.168.50.2 primary
192.168.50.3 secondary1
192.168.50.4 secondary2
On secondary1:
127.0.0.1 localhost secondary1
192.168.50.2 primary
192.168.50.3 secondary1
192.168.50.4 secondary2
On secondary2:
127.0.0.1 localhost secondary2
192.168.50.2 primary
192.168.50.3 secondary1
192.168.50.4 secondary2
Check connectivity among themselves by using ping command:
$ ping primary
$ ping secondary1
$ ping secondary2
### Set up a Replica Set ###
After verifying connectivity among VMs, we can go ahead and create the admin user so that we can start working on the Replica Set.
On primary node, open /etc/mongodb.conf, and comment out two lines that start with auth and replSet:
dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongod.log
logappend=true
#auth = true
keyFile=/var/lib/mongodb/keyFile
#replSet=myReplica
Restart mongod daemon.
$ sudo service mongod restart
Create an admin user after conencting to MongoDB:
> use admin
> db.createUser({
user:"admin",
pwd:"
})
$ sudo service mongod restart
Connect to MongoDB and use these commands to add secondary1 and secondary2 to our Replicat Set.
> use admin
> db.auth("admin","myreallyhardpassword")
> rs.initiate()
> rs.add ("secondary1:27017")
> rs.add("secondary2:27017")
Now that we have our Replica Set, we can start working on our project. Consult the [official driver documentation][1] to see how to connect to a Replica Set. In case you want to query from shell, you have to connect to primary instance to insert or query the database. Secondary nodes will not let you do that. If you attempt to access the database on a secondary node, you will get this error message:
myReplica:SECONDARY>
myReplica:SECONDARY> show databases
2015-05-10T03:09:24.131+0000 E QUERY Error: listDatabases failed:{ "note" : "from execCommand", "ok" : 0, "errmsg" : "not master" }
at Error ()
at Mongo.getDBs (src/mongo/shell/mongo.js:47:15)
at shellHelper.show (src/mongo/shell/utils.js:630:33)
at shellHelper (src/mongo/shell/utils.js:524:36)
at (shellhelp2):1:1 at src/mongo/shell/mongo.js:47
I hope you find this tutorial useful. You can use Vagrant to automate your local environments and help you code faster.
--------------------------------------------------------------------------------
via: http://xmodulo.com/setup-replica-set-mongodb.html
作者:[Christopher Valerio][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/valerio
[1]:http://docs.mongodb.org/ecosystem/drivers/

View File

@ -0,0 +1,114 @@
Linux FAQs with Answers--How to block specific user agents on nginx web server
================================================================================
> **Question**: I notice that some robots often visit my nginx-powered website and scan it aggressively, ending up wasting a lot of my web server resources. I am trying to block those robots based on their user-agent string. How can I block specific user agent(s) on nginx web server?
The modern Internet is infested with various malicious robots and crawlers such as malware bots, spambots or content scrapers which are scanning your website in surreptitious ways, for example to detect potential website vulnerabilities, harvest email addresses, or just to steal content from your website. Many of these robots can be identified by their signature "user-agent" string.
As a first line of defense, you could try to block malicious bots from accessing your website by blacklisting their user-agents in robots.txt file. However, unfortunately this works only for "well-behaving" robots which are designed to obey robots.txt. Many malicious bots can simply ignore robots.txt and scan your website at will.
An alternative way to block particular robots is to configure your web server, such that it refuses to serve content to requests with certain user-agent strings. This post explains how to **block certain user-agent on nginx web server**.
### Blacklist Certain User-Agents in Nginx ###
To configure user-agent block list, open the nginx configuration file of your website, where the server section is defined. This file can be found in different places depending on your nginx setup or Linux distribution (e.g., /etc/nginx/nginx.conf, /etc/nginx/sites-enabled/<your-site>, /usr/local/nginx/conf/nginx.conf, /etc/nginx/conf.d/<your-site>).
server {
listen 80 default_server;
server_name xmodulo.com;
root /usr/share/nginx/html;
....
}
Once you open the config file with the server section, add the following if statement(s) somewhere inside the section.
server {
listen 80 default_server;
server_name xmodulo.com;
root /usr/share/nginx/html;
# case sensitive matching
if ($http_user_agent ~ (Antivirx|Arian) {
return 403;
}
# case insensitive matching
if ($http_user_agent ~* (netcrawl|npbot|malicious)) {
return 403;
}
....
}
As you can guess, these if statements match any bad user-string with regular expressions, and return 403 HTTP status code when a match is found. $http_user_agent is a variable that contains the user-agent string of an HTTP request. The '~' operator does case-sensitive matching against user-agent string, while the '~' operator does case-insensitive matching. The '|' operator is logical-OR, so you can put as many user-agent keywords in the if statements, and block them all.
After modifying the configuration file, you must reload nginx to activate the blocking:
$ sudo /path/to/nginx -s reload
You can test user-agent blocking by using wget with "--user-agent" option.
$ wget --user-agent "malicious bot" http://<nginx-ip-address>
![](https://farm6.staticflickr.com/5333/17434036358_ef139a6b59_b.jpg)
### Manage User-Agent Blacklist in Nginx ###
So far, I have shown how to block HTTP requests with a few user-agents in nginx. What if you have many different types of crawling bots to block?
Since the user-agent blacklist can grow very big, it is not a good idea to put them all inside your nginx's server section. Instead, you can create a separate file which lists all blocked user agents. For example, let's create /etc/nginx/useragent.rules, and define a map with all blocked user agents in the following format.
$ sudo vi /etc/nginx/useragent.rules
----------
map $http_user_agent $badagent {
default 0;
~*malicious 1;
~*backdoor 1;
~*netcrawler 1;
~Antivirx 1;
~Arian 1;
~webbandit 1;
}
Similar to the earlier setup, '~*' will match a keyword in case-insensitive manner, while '~' will match a keyword using a case-sensitive regular expression. The line that says "default 0" means that any other user-agent not listed in the file will be allowed.
Next, open an nginx configuration file of your website, which contains http section, and add the following line somewhere inside the http section.
http {
.....
include /etc/nginx/useragent.rules
}
Note that this include statement must appear before the server section (this is why we add it inside http section).
Now open an nginx configuration where your server section is defined, and add the following if statement:
server {
....
if ($badagent) {
return 403;
}
....
}
Finally, reload nginx.
$ sudo /path/to/nginx -s reload
Now any user-agent which contains a keyword listed in /etc/nginx/useragent.rules will be automatically banned by nginx.
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/block-specific-user-agents-nginx-web-server.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni

View File

@ -0,0 +1,45 @@
Linux FAQs with Answers--How to fix “404 Not Found” error with “apt-get update” on old Ubuntu
================================================================================
> **Question**: I have old Ubuntu 13.04 (Raring Ringtail) installation on my PC. When I run "sudo apt-get update" on it, it throws a bunch of "404 Not Found" errors, and I cannot install or update any package using apt-get or aptitude. Due to this error I cannot even upgrade it to a newer release. How can I fix this problem?
![](https://farm6.staticflickr.com/5460/17634085636_996b2a8ab5_b.jpg)
Every Ubuntu release has its end-of-life (EOL) time; regular Ubuntu releases are supported for 18 months, while LTS (Long Term Support) versions are supported up to 3 years (server edition) and 5 years (desktop edition). Once a Ubuntu release has reached EOL, its repositories will no longer be accessible, and you won't get any maintenance updates and security patches from Canonical. As of this writing, Ubuntu 13.04 (Raring Ringtail) has already reached EOL.
If the Ubuntu system you are using is EOL-ed, you will get the following 404 errors from apt-get or aptitude as its repositories have been deprecated.
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/raring-backports/multiverse/binary-i386/Packages 404 Not Found [IP: 91.189.91.13 80]
W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/raring/main/binary-amd64/Packages 404 Not Found
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/raring-security/universe/binary-i386/Packages 404 Not Found [IP: 91.189.88.149 80]
E: Some index files failed to download. They have been ignored, or old ones used instead
For those users who are using old versions of Ubuntu, Canonical maintains old-releases.ubuntu.com, which is an archive of EOL-ed repositories. Thus, when Canonical's support for your Ubuntu installation ends, you need to switch to repositories at old-releases.ubuntu.com (unless you want to upgrade it before EOL).
Here is a quick way to fix "404 Not Found" errors on old Ubuntu by switching to old-releases repositories.
First, replace main/security repositories with old-releases versions as follows.
$ sudo sed -i -r 's/([a-z]{2}\.)?archive.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
$ sudo sed -i -r 's/security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
Then open /etc/apt/sources.list with a text editor, and look for extras.ubuntu.com. This repository is also no longer supported for 13.04. So you need to comment out extras.ubuntu.com by prepending '#' sign.
#deb http://extras.ubuntu.com/ubuntu raring main
#deb-src http://extras.ubuntu.com/ubuntu raring main
Now you should be able to install or update packages on an old unsupported Ubuntu release.
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/404-not-found-error-apt-get-update-ubuntu.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni

View File

@ -0,0 +1,31 @@
Linux FAQs with Answers--How to fix “Encountered a section with no Package: header” error on Raspbian
================================================================================
> **Question**: I installed fresh Rasbian on Raspberry Pi. But when I tried to update APT package index by running sudo apt-get update, it throws the following error:
E: Encountered a section with no Package: header
E: Problem with MergeList /var/lib/dpkg/status
E: The package lists or status file could not be parsed or opened.
> I then cannot install any package on Raspbian. How can I solve this error?
![](https://farm8.staticflickr.com/7704/17445484636_05ba81722f_c.jpg)
The error saying "Problem with MergeList /var/lib/dpkg/status" indicates that the status file got corrupted for some reason, and so cannot be parsed. This status file contains information about installed deb packages, and thus needs to be carefully backed up.
In this case, since this is freshly installed Raspbian, you can safely remove the status file, and re-generate it as follows.
$ sudo rm /var/lib/dpkg/status
$ sudo touch /var/lib/dpkg/status
$ sudo apt-get update
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/encountered-section-with-no-package-header-error.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni

View File

@ -0,0 +1,33 @@
Linux FAQs with Answers--How to fix “fatal error: security/pam_modules.h: No such file or directory”
================================================================================
> **Question**: I was trying to compile a program on [insert your Linux distro], but was getting the following compile error:
>
> "pam_otpw.c:27:34: fatal error: security/pam_modules.h: No such file or directory"
>
> How can I fix this error?
The missing header file 'security/pam_modules.h' is part of development files for libpam, a PAM (Pluggable Authentication Modules) library. Thus to fix this error, you need to install libpam development package, as described below.
On Debian, Ubuntu or Linux Mint:
$ sudo apt-get install libpam0g-dev
On CentOS, Fedora or RHEL:
$ sudo yum install gcc pam-devel
Now verify that the missing header file is installed under /usr/include/security.
![](https://farm8.staticflickr.com/7751/16819069693_fa961f0d40_b.jpg)
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/fatal-error-security-pam-modules.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni

View File

@ -0,0 +1,58 @@
Translating by GOLinux
Linux FAQs with Answers--How to view threads of a process on Linux
================================================================================
> **Question**: My program creates and executes multiple threads in it. How can I monitor individual threads of the program once they are created? I would like to see the details (e.g., CPU/memory usage) of individual threads with their names.
Threads are a popular programming abstraction for parallel execution on modern operating systems. When threads are forked inside a program for multiple flows of execution, these threads share certain resources (e.g., memory address space, open files) among themselves to minimize forking overhead and avoid expensive IPC (inter-process communication) channel. These properties make threads an efficient mechanism for concurrent execution.
In Linux, threads (also called Lightweight Processes (LWP)) created within a program will have the same "thread group ID" as the program's PID. Each thread will then have its own thread ID (TID). To the Linux kernel's scheduler, threads are nothing more than standard processes which happen to share certain resources. Classic command-line tools such as ps or top, which display process-level information by default, can be instructed to display thread-level information.
Here are several ways to **show threads for a process on Linux**.
### Method One: PS ###
In ps command, "-T" option enables thread views. The following command list all threads created by a process with <pid>.
$ ps -T -p <pid>
![](https://farm8.staticflickr.com/7749/17350561110_94cacfc456_c.jpg)
The "SID" column represents thread IDs, and "CMD" column shows thread names.
### Method Two: Top ###
The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.
$ top -H
![](https://farm9.staticflickr.com/8824/17350561070_3dfe447974_c.jpg)
To restrict the top output to a particular process <pid> and check all threads running inside the process:
$ top -H -p <pid>
![](https://farm8.staticflickr.com/7797/17538002751_c8a3d574d8_c.jpg)
### Method Three: Htop ###
A more user-friendly way to view threads per process is via htop, an ncurses-based interactive process viewer. This program allows you to monitor individual threads in tree views.
To enable thread views in htop, launch htop, and press <F2> to enter htop setup menu. Choose "Display option" under "Setup" column, and toggle on "Three view" and "Show custom thread names" options. Presss <F10> to exit the setup.
![](https://farm6.staticflickr.com/5338/17350364568_59bce22e7b_b.jpg)
Now you will see the follow threaded view of individual processes.
![](https://farm9.staticflickr.com/8885/17350560930_98952d5350_c.jpg)
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/view-threads-process-linux.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni

View File

@ -0,0 +1,81 @@
Linux FAQs with Answers--What is the Apache error log location on Linux
================================================================================
> **Question**: I am trying to troubleshoot Apache web server errors on my Linux system. Where is the Apache error log file located on [insert your Linux distro]?
Error log and access log files are a useful piece of information for system admins, for example to troubleshoot their web server, [protect][1] it from various malicious activities, or just to run [various][2] [analytics][3] for HTTP server monitoring. Depending on your web server setup, its error/access logs may be found in different places on your system.
This post may help you **find Apache error log location on Linux**.
![](https://farm8.staticflickr.com/7664/16958522954_4852ab5ea5_c.jpg)
### Apache Error Log Location on Debian, Ubuntu or Linux Mint ###
#### Default Error Log ####
On Debian-based Linux, the system-wide default location of Apache error log is **/var/log/apache2/error.log**. The default location can be customized by editing Apache configuration file.
#### Custom Error Log ####
To find a custom error log location, open /etc/apache2/apache2.conf with a text editor, and look for a line that starts with ErrorLog. This line specifies a custom location of Apache error log file. For example, the unmodified Apache configuration file has the following line:
ErrorLog ${APACHE_LOG_DIR}/error.log
In this case, the location is configured using APACHE_LOG_DIR environment variable, which is defined in /etc/apache2/envvars.
export APACHE_LOG_DIR=/var/log/apache2$SUFFIX
In reality, ErrorLog may point to any arbitrary path on your Linux system.
#### Custom Error Log with VirtualHost ####
If VirtualHost is used in Apache web server, ErrorLog directive can be specified within VirtualHost container, in which case the system-wide error log location described above will be ignored.
With VirtualHost enabled, each VirtualHost can define its own custom error log location. To find out the error log location of a particular VirtualHost, you can open /etc/apache2/sites-enabled/<your-site>.conf, and look for ErrorLog directive, which will show a site-specific error log file.
### Apache Error Log Location on CentOS, Fedora or RHEL ###
#### Default Error Log ####
On Red Hat based Linux, a system-wide Apache error log file is by default placed in **/var/log/httpd/error_log**. This default location can be customized by editing Apache configuration file.
#### Custom Error Log ####
To find out the custom location of Apache error log, open /etc/httpd/conf/httpd.conf with a text editor, and look for ServerRoot, which shows the top of the Apache server directory tree, under which log files and configurations are located. For example:
ServerRoot "/etc/httpd"
Now look for a line that starts with ErrorLog, which indicates where Apache web server is writing its error logs. Note that the specified location is relative to the ServerRoot value. For example:
ErrorLog "log/error_log"
Combine the above two directives to obtain the full path of an error log, which is by default /etc/httpd/logs/error_log. This is a symlink to /var/log/httpd/error_log with freshly installed Apache.
In reality, ErrorLog may point to any arbitrary location on your Linux system.
#### Custom Error Log with VirtualHost ####
If you enabled VirtualHost, you can find the error log location of individual VirtualHosts by checking /etc/httpd/conf/httpd.conf (or any file where VirtualHost is defined). Look for ErrorLog inside individual VirtualHost sections. For example, in the following VirtualHost section, an error log is found in /var/www/xmodulo.com/logs/error_log.
<VirtualHost *:80>
ServerAdmin webmaster@xmodulo.com
DocumentRoot /var/www/xmodulo.com/public_html
ServerName www.xmodulo.com
ServerAlias xmodulo.com
ErrorLog /var/www/xmodulo.com/logs/error_log
CustomLog /var/www/xmodulo.com/logs/access_log
<VirtualHost>
--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/apache-error-log-location-linux.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://ask.xmodulo.com/author/nanni
[1]:http://xmodulo.com/configure-fail2ban-apache-http-server.html
[2]:http://xmodulo.com/interactive-apache-web-server-log-analyzer-linux.html
[3]:http://xmodulo.com/sql-queries-apache-log-files-linux.html

View File

@ -0,0 +1,115 @@
Guake 0.7.0 已发布 - 一个用于Gnome桌面的下拉式终端
================================================================================
Linux的命令行是最好、最强大的东西它使新手着迷并为老手和极客的提供极端强大的功能。那些在服务器和生产环境下工作的人早已认识到了这个事实。有趣的是Linux终端是Linus Torvald在1991年写内核时实现的第一批功能之一。
终端是个强大的工具由于它没有可移动的部分所以十分可靠。终端介于控制台环境和GUI环境之间。终端自身作为一个GUI程序运行在桌面环境下。有许多终端是适用于特定的桌面环境的而其余是通用的。Terminator, Konsole, Gnome-Terminal, Terminology, XFCE terminal, xterm都是些常用的终端模拟器。
您可以从下面的链接中获得一份使用最广泛的终端模拟器的列表。
- [20 Useful Terminals for Linux][1]
前几日上网时我偶遇了名为Guake它是用于gnome的终端模拟器。尽管这并不是我第一次听到Guake。实际上我在大约一年前便知道了这个应用程序但不知怎么搞的我那时没有写写Guake再后来我便渐渐忘掉了Guake直到我再一次听到Guake。所以最终这篇文章诞生了。我将给你讲讲Guake的功能在Debian、Ubuntu、Fedora上的安装过程以及一些测试。
#### 什么是Guake ####
Guake是应用于Gnome环境的下拉式终端。主要由Python编写使用了一些C它以GPL2+证书发布适用于Linux以及类似的系统。Guake的灵感来源于电脑游戏Quake雷神之锤的终端Quake的终端能通过按下特定按键默认为F12从屏幕上滑下来并在按下同样的键后滑上去。
值得注意的是Guake并不是第一个这样的应用。YakuakeYet Another Kuake是一个运行于KDE的终端模拟器Tilda是一个用GTK+写成的终端模拟器。它们的灵感都来自于雷神之锤那上下滑动的终端。
#### Guake的功能 ####
- 轻量级
- 简单而优雅
- 众多功能
- 强大的
- 好看的
- 平滑的集成于GUI
- 在按下预定义的键后出现/消失
- 支持热键、标签、透明化背景这使得它适合所有Gnome用户
- 极端地可配置
- 包括许多颜色的调色板
- 设定透明度的快捷方式
- 通过Guake配置可在启动时运行一个脚本
- 可以在多个监视器上运行
Guake 0.7.0最近发布,它带来了一些修正以及上面提到的一些功能。完整的版本历史和源代码包可以在[这里][2]找到。
### 在Linux中安装Guake终端 ###
如果您对从源码编译Guake感兴趣您可以从上面的链接处下载Guake并在安装前进行编译。
然而Guake可以在许多的发行版中通过添加额外的仓库来安装。这里我们将在Debian、Ubuntu、Linux Mint和Fedora下安装Guake。
首先从仓库获取最新的软件包列表并从默认的仓库安装Guake如下所示
---------------- On Debian, Ubuntu and Linux Mint ----------------
$ sudo apt-get update
$ apt-get install guake
----------
---------------- On Fedora 19 Onwards ----------------
# yum update
# yum install guake
安装后可以从另一个终端中启动Guake
$ guake
在启动它后便可以在Gnome桌面中使用F12默认配置来下滑、上滑终端。
看起来非常漂亮,尤其是透明背景。滑下来...滑上去...滑下来...滑上去...执行命令,打开另一个标签,执行命令,滑上去...滑下来...(作者已沉迷其中)
![Guake Terminal in Action](http://www.tecmint.com/wp-content/uploads/2015/05/Guake.png)
Guake实战
如果您的壁纸或活动窗口的颜色和Guake的颜色有些不搭。您可以改变您的壁纸减少透明度或者改变Guake的颜色。
下一步便是进入Guake的配置根据每个人的需求修改设置。可以通过应用菜单或者下面的命令来运行Guake的配置。
$ guake --preferences
![Guake Terminal Properties](http://www.tecmint.com/wp-content/uploads/2015/05/Guake-Properties.png)
Guake终端配置
滚动配置
![Guake Scrolling Settings](http://www.tecmint.com/wp-content/uploads/2015/05/Guake-Scrolling.png)
Guake滚动配置
外观设置 - 在这里您可以修改文字颜色和背景色以及透明度。
![Appearance Properties](http://www.tecmint.com/wp-content/uploads/2015/05/Appearance-Properties.png)
外观设置
键盘快捷键 - 在这里您可以修改Guake显示的开关快捷键。
![Keyboard Shortcuts](http://www.tecmint.com/wp-content/uploads/2015/05/Keyboard-Shortcuts.png)
键盘快捷键
兼容性设置 - 基本上不必设置它。
![Compatibility Setting](http://www.tecmint.com/wp-content/uploads/2015/05/Compatibility-Setting.png)
兼容性设置
### 结论 ###
这个项目即不是太年轻也不是太古老因此它已经达到了一定的成熟度足够可靠可以开箱即用。像我这样需要在GUI和终端间频繁切换的人来说Guake是一个福利。我不需要管理一个多余的窗口频繁的打开和关闭使用tab在大量打开的应用程序中寻找终端或切换到不同的工作区来管理终端现在我需要的只有F12。
我认为对任何同时使用GUI和终端的Linux用户来说Guake都是必须的工具。同样的我会向任何想要在系统中结合使用GUI和终端的人推荐它因为它既平滑又没有任何障碍。
上面就是我要说的全部了。如果在安装和使用时有任何问题请告诉我我们会帮助您。也请您告诉我您使用Guake的经验。在下面的评论区反馈您宝贵的经验。点赞和分享以帮助我们宣传。
--------------------------------------------------------------------------------
via: http://www.tecmint.com/install-guake-terminal-ubuntu-mint-fedora/
作者:[Avishek Kumar][a]
译者:[wwy-hust](https://github.com/wwy-hust)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.tecmint.com/author/avishek/
[1]:http://www.tecmint.com/linux-terminal-emulators/
[2]:https://github.com/Guake/guake/releases/tag/0.7.0

View File

@ -0,0 +1,73 @@
如何在Linux下创建一个不可变更的文件
================================================================================
假如你想对Linux中的一些重要文件做写保护这样它们就不能被删除或者被篡改成之前的版本或者其他东西。或者在其他情况你可能想避免某些配置文件被软件自动修改。使用`chown`和`chmod`命令修改文件的归属关系或者权限位是处理这种情况的一个解决方法但这并不完美因为这样无法避免有root权限的操作。这时`chattr`就派上用场了。
`chattr`是一个可以设置或取消文件的标志位的Linux命令它和标准的文件权限读、写、执行是分离的。与此相关的另一个命令是`lsattr`它可以显示文件的哪些标志位被设置上了。最初只有EXT文件系统EXT2/3/4支持`chattr`和`lsattr`所管理的标志位但现在很多其他的本地Linux文件系统都支持了比如XFS、Btrfs、ReiserFS等等。
在这个教程中,我会示范如果使用`chattr`来让Linux中的文件不可变更。
`chattr`和`lsattr`命令是e2fsprogs包的一部分它在所有现代Linux发行版都预装了。
下面是`chattr`的基本语法。
$ chattr [-RVf] [操作符][标志位] 文件...
其中操作符可以是“+”(把选定的标志位添加到标志位列表)、“-”(从标志位列表中移除选定的标志位)、或者“=”(强制使用选定的标志位)。
下面是一些可用的标志位。
- **a**: 只能以追加模式打开。
- **A**: 不能更新atime文件访问时间
- **c**: 当被写入磁盘时被自动压缩。
- **C**: 关掉“写时复制”。
- **i**: 不可变更。
- **s**: 通过自动归零来安全删除。译注一般情况文件被删后内容不会被修改改标志位会使得文件被删后原有内容被0取代
### “不可变更”标志位 ###
为了让一个文件不可变更,你需要按照如下方法为这个文件添加“不可变更”标志位。例如,对/etc/passwd文件做写保护
$ sudo chattr +i /etc/passwd
注意设置或取消一个文件的“不可变更”标志位是需要根用户权限的。现在检查该文件“不可变更”标志位是否被添加上了。
$ lsattr /etc/passwd
一旦文件被设置为不可变更,任何用户都将无法修改该文件。即使是根用户也不可以修改、删除、覆盖、移动或者重命名这个文件。如果你想再次修改这个文件,需要先把“不可变更”标志位取消了。
用如下命令取消“不可变更”标志位:
$ sudo chattr -i /etc/passwd
![](https://farm9.staticflickr.com/8613/16152651317_076a65cf50_b.jpg)
如果你想让一个目录(比如/etc连同它下边的所有内容不可变更使用“-R”选项
$ sudo chattr -R +i /etc
### “只可追加”标志位 ###
另一个有用的的标志位是“只可追加”,它只允许文件内容被追加的方式修改。你不能覆盖或者删除一个设置了“只可追加”标志位的文件。这个标志位在你想避免日志文件被意外清理掉的情况很有用。
和“不可变更”标志位类似,你可以使用如下命令让文件变成“只可追加”模式:
$ sudo chattr +a /var/log/syslog
注意当你复制一个“不可变更”或者“只可追加”的文件到其他地方后,新文件不会保留这些标志位。
### 结论 ###
在这个教程中,我展示了如何使用`chattr`和`lsattr`命令来管理额外的文件标志位,来避免文件被篡改(意外或者其他情况)的方法。注意你不能将`chattr`作为一个安全措施,因为“不可变更”标志位可以很容易被取消掉。解决这个问题的一个可能的方式是限制`chattr`命令自身的可用性或者剥夺CAP_LINUX_IMMUTABLE内核权能标志。关于`chattr`以及可用的标志位的更多细节请参考它的man手册。
--------------------------------------------------------------------------------
via: http://xmodulo.com/make-file-immutable-linux.html
作者:[Dan Nanni][a]
译者:[goreliu](https://github.com/goreliu)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/nanni

View File

@ -1,171 +1,172 @@
Inxi: Find System And Hardware Information On Linux
================================================================================
We already have shown different [applications][1] and ways to find the system and hardware information on Linux. In that series, today we will see how to find such details using **inxi**. It can be used for forum technical support, as a debugging tool, to quickly ascertain user system configuration and hardware.
**Inxi** is a command line tool that can be used to find the complete system and hardware details such as;
- Hardware,
- CPU,
- Drivers,
- Xorg,
- Desktop,
- Kernel,
- GCC version,
- Processes,
- RAM usage,
- and other useful information.
### Installation ###
Inxi is available in the default repositories of most modern GNU/Linux operating systems. So, we can simply install it by running the following commands.
**On Debian based system:**
sudo apt-get install inxi
**On Fedora:**
sudo yum install inxi
**On RHEL based systems:**
Install EPEL repository:
sudo yum install epel-release
Then, install inxi using command:
sudo yum install inxi
### Usage ###
To find the quick view of the system information, run the following command from Terminal.
inxi
**Sample output:**
CPU~Dual core Intel Core i3-2350M CPU (-HT-MCP-) clocked at Min:800.000Mhz Max:1200.000Mhz Kernel~3.13.0-45-generic x86_64 Up~6:41 Mem~1537.7/3861.3MB HDD~500.1GB(52.5% used) Procs~183 Client~Shell inxi~1.9.17
Ofcourse, we can retrieve a particular hardware details. For example to retrieve the **Audio/Sound hardware details**, run the following command:
inxi -A
**Sample output:**
Audio: Card: Intel 6 Series/C200 Series Family High Definition Audio Controller driver: snd_hda_intel
Sound: Advanced Linux Sound Architecture ver: k3.13.0-45-generic
Cool, isnt it?
Likewise, you can retrieve the details of **Graphic card** information.
inxi -G
**Sample output:**
Graphics: Card: Intel 2nd Generation Core Processor Family Integrated Graphics Controller
X.Org: 1.15.1 drivers: intel (unloaded: fbdev,vesa) Resolution: 1366x768@60.0hz
GLX Renderer: Mesa DRI Intel Sandybridge Mobile GLX Version: 3.0 Mesa 10.3.0
What about harddisk information? Thats also possible. To view the full **harddisk** information, run the following command.
inxi -D
**Sample Output:**
Drives: HDD Total Size: 500.1GB (52.5% used) 1: id: /dev/sda model: ST9601325BD size: 500.1GB
To display the Bios and Motherboard details:
inxi -M
**Sample output:**
Machine: System: Dell (portable) product: Inspiron N5050
Mobo: Dell model: 01HXXJ version: A05 Bios: Dell version: A05 date: 08/03/2012
Not only hardware details, it can also displays the **list of available repositories** in our system.
inxi -r
**Sample output:**
Repos: Active apt sources in file: /etc/apt/sources.list
deb http://ubuntu.excellmedia.net/archive/ trusty main restricted
deb-src http://ubuntu.excellmedia.net/archive/ trusty main restricted
deb http://ubuntu.excellmedia.net/archive/ trusty-updates main restricted
deb-src http://ubuntu.excellmedia.net/archive/ trusty-updates main restricted
deb http://ubuntu.excellmedia.net/archive/ trusty universe
.
.
Active apt sources in file: /etc/apt/sources.list.d/intellinuxgraphics.list
deb https://download.01.org/gfx/ubuntu/14.04/main trusty main #Intel Graphics drivers
Active apt sources in file: /etc/apt/sources.list.d/linrunner-tlp-trusty.list
Active apt sources in file: /etc/apt/sources.list.d/wseverin-ppa-trusty.list
deb http://ppa.launchpad.net/wseverin/ppa/ubuntu trusty main
Inxi will also display the Weather details of your location. Surprised? Yes, It should.
inxi -W Erode,Tamilnadu
Here **Erode** is the District and **Tamilnadu** is a state in India.
Sample output:
Weather: Conditions: 79 F (26 C) - Clear Time: February 4, 6:00 PM IST
### Viewing Complete Hardware details ###
Tired of finding each hardware details? Well, you can list all details at once using command:
inxi -F
**Sample output:**
System: Host: sk Kernel: 3.13.0-45-generic x86_64 (64 bit) Desktop: LXDE (Openbox 3.5.2) Distro: Ubuntu 14.04 trusty
Machine: System: Dell (portable) product: Inspiron N5050
Mobo: Dell model: 01HXXJ version: A05 Bios: Dell version: A05 date: 08/03/2012
CPU: Dual core Intel Core i3-2350M CPU (-HT-MCP-) cache: 3072 KB flags: (lm nx sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx)
Clock Speeds: 1: 800.00 MHz 2: 1000.00 MHz 3: 800.00 MHz 4: 800.00 MHz
Graphics: Card: Intel 2nd Generation Core Processor Family Integrated Graphics Controller
X.Org: 1.15.1 drivers: intel (unloaded: fbdev,vesa) Resolution: 1366x768@60.0hz
GLX Renderer: Mesa DRI Intel Sandybridge Mobile GLX Version: 3.0 Mesa 10.3.0
Audio: Card: Intel 6 Series/C200 Series Family High Definition Audio Controller driver: snd_hda_intel
Sound: Advanced Linux Sound Architecture ver: k3.13.0-45-generic
Network: Card-1: Qualcomm Atheros AR9285 Wireless Network Adapter (PCI-Express) driver: ath9k
IF: wlan0 state: up mac:
Card-2: Realtek RTL8101E/RTL8102E PCI Express Fast Ethernet controller driver: r8169
IF: eth0 state: down mac:
Drives: HDD Total Size: 500.1GB (52.5% used) 1: id: /dev/sda model: ST9500325AS size: 500.1GB
Partition: ID: / size: 455G used: 245G (57%) fs: ext4 ID: /boot size: 236M used: 159M (72%) fs: ext2
ID: swap-1 size: 4.19GB used: 0.00GB (0%) fs: swap
RAID: No RAID devices detected - /proc/mdstat and md_mod kernel raid module present
Sensors: System Temperatures: cpu: 64.5C mobo: N/A
Fan Speeds (in rpm): cpu: N/A
Info: Processes: 186 Uptime: 6:52 Memory: 1547.2/3861.3MB Client: Shell (bash) inxi: 1.9.17
As you see in the above, inxi displays the complete hardware details.
For more details, refer the man pages.
man inxi
### Conclusion ###
Are you searching for a simple tool which displays your complete system and hardware details? Then, dont look anywhere, inxi will give you what actually want. And, it is light weight tool available in your default repositories. What else you want more? Give it a try, you wont be disappointed.
Cheers!
--------------------------------------------------------------------------------
via: http://www.unixmen.com/inxi-find-system-hardware-information-linux/
作者:[SK][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://www.unixmen.com/author/sk/
[1]:http://www.unixmen.com/screenfetch-bash-screenshot-information-tool/
Inxi——获取Linux的系统和硬件信息
================================================================================
我们已经展示了一些不同的[应用程序][1]和方法来获取Linux的系统和硬件信息。在这一系列我们将看到如何使用**inxi**来获取这些详情信息。在论坛技术支持中,它可以作为调试工具,迅速确定用户的系统配置和硬件信息。
**Inxi**是一个可以获取完整的系统和硬件详情信息的命令行工具,内容包括:
- 硬件
- CPU
- 磁盘驱动器
- Xorg
- 桌面环境
- 内核
- GCC版本
- 进程
- 内存占用
- 和其他有用的信息
### 安装方法 ###
Inxi在多数现代GNU/Linux操作系统的默认软件仓库中。所以我们可以简单地运行下列命令安装。
**在基于Debian的发行版**
sudo apt-get install inxi
**在Fedora**
sudo yum install inxi
**在基于RHEL的发行版**
安装EPEL软件仓库
sudo yum install epel-release
然后使用如下命令安装inxi
sudo yum install inxi
### 使用方法 ###
在终端运行如下命令可以获取系统的概况信息。
inxi
**示例输出:**
CPU~Dual core Intel Core i3-2350M CPU (-HT-MCP-) clocked at Min:800.000Mhz Max:1200.000Mhz Kernel~3.13.0-45-generic x86_64 Up~6:41 Mem~1537.7/3861.3MB HDD~500.1GB(52.5% used) Procs~183 Client~Shell inxi~1.9.17
当然,我们可以获取一个特定硬件的详情信息。比如获取**声音/音频硬件详情信息**,可以运行如下命令:
inxi -A
**示例输出:**
Audio: Card: Intel 6 Series/C200 Series Family High Definition Audio Controller driver: snd_hda_intel
Sound: Advanced Linux Sound Architecture ver: k3.13.0-45-generic
很酷是吧?
同样的,你可以获取**显卡**的详情信息。
inxi -G
**示例输出:**
Graphics: Card: Intel 2nd Generation Core Processor Family Integrated Graphics Controller
X.Org: 1.15.1 drivers: intel (unloaded: fbdev,vesa) Resolution: 1366x768@60.0hz
GLX Renderer: Mesa DRI Intel Sandybridge Mobile GLX Version: 3.0 Mesa 10.3.0
硬盘信息呢?也是可以的。运行如下命令来获取完整的**硬盘**信息。
inxi -D
**示例输出:**
Drives: HDD Total Size: 500.1GB (52.5% used) 1: id: /dev/sda model: ST9601325BD size: 500.1GB
显示Bios和主板详情信息
inxi -M
**示例输出:**
Machine: System: Dell (portable) product: Inspiron N5050
Mobo: Dell model: 01HXXJ version: A05 Bios: Dell version: A05 date: 08/03/2012
不只有硬性详情信息,它也可以显示我们系统中的**可用软件仓库列表**。
inxi -r
**示例输出:**
Repos: Active apt sources in file: /etc/apt/sources.list
deb http://ubuntu.excellmedia.net/archive/ trusty main restricted
deb-src http://ubuntu.excellmedia.net/archive/ trusty main restricted
deb http://ubuntu.excellmedia.net/archive/ trusty-updates main restricted
deb-src http://ubuntu.excellmedia.net/archive/ trusty-updates main restricted
deb http://ubuntu.excellmedia.net/archive/ trusty universe
.
.
Active apt sources in file: /etc/apt/sources.list.d/intellinuxgraphics.list
deb https://download.01.org/gfx/ubuntu/14.04/main trusty main #Intel Graphics drivers
Active apt sources in file: /etc/apt/sources.list.d/linrunner-tlp-trusty.list
Active apt sources in file: /etc/apt/sources.list.d/wseverin-ppa-trusty.list
deb http://ppa.launchpad.net/wseverin/ppa/ubuntu trusty main
Inxi还可以显示你所在位置的天气信息。感到意外吗是的它可以。
inxi -W Erode,Tamilnadu
这里**Erode**是区,**Tamilnadu**是印度的一个邦。
示例输出:
Weather: Conditions: 79 F (26 C) - Clear Time: February 4, 6:00 PM IST
### 查看完整的硬件详情信息 ###
厌倦了获取每种硬件的信息?你可以使用如下命令将所有信息一次列出:
inxi -F
**示例输出:**
System: Host: sk Kernel: 3.13.0-45-generic x86_64 (64 bit) Desktop: LXDE (Openbox 3.5.2) Distro: Ubuntu 14.04 trusty
Machine: System: Dell (portable) product: Inspiron N5050
Mobo: Dell model: 01HXXJ version: A05 Bios: Dell version: A05 date: 08/03/2012
CPU: Dual core Intel Core i3-2350M CPU (-HT-MCP-) cache: 3072 KB flags: (lm nx sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx)
Clock Speeds: 1: 800.00 MHz 2: 1000.00 MHz 3: 800.00 MHz 4: 800.00 MHz
Graphics: Card: Intel 2nd Generation Core Processor Family Integrated Graphics Controller
X.Org: 1.15.1 drivers: intel (unloaded: fbdev,vesa) Resolution: 1366x768@60.0hz
GLX Renderer: Mesa DRI Intel Sandybridge Mobile GLX Version: 3.0 Mesa 10.3.0
Audio: Card: Intel 6 Series/C200 Series Family High Definition Audio Controller driver: snd_hda_intel
Sound: Advanced Linux Sound Architecture ver: k3.13.0-45-generic
Network: Card-1: Qualcomm Atheros AR9285 Wireless Network Adapter (PCI-Express) driver: ath9k
IF: wlan0 state: up mac:
Card-2: Realtek RTL8101E/RTL8102E PCI Express Fast Ethernet controller driver: r8169
IF: eth0 state: down mac:
Drives: HDD Total Size: 500.1GB (52.5% used) 1: id: /dev/sda model: ST9500325AS size: 500.1GB
Partition: ID: / size: 455G used: 245G (57%) fs: ext4 ID: /boot size: 236M used: 159M (72%) fs: ext2
ID: swap-1 size: 4.19GB used: 0.00GB (0%) fs: swap
RAID: No RAID devices detected - /proc/mdstat and md_mod kernel raid module present
Sensors: System Temperatures: cpu: 64.5C mobo: N/A
Fan Speeds (in rpm): cpu: N/A
Info: Processes: 186 Uptime: 6:52 Memory: 1547.2/3861.3MB Client: Shell (bash) inxi: 1.9.17
就像上面你看到的那样inxi显示出了完整的硬件详情信息。
更多的细节可以参考man手册。
man inxi
### 结论 ###
你在寻找一个可以显示完整的系统和硬件详情信息的简单工具吗那么不用再找了inxi会提供你所需要的。并且它还是在你系统默认的软件仓库中的轻量级工具。你还想要更多东西吗试一试它你不会失望。
欢呼吧!
--------------------------------------------------------------------------------
via: http://www.unixmen.com/inxi-find-system-hardware-information-linux/
作者:[SK][a]
译者:[goreliu](https://github.com/goreliu)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://www.unixmen.com/author/sk/
[1]:http://www.unixmen.com/screenfetch-bash-screenshot-information-tool/

View File

@ -0,0 +1,63 @@
zBackup——一个通用的重复数据备份工具
================================================================================
zbackup是一个基于rsync思想的全局重复数据备份工具。给它传入一个大的tar文件后它会存储该文件的重复区域仅进行一次然后对结果进行压缩并根据参数确定是否对其加密。传入另一个tar文件后它会从之前的已备份文件中复用重复的数据。只有新的改动会被保存并且只要文件变动不是很大需要的存储空间非常少。任何时候之前的已备份文件都可以被完整地读出来。
### zBackup特性 ###
- 使用并行的LZMA或者LZO压缩算法压缩已备份数据
- 使用内置的AES加密算法加密已备份数据
- 可以删除旧的已备份数据
- 使用一个64位滚动哈希保持软碰撞数量为0
- 已备份数据由不可更改的文件组成。任何现有文件都没有被更改过
- 使用C++语言编写,并且只有适量的依赖库
- 可以在生产环境安全使用
- 可以在不同备份库中交换数据而无需重新压缩
### 在ubuntu中安装zBackup ###
打开终端并运行如下命令:
sudo apt-get install zbackup
### 使用zBackup ###
`zbackup init`命令会初始化一个备份库,用来存放待备份的数据。
zbackup init [--non-encrypted] [--password-file ~/.my_backup_password ] /my/backup/repo
`zbackup backup`命令备份一个由`tar c`创建的tar文件到刚才使用`zbackup init`初始化的备份库。译注实际使用时类似这样tar c files | zbackup ...
zbackup [--password-file ~/.my_backup_password ] [--threads number_of_threads ] backup /my/backup/repo/backups/backup-`date +%Y-%m-%d'`
`zbackup restore`命令从备份库中恢复一个已备份文件到tar文件中。
zbackup [--password-file ~/.my_backup_password ] [--cache-size cache_size_in_mb ] restore /my/backup/repo/backups/backup-`date +%Y-%m-%d'` > /my/precious/backup-restored.tar
### 可用选项 ###
- -non-encrypted -- 不加密备份库。
- --password-file ~/.my_backup_password -- 使用位于~/.my_backup_password的口令文件来加密备份库和待备份文件以及解密已备份文件。
- --threads number_of_threads -- 限制并行LZMA压缩的线程数到number_of_threads。建议在32位的系统平台使用。
- --cache-size cache_size_in_mb -- 使用cache_size_in_mb中的缓存大小来加速恢复文件的过程。
### zBackup相关文件 ###
~/.my_backup_password 用来加密备份库和待备份文件以及解密已备份文件。更多细节见zbackup。
/my/backup/repo 存放备份库的目录。
/my/precious/restored-tar 用来恢复已备份文件的tar文件。
/my/backup/repo/backups/backup-`date +%Y-%m-%d'` 指定的之前已备份文件的文件名。
--------------------------------------------------------------------------------
via: http://www.ubuntugeek.com/zbackup-a-versatile-deduplicating-backup-tool.html
作者:[ruchi][a]
译者:[goreliu](https://github.com/goreliu)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://www.ubuntugeek.com/author/ubuntufix

View File

@ -0,0 +1,399 @@
70 个可能的 Shell 脚本面试问题及解答
================================================================================
我们为你的面试准备选择了 70 个可能的 shell 脚面问题及解答。了解脚本或至少知道基础知识对系统管理员来说至关重要,它也有助于你在工作环境中自动完成很多任务。在过去的几年里,我们注意到所有的 linux 工作职位都要求脚本技能。
### 1) 如何向脚本传递参数 ? ###
./script argument
**例子** : 显示文件名称脚本
./show.sh file1.txt
cat show.sh
#!/bin/bash
cat $1
### 2) 如何在脚本中使用参数 ? ###
第一个参数: $1,
第二个参数 : $2
例子 : 脚本会复制文件(arg1) 到目标地址(arg2)
./copy.sh file1.txt /tmp/
cat copy.sh
#!/bin/bash
cp $1 $2
### 3) 如何计算传递进来的参数 ? ###
$#
### 4) 如何在脚本中获取脚本名称 ? ###
$0
### 5) 如何检查之前的命令是否运行成功 ? ###
$?
### 6) 如何获取文件的最后一行 ? ###
tail -1
### 7) 如何获取文件的第一行 ? ###
head -1
### 8) 如何获取一个文件每一行的第三个元素 ? ###
awk '{print $3}'
### 9) 假如第一个等于 FIND如何获取文件中每行的第二个元素 ###
awk '{ if ($1 == "FIND") print $2}'
### 10) 如何调试 bash 脚本 ###
Add -xv to #!/bin/bash
例子
#!/bin/bash xv
### 11) 举例如何写一个函数 ? ###
function example {
echo "Hello world!"
}
### 12) 如何向 string 添加 string ? ###
V1="Hello"
V2="World"
V3=$V1+$V2
echo $V3
Output
Hello+World
### 13) 如何进行两个整数相加 ? ###
V1=1
V2=2
V3=$V1+$V2
echo $V3
Output
3
### 14) 如何检查文件系统中是否存在某个文件 ? ###
if [ -f /var/log/messages ]
then
echo "File exists"
fi
### 15) 写出 shell 脚本中所有循环语法 ? ###
#### for loop : ####
for i in $( ls ); do
echo item: $i
done
#### while loop : ####
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
#### untill oop : ####
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
### 16) 每个脚本开始的 #!/bin/sh 或 #!/bin/bash 表示什么意思 ? ###
这一行说明要使用的 shell。#!/bin/bash 表示脚本使用 /bin/bash。对于 python 脚本,就是 #!/usr/bin/python
### 17) 如何获取文本文件的第 10 行 ? ###
head -10 file|tail -1
### 18) bash 脚本文件的第一个符号是什么 ###
#
### 19) 命令:[ -z "" ] && echo 0 || echo 1 的输出是什么 ###
0
### 20) 命令 “export” 有什么用 ? ###
使变量在子 shell 中公有
### 21) 如何在后台运行脚本 ? ###
在脚本后面添加 “&
### 22) "chmod 500 script" 做什么 ? ###
使脚本所有者拥有可执行权限
### 23) ">" 做什么 ? ###
重定向输出流到文件或另一个流。
### 24) &&& 有什么区别 ###
& - 希望脚本在后台运行的时候使用它
&& - 当第一个脚本成功完成才执行命令/脚本的时候使用它
### 25) 什么时候要在 [ condition ] 之前使用 “if” ? ###
当条件满足时需要运行多条命令的时候。
### 26) 命令: name=John && echo 'My name is $name' 的输出是什么 ###
My name is $name
### 27) bash shell 脚本中哪个符号用于注释 ? ###
#
### 28) 命令: echo ${new:-variable} 的输出是什么 ###
variable
### 29) ' 和 " 引号有什么区别 ? ###
' - 当我们不希望把变量转换为值的时候使用它。
" - 会计算所有变量的值并用值代替。
### 30) 如何在脚本文件中重定向标准输入输出流到 log.txt 文件 ? ###
在脚本文件中添加 "exec >log.txt 2>&1" 命令
### 31) 如何只用 echo 命令获取 string 变量的一部分 ? ###
echo ${variable:x:y}
x - 起始位置
y - 长度
例子:
variable="My name is Petras, and I am developer."
echo ${variable:11:6} # 会显示 Petras
### 32) 如果给定字符串 variable="User:123:321:/home/dir" 如何只用 echo 命令获取 home_dir ? ###
echo ${variable#*:*:*:}
echo ${variable##*:}
### 33) 如何从上面的字符串中获取 “User” ? ###
echo ${variable%:*:*:*}
echo ${variable%%:*}
### 34) 如何使用 awk 列出 UID 小于 100 的用户 ? ###
awk -F: '$3<100' /etc/passwd
### 35) 写程序为用户计算主组数目并显示次数和组名 ###
cat /etc/passwd|cut -d: -f4|sort|uniq -c|while read c g
do
{ echo $c; grep :$g: /etc/group|cut -d: -f1;}|xargs -n 2
done
### 36) 如何在 bash shell 中更改标注域分隔符为 ":" ? ###
IFS=":"
### 37) 如何获取变量长度 ? ###
${#variable}
### 38) 如何打印变量的最后 5 个字符 ? ###
echo ${variable: -5}
### 39) ${variable:-10} 和 ${variable: -10} 有什么区别? ###
${variable:-10} - 如果之前没有给 variable 赋值则输出 10
${variable: -10} - 输出 variable 的最后 10 个字符
### 40) 如何只用 echo 命令替换字符串的一部分 ? ###
echo ${variable//pattern/replacement}
### 41) 哪个命令将命令替换为大写 ? ###
tr '[:lower:]' '[:upper:]'
### 42) 如何计算本地用户数目 ? ###
wc -l /etc/passwd|cut -d" " -f1
或者
cat /etc/passwd|wc -l
### 43) 不用 wc 命令如何计算字符串中的单词数目 ? ###
set ${string}
echo $#
### 44) "export $variable" 或 "export variable" 哪个正确 ? ###
export variable
### 45) 如何列出第二个字母是 a 或 b 的文件 ? ###
ls -d ?[ab]*
### 46) 如何将整数 a 加到 b 并赋值给 c ? ###
c=$((a+b))
c=`expr $a + $b`
c=`echo "$a+$b"|bc`
### 47) 如何去除字符串中的所有空格 ? ###
echo $string|tr -d " "
### 48) 重写命令输出变量转换为复数的句子: item="car"; echo "I like $item" ? ###
item="car"; echo "I like ${item}s"
### 49) 写出输出数字 0 到 100 中 3 的倍数(0 3 6 9 …)的命令 ? ###
for i in {0..100..3}; do echo $i; done
for (( i=0; i<=100; i=i+3 )); do echo "Welcome $i times"; done
### 50) 如何打印传递给脚本的所有参数 ? ###
echo $*
echo $@
### 51) [ $a == $b ] 和 [ $a -eq $b ] 有什么区别 ###
[ $a == $b ] - 用于字符串比较
[ $a -eq $b ] - 用于数字比较
### 52) = 和 == 有什么区别 ###
= - 用于为变量复制
== - 用于字符串比较
### 53) 写出测试 $a 是否大于 12 的命令 ? ###
[ $a -gt 12 ]
### 54) 写出测试 $b 是否小于等于 12 的命令 ? ###
[ $b -le 12 ]
### 55) 如何检查字符串是否以字母 "abc" 开头 ? ###
[[ $string == abc* ]]
### 56) [[ $string == abc* ]] 和 [[ $string == "abc*" ]] 有什么区别 ###
[[ $string == abc* ]] - 检查字符串是否以字母 abc 开头
[[ $string == "abc* " ]] - 检查字符串是否完全等于 abc*
### 57) 如何列出以 ab 或 xy 开头的用户名 ? ###
egrep "^ab|^xy" /etc/passwd|cut -d: -f1
### 58) bash 中 $! 表示什么意思 ? ###
后台最近命令的 PID
### 59) $? 表示什么意思 ? ###
前台最近命令的结束状态
### 60) 如何输出当前 shell 的 PID ? ###
echo $$
### 61) 如何获取传递给脚本的参数数目 ? ###
echo $#
### 62) $* 和 $@ 有什么区别 ###
$* - 以一个字符串形式输出所有传递到脚本的参数
$@ - 以 $IFS 为分隔符列出所有传递到脚本中的参数
### 63) 如何在 bash 中定义数组 ? ###
array=("Hi" "my" "name" "is")
### 64) 如何打印数组的第一个元素 ? ###
echo ${array[0]}
### 65) 如何打印数组的所有元素 ? ###
echo ${array[@]}
### 66) 如何输出所有数组索引 ? ###
echo ${!array[@]}
### 67) 如何移除数组中索引为 2 的元素 ? ###
unset array[2]
### 68) 如何在数组中添加 id 为 333 的元素 ? ###
array[333]="New_element"
### 69) shell 脚本如何获取输入的值 ? ###
a) 通过参数
./script param1 param2
b) 通过 read 命令
read -p "Destination backup Server : " desthost
### 70) 在脚本中如何使用 "expect" ? ###
/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect "*?assword:*"
send "${password}\r"
expect eof
EOD
好运 !! 如果你有任何疑问或者问题需要解答都可以在下面的评论框中写下来。让我们知道这对你的面试有所帮助:-)
--------------------------------------------------------------------------------
via: http://linoxide.com/linux-shell-script/shell-scripting-interview-questions-answers/
作者:[Petras Liumparas][a]
译者:[ictlyh](https://github.com/ictlyh)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://linoxide.com/author/petrasl/