Linux cheat sheet


Known Directory

  • /media : removable media
  • /bin: binaries and executable programs
  • /boot: files need to boot the OS
  • /etc : system configuration files
  • /opt: third-party software
  • /var : log files
  • /user/local: locally installed software
  • /run: runtime data for processes since the last boot
  • /root: root user home directory
  • /tmp: files are removed after ten days; universal read/write permissions
  • /dev: contains information on essential devices
  • /home: location of home directories; used for storing personal documents and information on the system

 

Basic Commands

  • pwd: show the current working directory path
  • cd: change directory
  • ls: list contents of the directory
  • ls -l: -l to see detail like permissions and size ...
  • sudo: allows a superuser to run a command with root privileges
  • mkdir {directoryname}: create new directory
  • mkdir -p {parentdirname/directoryname}: create new directory and parent dir if it doesn't exist
  • rmdir {dirName} : remove directory
  • rm -rf {dirName}: recursiv force remove dir and everything inside
  • touch {filename}: create new, empty files
  • cat: display file content
  • less{filename}: application to view file
  • head{filename}: show the first ten lines of the file and add the option -n to define the number of lines.
  • tail{filename}: show the last ten lines of the file.
    • Add the option -n to define the number of lines.
    • Add the option -f to keep watching for new additions to the end of the file gives you a live feed.
  • whoami: se whish users you are.
  • su username: To change the user.
  • reboot, systemctl reboot, shutdown -r now: to reboot the system.
  • systemctl halt, halt, shutdown -h now, init 0: to shutdown the system but not power it off.
  • systemctl poweroff, poweroff, shutdown -P: to power off.

 

In-Out Redirection

  • echo "test" > file.txt : redirect standard output to a file. This will replaces the file if the file already exists
  • echo "test" >> file.txt: appends to the file
  • cat /etc/passwd | grep root: Chain scripts, files and commands together by the STDOUT as STDIN for the next command
  • 2> : Redirect standard error
  • 2>> : Redirect and append standard error
  • /dev/null: send the date to /dev/null which mean output will be delete
  • 2>&1 : Redirect STDEDD to STDOUT
  • : Accept input from file ex(mysql < filedump.sql)
  • exec : run command against output if command doesn't take exec you can do ex
    (find / -user testuser -exec rm -rf {} \; )
  • echo 'foo' | tee foo.txt : Tee command writes to the STDOUT, and to a file at a time as shown in the examples.

 

SSH SCP SFTP

AUTHENTICATION METHODS:
  • Password authentication
    ssh user@server : will be prompter to enter password
    ssh user@server:passwsshord : enter the password on the same line
  • KeyBase Authentication
    this key is generated from the server as a file, and you use it to connect to the server
    ssh -i "Key.pem" ubuntu@netprepare.com
    Also, you generate your key, and you give your public key to the server
    ssh-keygen
    cat ~/.ssh/id_rsa.pub
    ssh user@server
SSH SCP SFTP COMMANDS:
  • To issue the command on the remote server
    ssh user@server command
  • Secure copy file to the server
    scp filename user@server:~/
  • Secure copy from server
    scp user@server:~/ filename
  • Secure File Transfer Protocol This is like FTP but secure. You will be in a dif promote
    sftp user@server
    • ? : display options
    • ls : list files and dir
    • cd : change directories
    • get : download
    • put : upload
    • quit : Exit sftp
FTP TFTP TELNET:
  • File Transfer Protocol this traffic is not secure clear text
    ftp ftp://username:password@my.domain.com
    • ? : display options
    • ls : list files and dir
    • cd : change directories
    • get : download
    • put : upload
    • quit : Exit sftp
  • TFTP uses UDP also not secure and less reliable.
    To Download any file from the TFTP server:
    tftp -g -r filename ip-addr
    To push/upload any file from the device to the host:
    tftp -p -r filename ip-addr
  • Telnet uses TCP to access the server terminal, not secure traffic in clear text:
    telnet ip-addr

 

GREP

GREP EXAMPLES

  • grep pattern file.txt : look for the pattern in the file.txt if we add the option -i will ignore case and the option -v will shows lines that doesn't containe the pattern
  • grep mpls * : grep all files in curent directory
  • grep -r mpls : grep all files in this dir and subdirectory for the word MPLS
  • grep "^mpls" filename : search for lines starting with mpls
  • grep "mpls$" filename : search for lines ending with mpls
  • grep "^[abd]" filename : search for characters not contained in brackets
  • grep [mM]pls filename : search for pattern starting with either capital or lowercase m
  • grep "^$" filename : search for empty lines
  • grep -v ^# filename : search for uncommented lines
  • egrep :same as grep but using extended regular expressions

 

