My personal quicklist of Linux server commands.
Just FYI, these commands are mostly for Apache/LiteSpeed servers on CentOS. I don’t do as much stuff with NGINX and Ubuntu. Will add more over time.
OS:
- hostnamectl– see operating system and version, reference link
- hostname– see current temporary hostname (I recommend not to use this, and to use- hostnamectlinstead.)
- hostnamectl set-hostname server.domain.com– change hostname to any desired domain. You may also have to edit hostname in files- /etc/hostsand- /etc/sysconfig/network, and possibly- /etc/sysconfig/network-scripts/*networkdevicename*(if you manually set it here).
- whoami– shows your user name (useful for knowing if you’re executing commands as root user or another user)
- su,- su -,- sudo -i– switch to root user if you haven’t already. “su -” is probably more proper since it creates a login shell with new environment.
- passwd– change password for current user
- logout– log out of current user
- yum update– update server packages (useful before doing new software installs)
- Auto completion – hit the [TAB] key while typing commands to auto complete names of directories and files.
- sudo dmesg -n 1– suppress annoying kernel messages every 10 seconds. Add this command to- etc/rc.local(or its equivalent) to run it at boot. More info
SSH:
- Connect to ssh ssh user@ip -p 2222(the-pand port number isn’t needed if using default port 22)
- /etc/ssh/sshd_config– editing SSHD, changing SSH port number, allowing/disabling SSH or password authenthication, etc.
- getting SSH port grep Port /etc/ssh/sshd_config(may need “sudo” in front)
- systemctl restart sshd.service– restart sshd. Link.
- cat ~/.ssh/authorized_keys– lists authorized SSH keys, add more public SSH keys here to give access other admins or support staff. The location might also be- /root/.ssh/authorized_keys.
SSH key – generate on Macbook terminal:
- generate SSH key ssh-keygen -t rsa
- choose private key save location or leave empty for default /Users/username/.ssh/id_rsa, choose passphrase for private key if you want (I usually leave empty)
- cat /Users/username/.ssh/id_rsa.pubto see public key, copy and import it to where you need. TIP: sometimes when copying off the command line, it adds line-breaks that you need to delete when pasting elsewhere.
- ssh-add /Users/user/.ssh/id_rsato load private key in terminal
- ssh-keygen -R 123.123.123.123– solves the “known host issue” by removing a known host. Useful for when you rebuild a server but keep the same IP.
SSH key – generate on Linux:
- generate SSH key ssh-keygen -t rsa -b 4096, and press enter through all the prompts (about 3).
- cat /root/.ssh/id_rsa.pubto see public key.
- cat /root/.ssh/id_rsato see private key.
Navigating around command line (full guide):
- ls,- ls -a– list files in directory, use- ls -Sto sort by size or- ls -Srto reverse order, show hidden files
- ls -l– list files but also show permissions, # of hardlinks, file owner and group, size and modification time. You can combine together- ls -la
- ls *.php– lists only files with .php extension.
- cd– goes to user home directory.
- cd /– goes to root directory.- cdor- cd ~goes to user home directory (of whichever user is logged in).- cdreturns to default working directory in linux (ideally, the root but often not the case)
- cd [directoryname]is relative whereas- cd /directoryis absolute
- cd ..– goes up to parent directory
- cd -– goes to previous directory
- pwd– shows path to current directory
- clearor CTRL+L to clear the screen
Files & Directories (create, delete, move, copy, archive):
- mkdir test– make directory called “test”,- rmdir testremoves it
- rm test– delete file or directory called “test”
- rm -rf test– deletes “test” directory without prompting you for every file
- rm -rf *test*– deletes all files/directories with the string “test” in the name.
- rm -fv *.txtremoves all files in current directory with “.txt” extension.
- find . -name *.ext -type f -deletedeletes all files with “ext” extension including within subdirectories. Other options.
- cp test /location– copy “test” file or directory to “/location” directory. Other options.
- cp oldname.txt newname.txtcopies file to new name in same directory.
- 'cp' -R -rf file locationuse this to do recursive overwrite without any prompt.
- cp -avr /path/dir1 /path/dir2copies one directory (and contents) to another.
- mv test /location– move “test” to “/location” directory. Use- mv -fto force overwrites. Other options.
- mv oldname.txt newname.txt– renames the file.- mvcommand also used for renaming directories as well.
- tar -czvf folder.tar.gz folder– archive “folder” directory into folder.tar.gz file. Other compression commands.
- tar -xzvf folder.tar.gz– extract archive in current working directory. Other options.
- gzip -d database.sql.gz– extract sql.gz files.
- zip -r folder.zip folderarchives the “folder” directory into zip format. You don’t actually need to put “.zip” but I find it makes the command easier to remember. (Don’t forget the- -roption as it makes the command recursive and includes every file within subdirectories as well.)
- unzip folder.zipunzips archive to current directory.
- Hide files and show hidden files
Files & Directories (ownership, permissions):
- Change file ownership – chown USER:GROUP FILEorchown -R USER:GROUP FILEfor recursive. Useful after migrating files from another server and they don’t work. Another link.
- chmod -R 755 /path/to/file.phpchanges that file permission to 755. For more explanations about change permissions and recursively change permissions (symbolic vs numeric method).
- find /path/to/dir -type d -exec chmod 755 {} \;and- find /path/to/dir -type f -exec chmod 644 {} \;are much betters ways to recursively set all directory permissions to 755 and file permissions to 644 (as common web practice).
- save command output to a file https://askubuntu.com/questions/420981/how-do-i-save-terminal-output-to-a-file
Files (searching & hack detection):
- grep -r "string" /home/user– (recursively) searches all instances of “string” for all files within- /home/user directory. Can also do- grep -r -l 'pattern' /path/to/dirto list only the files.
- find /home/user -type f -name "something.php"– searches- /home/userdirectory for all files named “something.php”.
- find /home/user -type f -ctime -7– searches all files within- /home/userdirectory changed within 7 days or less. (Change to + sign if you want to search for changes older…usually uncommon.)
- find /home/user -type f -name "*.php" -ctime -30– finds all files with .php extension changed within past 30 days. More find examples.
- find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort– finds most recently changed files, listed in order of less recent to most recent. More find examples.
- zgrep -Eo "string" /path/to/gzippedfile.gz– searches for the text “string” within an archive.
- find . -type f | wc -l– counts number of total files in current directory and subdirectories
File Transfer:
- wget https://address.com/to/file.zip– download external file to current working directory
- curl -0 https://addres.com/to/file.zipcan also work if wget doesn’t (other alternatives to wget)
- rsync -a [email protected]:/remote/dir /local/dircopies (pulls) remote directory to local directory.
- rsync -a /local/dir [email protected]:/remote/dircopies (pushes) local directory to remote directory.
- rsync -avz --rsh='ssh -p2220' /local/dir [email protected]:/remote/dirpushes to remote site using specified ssh port 2220.
- sftp user@IPorhostname:/path/to/file /local/dirdownloads remote file via SFTP to specific directory. This command will ask you for SFTP password. Can also try this command with “scp -r” instead of “sftp” if you need recursive copy.
SFTP:
- sftp user@serverIP_or_hostname– do this from destination server. (Use- sftp -oPort=1234 user@serverIP_or_hostnameif there’s a custom SFTP port other than 22.)
- Use cdandlscommands to navigate around the remote computer.
- get filename.zip– to download file local.
- Reference link
VI text editor:
- vi filename.txt– open any file up in vi editor
- press[ESC]– to switch to normal mode
- :i– insert (editing mode)
- dd(from normal mode) – deletes the line under cursor. Other delete commands.
- G(normal mode) – skips to last line
- o(normal mode) – appends a new line
- :q!– quit without saving
- :wq– quit with saving
- cat /path/to/file– prints the file.
- cat /path/to/file | more– prints file but showing full lines.
- grep database wp-config.php– prints only lines with the string “database” in wp-config.php.
- grep -A 1 "database" wp-config.php– prints all lines with “database” (but also INCLUDING 1 line after). Can use- -B 1to show 1 line before, or- -C 1to show both one line before and after.
Disks, usage & space:
- Check available space – df(default),df -h(friendly KB/MB/GB format),df -l(local size only)
- du -sh *– check sizes within current directory
- df -k
- df -k /tmp– checks free space of “/tmp” directory
- sudo du -a /home/ | sort -n -r | head -n 20– lists largest files in “/home” directory.
- find large files
- mount
- unmount – umount /path/to/mount(removes from /etc/fstab)
- view mounts – cat /etc/fstab
- disk space commands and more du commands
- du -hsx /* | sort -rh | head -10
Ports:
- Check for listening ports sudo lsof -i -P -n | grep LISTEN
Processes:
- kill processes – pkill 12345, replacing “12345” with actual process ID
Databases (MySQL & MariaDB):
- restart MariaDB – systemctl start mariadb
- export (aka “dump”) mysql database into a file – mysqldump -u dbuser -p dbname > dbfile.sql, you will be prompted for password
- import sql file into db (assuming db’s and users already created) – mysql -u dbuser -p dbname < dbfile.sql, you will be prompted for password. (Add-fflag after the “-p” to force an import to skip errors.)
- cat /root/.my.cnf– recover mysql root pass, or reset it
- managing databases and users from SSH, nice video and explanation
- creating databases and users from SSH
- curious about trying non-default mysql configs? Try this.
MySQL commands (for MySQL/MariaDB shell/prompt):
- mysql -u user -plogs you in,- exitlogs you out
- SHOW DATABASES;list all databases
- CREATE DATABASE database_name;– creates DB
- DROP DATABASE database_name;– drops DB
- SELECT user, host FROM mysql.user;– list all DB users
- CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'user_password';– creates DB user
- DROP USER 'database_user'@'localhost';– deletes DB user
- GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';– grant all privileges to specified user for specified database
- GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';– grant all privileges to specified user for all databases
- REVOKE ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';– revoke privileges
- SHOW GRANTS FOR 'database_user'@'localhost';– see all user privileges
- show global variables like 'log_error'– show location of error log file.
LiteSpeed web server:
- installing LS
- reset LS console pass – cd /usr/local/lsws/admin/miscand then./admpass.sh
- version check – /usr/local/lsws/bin/lshttpd -v
- start LS – /usr/local/lsws/bin/lswsctrl start
- restart LS – /usr/local/lsws/bin/lswsctrl reload
- upgrade OLS – yum update', then 'yum upgrade openlitespeed
- enable crawler (cPanel) – vi /etc/apache2/conf.d/includes/pre_main_global.confand add
- view logs /tmp/lshttpd/.status
- More LS license commands
WHM/cPanel:
- refresh disk quota
- license check
- force run backups – /usr/local/cpanel/bin/backup --force(more info)
- update WHM /scripts/upcpor/scripts/upcp --force(if it’s already updated)
- Reset max deferred email limit – delete `rm /var/cpanel/email_send_limits/max_deferfail_thedomain.com`
CyberPanel:
- Error logs – cat /home/cyberpanel/error-logs.txt(log files on CyberPanel)
- Cron schedules – /etc/crontabclear out unnecessary cronjobs eating up server resources (backups)
Security:
- CSF firewall – CSF firewall installation and basic commands
- opening port 1234 – iptables -I INPUT -p tcp --dport 1234 -j ACCEPT
- closing ports 111 – iptables -I INPUT 1 -m tcp -p tcp --dport 111 -j DROP,iptables -I INPUT 1 -m udp -p udp --dport 111 -j DROP
- sudo dmesg -n 1– disable annoying kernel messages
- Security log-scanning commands, please see Recovering from HACKED server
Firewalld:
- systemctl status firewalld– check status
- systemctl start firewalld– start it
- systemctl enable firewalld– enables it
- firewall-cmd --list-all,- firewall-cmd --list-ports
 – see open ports, alternate:- for s in firewall-cmd --list-services; do firewall-cmd --permanent --service "$s" --get-ports; done;`
- open port, firewall-cmd --permanent --add-port=1234/tcp(using whichever port number you need) , thenfirewall-cmd --reload
- systemctl stop firewalld– stops it
- systemctl disable firewalld– disables it
Configuration files (common locations):
Logs (locations and common commands):
- tail /location/of/logshows last 10 lines of log file
- tail -n 100 /location/of/logshows last 100 lines
- tail -f /location/of/logkeeps watching last 10 lines of log file
- You can also use “less +F” (but generally not for big files)
- grep "abc" /file/nameto find lines with the string “abc” in them. See other grep examples.
Disks (format, partition, mount):
- df -Thshow mounted disks/partitions and file systems
- lsblkshow attached storage disks
- Partition & format disk – sudo fdisk /dev/disknamereplace “diskname” with what you want (usually sda1/vdb1). From partition command line,nfollow defaults, thenato make it bootable (if needed),pto check that it partitioned correctly, andwto write these partition changes. Trylsblkafterwards to check everything worked.
- sudo mkfs.ext4 /dev/partitionnamepartition name is usually disk name with a partition number (sda1, sda2, etc). You can also switch- ext4file system to something else like- xfs.
- Mount new disk – sudo mkdir /disk1to create new “disk1” directory in your root (use another name if you want).sudo mount /dev/partitionname /disk1mounts partition to the directory.
- https://upcloud.com/community/tutorials/adding-removing-storage-devices/ for more info on automatically mounting at boot, etc.
Scripts:
- bash scriptname.shto run the script,- sh scriptname.shis another option
Leave a Reply