Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

linux_Commads

0 views

Published on

this is document very useful for linux new user.

Published in: Education
  • Be the first to comment

  • Be the first to like this

linux_Commads

  1. 1. commands:----------------------------------------------------------------------------------------------------------------------------ref: http://www.devside.net/articles/linux/sysadminhttp://linux.die.net/abs-guide/system.htmlhttp://www.linuxtraining.co.uk/download/new_linux_course_modules.pdfhttp://www.omnisecu.com/gnu-linux/index.htmhttp://www.comptechdoc.org/os/linux/usersguide/linux_ugusers.html----------------------------------------------------------------------------------------------------------------------------Syntax:#command option argumentoption : single letter preceded by - [ex. -a, -x etc ] and full word preceded by -- [ex --help etc ]argument : it is name of fileArguments in [] are optionalArguments in CAPS or <> are variablesText followed by ... represents a listx|y|z means "x or y or z" -abc means "any mix of -a, -b or -c"[multiple command seperated by ; semicolon ]----------------------------------------------------------------------------------------------------------------------------command terminal :=> wildcard :? : match single charactor* : match zero or more[0-9] : match range[abc] : match any of abc[^abc] : match except abc=> use tab to complete argument , command=> Command Editing Tricks● Ctrl-a moves to beginning of line● Ctrl-e moves to end of line● Ctrl-u deletes to beginning of line● Ctrl-k deletes to end of line● Ctrl-arrow moves left or right by word
  2. 2. ----------------------------------------------------------------------------------------------------------------------------Bash shell scripts :1. create file# vi scriptfileName.shwrite required command sequencefirst line must be #!/bin/bashand # show comment2. set execute permissionchmod u+x myscript.sh3. run with saved or given path----------------------------------------------------------------------------------------------------------------------------Redirection:1. Redirecting Output to a File# command operator filenameoperator:> Redirect STDOUT to file2> Redirect STDERR to file&> Redirect all output to file2>&1: Redirects STDERR to STDOUT(): Combines STDOUTs of multiple programs● File contents are overwritten by default. >> appends.2.Redirecting STDOUT to a Program (Piping)# command1 | command2STDERR is not forwarded across pipes3.Redirecting STDIN from a FileRedirect standard input with <tee commndls | tee filename => store and display output of ls=====================================================================1. users :1.Show logged in users and what they are doing.
  3. 3. #w=> show all logon usrs# users# who -q or # whoami=> show current usr login name# logname=>list current usrs and group they belong# groups2. report user and group id for process# idfind uid and gid of userlogin as root# id -u <username># id -g <username># id -G <username> => all gid for that user3.view logged activity# less /var/log/secure => u check login form which remote host with time and date# less /var/log/messages4. show listing of last login users# last [ # last | head => to look only upper logs for better understanding ]=> show users login time# ac { find detail}5. show log of login activity by users name# lastlog5. list loaded module# lsmod6. run program as substitute user# su [note default root]=> run command as root# sudo7. Sets, changes, or manages a users password.# passwd
  4. 4. 8. tcp / udp socket info# ss9. display info about system usr# finger10 : ~ indicate other user11.Authentication information is stored in plaintext files: # /etc/passwd # /etc/shadow # /etc/group # /etc/gshadow12.User management tools=> add user : # useradd Login_name=>modify user accountBy default user gets bash sell prompts. But we modified this by –s switch and given user to /bin/sh shell. Now change user shell again#usermod –s /bin/bash user1=> userdel = delete a user account and user’s related files# userdel loginnameprevent them to change any password:chattr +i /etc/shadowThen they run chattr -i /etc/shadow with sudo and are back in business.13.system usertypically run as unprivileged users, not as root Examples: daemon, mail, lp, nobodyRunning programs in this way limits the amount of damage any single program can doto the system.=====================================================================2. service:1. Control a Service.# service service_name start/stop/reload/status2. list all services chkconfig knows# chkconfig --list
  5. 5. 3. Turn services OFF or ON, under the specified System Run-Levels.# chkconfig --level 0123456 service on/off=====================================================================3. process:1.report running process status { note be sure that all service are running httpd, mysql ssh}# ps -auxf2. kill a process# kill pid3. really kill proces# kill -s 9 pidex. # pkill httpd : httpd or any process nameUsing this command the parent process will be running and all the child process will be killed.#killallThis command is used to kill all the processes4. check working process in detail [List open files.]# lsof -i5.Continuously updated display of most cpu-intensive processes# top6. process and parent child relation# pstreee, pstree -p7 find process.By predefined patterns: pgrep# pgrep -U root# pgrep -G student [student is group name]By exact program name: pidof# pidof programName [ex bash]8. signal send to procesSignal 15, TERM (default) - Terminate cleanlySignal 9, KILL - Terminate immediatelySignal 1, HUP - Re-read configuration files8.Scheduling Priority
  6. 6. => Viewed with ps -o comm,nice [Note : Values range from -20 to 19 but default to 0]=> Altering Scheduling PriorityWhen starting a process:# nice -n 5 commandAfter starting:# renice 5 PID9.Job Control=> run in background ; # command&=> halt process : ctrl + z=> resume in forground : # fg=> resume in background : # bg=> List job numbers and names: # jobs=====================================================================4. Network:1. check which service work on which port# netstat -ape# netstat -tulpnThis command is used to find the number of connections to the server. " netstat " commandwill list all the connections using httpd, exim, ftp etc. You can grep the needed port and find thenumber of connections to a particular port. You can find the Local Address, Foreign Address,State, port etc of all the connections.Example:root@server [~]$ netstat -planorroot@server [~]$ netstat -plan | grep ":80"display network interface i.e. information { note be sure that your interface up and running}# ifconfig => Enable interface with ifup ethX => Disable interface with ifdown ethX2. Checks the domain name and IP information of a server# nslookup domainname3. Sends test packets to a specified server to check if it is responding properly# ping ip./domain4. Lists the routing tables for your server# route
  7. 7. 5.Traces the existing network routing for a remote or local server# traceroute ip/domain6. to check active status of remote machin# ping ip/domain_name7. to check working of particular portTELNET is a client-server protocol, based on a reliable connection-oriented transport. Thiscommand will help us to find if a particular port on the server is open or not.# telnet ip portnoyou could find that port is open on server. If we receive a " connection refused " signal, thatmeans the particular port is not open on the server8.this command use to investigate dns record via terminal# dig A domain name# dig CNAME domain name# dig NS domain name9.it give hosting server ip and mail server for that domain# host domain name10. for ssh login# ssh ip -p portnoex # ssh 213.175.194.46 -p 2332211. Network Configuration Files=> Device configuration is stored in text files/etc/sysconfig/network-scripts/ifcfg-ethX=> Network Configuration FilesGlobal Network Settings => /etc/sysconfig/networkDNS Configuration => /etc/resolv.conf=====================================================================4. Hostname:1. check host name# hostname2. change hostnameedit file /etc/sysconfig/network => change hostname and domain name=> use following command to check ip
  8. 8. # hostname -ior change hostname as# hostname new_hostnmaeor make change in/etc/hosts=====================================================================6. System info:1. display bootup message# dmesg2. display system information (OS, kernel version, etc )# uname -a3.display free system memory# free -m=> display virtual memory stat# vmstat4.display free disk space# df -h=> disk used# du -sh or # du -kcheck used space for any location# du -sh *5. Check the environment.# set6. system architecture# arch or # uname -m7. how long system is up# uptime8. name of host
  9. 9. # hostname9. hexadecimal id for host# hostid10. i/o and cpu statistic# iostat11. statistic# cat /proc/cpuinfo# cat /proc/meminfo# cat /proc/zoneinfo# cat /proc/mounts12. You can also try this to find out if your CPU/Processor is 32 bit or 64 bit:# getconf LONG_BIT13. load on server# cat /proc/loadavg or #w or #uptime=====================================================================7. File :1. status of file# stat filename2. create file# vi filename ; create file if not exit=> using touch [ only create file ]# touch filename3. open file in editor# vi filename4. read file content=> # cat filename=> # more filename ; pagewise display=> # less filename ; step by step one page at a time=> # tail filenmae ; show file from end=> # head filename ; show file from beginning
  10. 10. 5. rename file# mv oldname newname6. copy file# cp source destination7. remove / delete file# rm filename=> # rm -f : force to change=> # rm -i : remove interactively=> # rm -r : remove recursively8. Searching file:# find -name filename=> show location of binary file# whereis binfile=> show full path of binary file#which binfile=> # locate fileName=> find file modified in specified days# find -ctime -10 [ ex in 10 days]9.creating link [ the link name not exit for creating that link ]=> symbolic link [It allows to associate multiple filenames with a single file , the data inthe original file can be accessed through the special file, which is called as Soft Link.,The inode of the original file/directory and the soft link should not be identical.]# ln -s file1 lnk1=> physical link [hard link not allow for dir , more than one file name reference the sameinode number. it helps us to reduce the disk space by having single copy of the originalfile and ease the administration tasks as the modification in original file reflects in otherplaces , The inode number for the hard linked files would be same]# ln file1 lnk1[Note : When a file system is created, data structures that contain information about files arecreated. Each file has an inode and is identified by an inode number (often "i-number" or even
  11. 11. shorter, "ino") in the file system where it resides. Inodes store information on files such as userand group ownership, access mode (read, write, execute permissions) and type of file ]10. permission# chmod [-option] whos=/+/- permissions filenamewhos : u - user, g -group, o - other , a - all=/+/- : = assign , + add permission, - remove permissionpermission : r -read, w -write, x -executeor by numeric method4- read, 2 - write , 1-execute for each whosmake combination of above for all whos# chmod combi_number filename----------------------------------------------------------------------------------------------------------------------------3 special attributes other than the common read/write/execute.Example:drwxrwxrwt - Sticky Bits - chmod 1777=> If the sticky bit is set for a directory, only the owner of that directory or the owner of afile can delete or rename a file within that directory.drwsrwxrwx - SUID set - chmod 4777=> The SUID permission makes a script to run as the user who is the owner of thescript, rather than the user who started it.chmod 4777 filename will change the mode to rwsrwxrwx You can run a simple find / -perm +4000 to get a list of all the suid files. You will notice a lot of network applicationssince root does all network related tasks.drwxrwsrwx - SGID set - chmod 2777=> If a file is SGID, it will run with the privileges of the files group owner, instead of theprivileges of the person running the program.chmod 2777 directoryname will set the sgid. If I have a dir named share and it is ownedby root and owned by a group named buddies, then when the sgid bit is set on thatdirectory, any file created or placed in that directory will be owned by the buddies groupregardless of who put the file in there.
  12. 12. if this permission set then it highlight it in terminal of linuxs instead of x in the owner permissions means that the sticky bit (suid) is enabled, sothis file will be executed with root permissions by all users----------------------------------------------------------------------------------------------------------------------------umask => for permissionExamples of using the umask commandTo give yourself full permissions for both files and directories and prevent the group andother users from having access: umask 077This subtracts 077 from the system defaults for files and directories 666 and 777. Givinga default access permissions for your files of 600 (rw-------) and for directories of 700(rwx------).To give all access permissions to the group and allow other users read and executepermission: umask 002This subtracts 002 from the sytem defaults to give a default access permission for yourfiles of 664 (rw-rw-r--) and for your directories of 775 (rwxrwxr-x).To give the group and other users all access except write access: umask 022This subtracts 022 from the system defaults to give a default access permission for yourfiles of 644 (rw-r--r--) and for your directories of 755 (rwxr-xr-x).ref: http://som.ou.edu/computing/unixhelp/examples/umask.html----------------------------------------------------------------------------------------------------------------------------11. owership ; change owner and group of file# chown [option] newowner: newgroup filename
  13. 13. [newowner or group must be exist][Note : each file or process has user and group id . if uid match give user permission ,if gid match give group permission , otherwise give other permission. each user hasprivate group and user id]12.attribute settingTo prevent anyone - even a root user - from deleting a file, you set the immutable bit ofthe file using the chattr command as follows -# chattr +i filenameif you want to allow everybody to just append data to a file and not change alreadyentered data, you can set the append bit as follows:# chattr +a filenameTo see what all attributes are set for a particular file, you run the lsattr command asfollows.# lsattr filename----i-------- filenameIf the immutable flag is set, there will be an i in the listing.lsattr filename ====> To check attributechattr -uia filename =====> To remove attributechattr +uia filename =====> To add attributeA list of common attributes and their associated flags is listed below. For a morecomplete list see man chattr.(A) Dont update atime(S) synchronous updates(a) append only(d) no dump(i) immutable(j) data journalling(t) no tail-mergingref: http://www.aboutlinux.info/2005/11/make-your-files-immutable-which-even.html13. determin file content
  14. 14. # file filenameCheck file type with file before opening todetermine appropriate command or applicationto use.14. text analysing=> # wc filename: count word , charactor, line, byte for input=> #sort filename : sort content of file original file remain unchange=> # uniq -c filename : remove duplicate=># diff : campare files=># aspell check filename : spell checking15. manipulating text=>#sed : stream editor [ find and replace]#sed ‘s/word/replaceword/g’ filename=>#tr : translate lowercase to uppercase and vice versa.==============================================================8. Greeting :1. ssh prelogin text# vi /etc/issue ; write message here2. postlogin message# vi /etc/motd ; default blank=====================================================================9. Directory:1. create directory# mkdir dirName2. rename directory# mv oldname newname3. remove empty dir# rmdir dirname=> remove dir with content# rm -r dir_name
  15. 15. 4. change directory# cd path=> # cd ; home dir=> # cd - : previous working dir=> # cd .. : one level up5. print working dir# pwd6. directory listing# ls=> long listing# ls -l→ first charactor is: ● - regular file ● l link file ● d directory ● p pipe ● c character special device ● b block special device=> # ls -a : include hidden file=> # ls -R : recursive thorugh dir=> # ls -ld : dir and symbolic link.check no of item in folder#ll | wc -l=====================================================================10. vi editorref: http://www.washington.edu/computing/unix/vi.htmluse vimtutor commad for help1. create# vi filename2. mode=> insert mode press i or insert button=> commadn mode press esc ones or twice upto sound beep
  16. 16. => visual mode: v for highlight3. command mode:navigation => h j k l button for left righ ..w or b : move word by worddelete char: forward: x backward : X number of char : 4x : 4 any number[ note: press 4x such combination one by one means press 4 then x etc ]delete word : dw, 3dwdelete line : whole line over cursor: dd line next to cursor : D number of line : 2dd [ put cursor at beginning of line ]u : undoctrl + r : redoother editor:vimnanogeditgvim====================================================================11. Extra :rpm1.rpm -ivh package : install2.rpm -Uvh package : upadate3.rpm -e package : uninstall4.rpm -qa : list all packageyum1.yum install package2.yum update package3.yum remove package4.yum listall : show all package5. # yum list installedwget:
  17. 17. 1.wget url : to downlaod filetar1. tar -cvf dir.tar dir : create archiv2. tar -tvf dir.tar : show all archive content3. tar rvf archive_name.tar newfile : add in archive4. tar xvf my-archive.tar : extract=====================================================================12. MySql :1. # mysqladmin processlistThis command is used to find the connections to the mysql database. It gives information aboutId, User, Host, db, Command, Time, State and Info of a mysql request to the server2. mysqladmin pr3. repair database table#repair table table_name;4. list all database#show databases;5. use particular database#use databaseName;=====================================================================13. CSF1. You can use these commands to block a particular IP from connecting to the serverhere it put ip in csf.deny file i.e. Block ip.# csf -d <IP>or# apf -d <IP> : if has apd firewall=> remove deny ip# csf -dr ip2.To check the status of CSF, run the command.
  18. 18. /etc/init.d/csf status3. Reload all the rules:# csf -r4. find ip in all csf files# grep ip /etc/csf/*5. allow ip [ note : it put ip in csf.allow , we never allow ip of server itself it is not permited bysystem]# csf -a ip=> remove allow ip# csf -ar ip6. enable csf# csf -e7. disable csf# csf -x8. quick restart# csf -g[ref : http://forums.digitalpoint.com/showthread.php?t=3155091 >> if ip block by csf firewall due to multiple wrong login entres need to remove it form firewall.ip block is indicated by error"Error - Access denied.2 >> If webmin has blocked your IP address, then you can remove the IP block by deleting theline from this file# /var/webmin/blockedIf you make to many wrong login/authentication attempts in Webmin, it automatically blocksyour IP from continuing.3>> ip also block using .htaccessIn .htaccessCode:
  19. 19. order allow,denydeny from xxx.xx.x.xxallow from all4>> Though using iptables is recommended, they can get a little confusing. You can also usethe route program which is a bit more straight forward./sbin/route add -host xxx.xxx.xxx.xxx reject=====================================================================14. apacheNumber of active conncection on the server at port 80# netstat -nap | grep :80 | wc -l=====================================================================15. tomcat=====================================================================16.eximvi /etc/cpanel_exim_system_filter exim -bpc exim -bp exim -bpr | grep frozen | awk {print $3} | xargs exim -Mrm /etc/init.d/exim status /etc/init.d/exim restart=====================================================================17. php=====================================================================18. cpanel=====================================================================19. perl1.# perl -v => check perl version=====================================================================20. clamscan antivirus:at startingclamscan -i --recursive=yes --remove=no path
  20. 20. after scanningclamscan -i --recursive=yes --remove=yes path[ path is dir path to which u want to scan ]=====================================================================21. croncrontab -lcd /var/log/croncd /var/spool/cron/=====================================================================22. iptables1. save changes in iptables/etc/init.d/iptables save2. stop service fo iptables/etc/init.d/iptables stop=====================================================================23. ssh1. find working port of sshgrep Port /etc/ssh/sshd_config2.ssh login#ssh -p portNO IP=====================================================================24. simple command1. date - display date and timefind file created on specific datels -l | grep Jun 16 17ls -l | grep Jun(two spaces)9 17:01login detail for specific datelast | grep Oct 14lastlog | grep Oct 14
  21. 21. 2. cal - display calendar3 history : show history of command previously run1. clear history# history -c2. disable history#export HISTSIZE=03. help=> # whatis command : getting short desciption of comand=> #commnad --help : Displays usage summary and argument list . not for all command=> #man command : Provides documentation for commands=> #info command : Similar to man, but often more in-depth=> cat /usr/share/doc : Extended Documentation4.Aliases let you create shortcuts to commands# alias dir=ls -laF. [where dir : alias name and ls -laf is commad to which dir aliase create] Ctrl + A Go to the beginning of the line you are currently typing on. Extremely useful in those scenarios when left/right arrow keys do not work. Same as HOME button. Ctrl + E Go to the end of the line you are currently typing on. Same as END button. Ctrl + L Clears the Screen, same as the clear command. Ctrl + U Clears the line before the cursor position. If you are at the end of the line, clears the entire line. Ctrl + H Backspace. Ctrl + R Let’s you search through previously used commands. Hit again to roll through the hits in the history. Searches through .bash_history in the user’s home directory. Arrowkeys Up/ Same as CTRL + P and CTRL + N. This will browse through the history. Hit Down enter to execute the command. Ctrl + C Kill whatever you are running. Ctrl + D Exit the current shell – logout.
  22. 22. Ctrl + Z Puts whatever you are running into a suspended background process. You can then use the terminal for something else. Type ‘fg’ in the terminal to restore the process. Ctrl + W Delete the word before the cursor. Ctrl + K Clear the line after the cursor. Ctrl + T Swap the last two characters before the cursor. Esc + T Swap the last two words before the cursor. Alt + F Move cursor forward one word on the current line. Alt + B Move cursor backward one word on the current line. Tab Auto-complete files and folder names. Shift + Page Up Scrolls through terminal buffer. / Down Ctrl+s pause Ctrl+q resume Ctrl+u del to start of line Ctrl+w del word (to left)=====================================================================Find version installed on server php -v httpd -v mysql -v exim -bVLinux distribution and kernel version :uname -a && cat /etc/*release check linux kernel and distribution running on server
  23. 23. $ uname -mrs =>distro is simply a kernel plus a set of packages that the distro creator decided should beincludedex : Linux 2.6.32-5-amd64 x86_64Where, Linux - Kernel name 2.6.32-5-amd64 - Kernel version number x86_64 - Machine hardware name (64 bit)OR # cat /proc/versionTomcat : check path for that./usr/local/jakarta/apache-tomcat-5.5.35/logs/catalina.outtomcat-5.5.35 is version install on server----------------------------------------------------------------------------------------------------------------------------Common Linux log files name and usage => /var/log/message: General message and system related stuff /var/log/auth.log: Authenication logs /var/log/kern.log: Kernel logs /var/log/cron.log: Crond logs (cron job) => /var/log/maillog: Mail server logs /var/log/qmail/ : Qmail log directory (more files inside this directory) /var/log/httpd/: Apache access and error logs directory /var/log/lighttpd: Lighttpd access and error logs directory /var/log/boot.log : System boot log /var/log/mysqld.log: MySQL database server log file => /var/log/secure: Authentication log /var/log/utmp or /var/log/wtmp : Login records file /var/log/yum.log: Yum log filesapf_log -- APF related logsbfd_log -- BFD related logscron -- Logs for all cronjobs that are run on the serverdmesg -- Logs from dmesg program which is used to examine or control the kernel ring buffer.lastlog -- The binary log that contains all of the last login information. (Type "last" to view)messages -- System logs from syslogdmysqld.log -- Logs from the mysqld process
  24. 24. secure -- Access logs from the sshd processyum.log -- Logs from system updates via yumLog location/var/log/messages# tail -f /var/log/messages# tail -f /var/log/maillog# tail -f /var/log/secure----------------------------------------------------------------------------------------------------------------------------

×