File and Dir

TEXT EDITORS:
  • vi: Text editor that is always installed
  • vim: new version of vi
  • nano: Simple text editor
  • touch: Create empty file
  • NB: new files belong to your primary groups
COMMANDS:
  • mkdir: Make directory add the option -p to create parent directories, if not already created
  • cp: Copy files and directories add the option -R to copy directory recursively
  • mv: Move files and directories
  • rm: Remove files and directories option -r / -R: Remove recursively option -f: Force remove option -i: Prompt before removal
PERMISSIONS:
  • ls -l: Check file or dir permissions you the command
  • chmod : To change the permissions for a file or directory you need to know:
    • Symbolic characters, such as u, g, o, r, w and x
      • u: User
      • g: Group
      • o: Other
      • a: All
      • r: Read
      • w: Write
      • x: Execute
      • s: Set UID or GID
      • t: Set sticky bit
      • -X: Indicate the execute permissions should only affect directories and not regular files
    • Octal bits
      • 1= Execute
      • 2= Write
      • 4= Read
  • chown user:group filename : To change owner and group permissions we can add the option -R: Set ownership recursively
  • chgrp: Change group ownership
  • setuid: Set user ID permissions on executable file
  • setgid: Set group ID permissions on executable file
  • umask:Set default permissions for new directories and files

 

Documentation

  • <command> --help : to get info on app/command
  • info <command> : Provides info on app/command can be more detailed than man
  • which <command>: show path of command
  • whatis <command>: display man page description and section
  • apropos <text> : Search man pages and descriptions for text
  • man secNum <app>/<command> : to check documentation we have ine sections
    1. Executable programs and shell commands
    2. System calls
    3. Library calls
    4. Special files
    5. File formats
    6. Games
    7. Miscellaneous
    8. root user commands
    9. Kernel routines

 

  • Symlinks: Soft links that connect one file to another symbolically; if the target file moves, the link must be updated
  • Hard link: Links directly to an inode and create a new entry referencing the existing file on the system
  • Create links between files:
    ln add the option -s for Symlink files, and without the -s option will create a hard link.

 

Users & Accounts

CREATE, DELETE AND MODIFY USERS:
  • sudo useradd username : create a user.
  • sudo useradd -u 1500 username : create a user with a specific ID.
  • sudo useradd -m username : create a user and create the home directory.
  • sudo useradd -m -d /path/to/home username : create a user and assign a home directory.
  • sudo passwd username : change or create a password.
  • sudo useradd -g priGroupName username : creating a user with a specific group
  • sudo useradd -g priGroupName -G SecGr1Name,SecGr2Name username : creating a User and Assign Multiple Groups
  • sudo useradd -s /usr/bin/zsh username : creating a user with a specific login shell
  • sudo useradd -c "Test User Account" username : creating a user with a custom comment
  • sudo useradd -e 2019-01-22 username : creating a user with an expiry date.
  • sudo chage -l username: to verify the user command
  • sudo useradd -r username : creating a system user used by the application
  • sudo usermod username : Modify user
  • sudo userdel username : Delete user
CREATE, DELETE AND MODIFY GROUPS:
  • groupadd groupname : Add a group
  • groupadd -g #GroupID groupname : Add a group and set Group ID
  • groupadd -r groupname : Create a system group
  • groupmod : Modify group
  • groupmod -n newName oldName : New group name
  • groupdel : Delete group
  • chmod g+s directoryname : Set group permissions for the directory, and all files created in that directory have the same permissions
IMP-COMMANDS AND NOTES:
  • id -u username : You can verify the user’s UID using the id command
  • id -gn username : To verify the user’s GID, use the id command
  • /etc/passwd : Users login and password and other info information ex (user comment and Login Shell)
  • grep username /etc/passwd : grep to access only the line containing the user
  • /etc/shadow : User login and password hash information
  • /etc/groups : Group member information
  • getent group username : Show all groups for a user
  • Primary group : The main group for a user; all files created by a user are set under this group
  • id : Print user and group IDs UID ranges:
    • 0 : root
    • 1-200 : System users for Red Hat processes
    • 201-999 : System users for processed that do not own files
    • 1000+ : Regular users
PASSWORD AGING OPTIONS:
  • chage : Modify the number of days between password changes
    • -d : Number of days since 1970-01-01 to define password change
    • -E : Set password expiration date
    • -I : Number of days of inactivity before password expiration
    • -l : Show account aging information
    • -m : Minimum number of days between password changes
    • -M : Maximum number of days between password changes
    • -W : Days of warning before the password change

 

Archive&Compress

TAR ARCHIVE FILES
  • tar : Archive files
    • -c : Create a new archive
    • -t : List contents of the archive
    • -x : Extract files from the archive
    • -z : Compress or uncompress the file in gzip
    • -v : Verbose
    • -j : Compress or uncompress the file in bzip2
    • -f : Read archive from or to file
  • tar -cf File12Archive.tar file1 file2 : Archive file1 and file2 into File12Archive.tar archive
  • tar -tvf File12Archive.tar : List all files in the File12Archive.tar archive
  • tar -xf File12Archive.tar : Extract files in the archive
  • tar -czvf File12Archive.tar.gz file1 file2 : Archive and compress using gzip file1 and file2 files into File12Archive.tar.gz archive
  • tar -zxvf File12Archive.tar.gz : Uncompress in gzip and extract files from the archive
STAR ARCHIVE FILES GENERALLY USED TO ARCHIVE LARGE DATA
  • tar : Archive files
    • -c : Create an archive file
    • -v : Verbose output
    • -n : Show results of running the command without executing the actions
    • -t : List contents of the file
    • -x : Extract file
    • --diff : Show the difference between files
    • -C : Change to the specified directory
    • -f : Specify the file name
  • star -c f=archive.tar file1 file2 : Archive file1 and file2 into archive.tar
  • star -c -C /home/user/ -f=archive.tar file1 file2 : Move to /home/user and archive file1 and file2 from that directory into archive.tar
  • star -x -f=archive.tar : Extract archive.tar
  • star -t -f=archive.tar : List contents of archive.tar
GZIP COMPRESSION UTILITY
  • gzip : Compression utility
  • -d : Decompress files
  • -l : List compression information
  • Examples:
    • gzip file1 : Compress file1 into file1.gz
    • gzip -d file1.gz : Unpack file1
    • gunzip filename : Unpack filename

 

CPU & Memory

PS
  • ps : display process status
  • ps -e : all prosses
  • ps -f : full format list
  • ps -ef : all full format
  • ps -eH : all in tree
  • ps -e -forest : all in tree different display
  • ps -u username : display users' process
  • ps -p pid : info of this PID
  • ps aux : get more info
  • pstree : other display
  • top : other display
  • htop : other display
TOP
  • : Kill process
  • : Quit
  • : Renice
  • : Change update rate
  • : Sort by CPU usage
  • : Sort by memory usage
  • : Toggle load average
  • : Toggle task display
  • : Toggle memory display
  • : Bold display
  • : Filter by username
  • -b : Start in batch mode
  • -n : Number of updates before exiting
NICE PRIORITY:
  • -20 : Highest priority
  • 19 : Lowest priority
  • Any user can make a task lower priority
  • nice -n 0 processName : to lunch a process with a defined nice
  • renice -n 10 : To change without killing the process
  • renice -n 10 $(pgrep processName) : To change the nice level of all process name processes
  • ps axo pid,comn,nice | grep processName : to test the process priority level has changed
PGREP : SEARCH PROCESSES
  • -u : Username
  • -l : Display process name
  • -t : Define tty ID
  • -n : Sort by newest
PKILL : KILL PROCESS
  • -u : Kill process for defined user
  • -t : Kill process for defined terminal
  • Kill signals:
    • 1 - SIGHUP :Configure reload without termination; also used to report termination of controlling process
    • 2 - SIGINT :Cause program to terminate
    • 3 - SIGQUIT :When user requests to quit a process
    • 9 - SIGKILL :Immediately terminate process
    • 15 - SIGTERM :Send request to terminate process; request can be interpreted or ignored
    • 18 - SIGCONT :Restart previously stopped process
    • 19 - SIGSTOP :Stop a process for later resumption
    • 20 - SIGTSTP :Send by terminal to request a temporary stop

 

Find&Locate

  • which command : show path of command
  • locate {fileName} : Locate file by name
  • updatedb : Update locate command databases incase a new file added it doesn show directly in the locate db
  • find :
    • find -name filename : To find files based on name in curent dir and sub dir
    • find -iname filename : To find files based on name ignore cases
    • find -mtime time : Find files based on time
    • find -size +N/-N : Find file based on size +N means size > N blocks and -N means size < N
    • find -newer file : Find files that were modified/created after ‘file’.
    • find / -mtime -3 : find all file that has been modified in the last 3 days. All file as we have defined the to start in the root dir
    • find / -mtime +3 : find all file that has been modified longer then 3 days
    • find / -user username : find all file owned by username
    • find / -uid 1002 : find all the file that belongs to a user by a userID id 1002
    • find / -user username -type f -exec rm {} \; : delete all files for the user username

List of titles