Bottom
apt / apt-get
Debian Package Manager
- sudo apt update
- sudo apt --upgradable (will show which packages will be updated)
.bash_profile
This is your login script
- Can edit .bash_profile to make Aliases permanent for your user.
.bashrc
Used to customize the shell - loaded whenever you open a new instance of the shell
- alias ls=’echo;ls –alF; echo; echo "Listed on: "$(date);echo’
- alias dir=’clear;ls’
- alias dir=’ls –lF | grep ^d’
- In Terminal to temporarily prevent an Alias from running, precede the aliased command with a backslash, ex: "\ls"
- Edit .bashrc or .bash_profile to make Aliases permanent for your user
- Note: If your alias is not working, move your User Specific Aliases and Functions BELOW where the globals are loaded in your .bashrc.
- If you’ve modified .bashrc and wish to "reload" it, use this command:
- Add this line to change the Root User Prompt Color to Red:
- PS1="[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]]# "
You can also just use /etc/profile instead of .bashrc or .bash_profile to edit your bash prompt, add aliases, etc. On a Raspberry Pi the custom Root Prompt is placed in /etc/bash.bashrc while the User prompt is placed in ~/.bashrc
In RHEL 7 for example the Alias 'll' with defaults of '-l --color=auto', lives in: /etc/profile.d/colorls.sh.
.htaccess
Example of .htaccess file:
AuthUserFile /var/www/html/private/.htpasswd
AuthGroupFile /dev/null
AuthName "My Private Directory"
AuthType Basic
<Limit GET POST>
require valid-user
</Limit>
Another Example of .htaccess file:
Satisfy all
Order deny,allow
Deny from all
Allow from all
AuthUserFile /var/www/html/.htpasswd
AuthName "EnterPassword"
AuthType Basic
<Limit GET POST>
require user ITS
</Limit>
Another Example of .htaccess file, deny IP or range:
Order allow,deny
Deny from 66.249.
Deny from 101.101.12.3
Allow from all
Note: Now create .htpasswd, see .htpasswd below
Note: changes to .htaccess are immediate, no httpd restart necessary
Note: you can also use: require user for specific users
Troubleshooting:
- Most common mistake: incorrect path to .htpasswd file, double-check path is correct
- Another common mistake: misspelling the .htaccess file (ex. .htacess)
- Apache config file: /etc/httpd/conf/httpd.conf – scroll down and make sure "AllowOverride" is NOT set to "None" but rather "All" – restart httpd
.htpasswd
Create the file:
- htpasswd –c .htpasswd <username>
To add users afterwards:
- htpasswd .htpasswd <username2>
.profile
Create to automatically load .bashrc in the shell:
~/.bash_profile should be super-simple and just load .profile and .bashrc (in that order)
~/.profile has the stuff NOT specifically related to bash, such as environment variables (PATH and friends)
~/.bashrc has anything you'd want at an interactive command line. Command prompt, EDITOR variable, bash aliases for your use. It must NOT output anything
Anything that should be available to graphical applications OR to sh (or bash invoked as sh) MUST be in ~/.profile
Anything that should be available only to login shells should go in ~/.profile
ACL (adding Access Control List functionality)
Before using ACLs for a file or directory, the partition for the file or directory must be mounted with ACL support:
- mount –t ext3 –o acl <device-name> <partition>
- or /etc/fstab:LABEL=/work /work ext3 acl 1 2
The file system being exported by an NFS server supports ACLs by default
Set ACLs for files and directories:
- setfacl –m <rules> <files/directories>
- setfacl –m g:accounting:rwx /project/payments
Set a Default ACL for a directory:
- setfacl –m d:<rules> <files/directories>
- setfacl –m d:g:fac:rwx /homes
Remove an ACL for files and directories:
- setfacl –x <rules> <files/directories>
- setfacl –x g:accounting /project/payments
Remove all extended ACL entries:
- setfacl –b <file/directory>
- setfacl –-remove-all <file/directory>
Remove all the Default ACL entries:
- setfacl –k <file/directory>
- setfacl –-remove-default <file/directory>
Set ACLs Recursively:
- setfacl –R –m <file/directory>
- setfacl –R –m g:fac:rwx /homes
View ACLs for files and directories:
- getfacl <file/directory>
- getfacl /project/payments
Note: in an long directory listing you ACLs are indicated by a "+" at the end
Active Directory: Joining a Linux Machine to AD
SSSD vs. Winbind
Winbind-ing
Adding new Hard Drive / Local Storage
- Add drive to server
- Once booted, fdisk –l to see new drive
- Create Partitions: fdisk
- fdisk /dev/<newdisk>
- n (add a new partition)
- v (verify)
- p (print partition table)
- w (write partition table to disk)
- Make file system:
- mkfs.ext3 –v /dev/<newdisk>
- mkfs –v –t ext3 /dev/<newdisk>
- Make local directory: mkdir mymount
- Mount new drive:
- mount /dev/<newdisk> /mymount
- Make mount permanent:
- edit /etc/fstab:
- /dev/ /mymount defaults 1,1
Add a User
Useradd (See User Administration below)
Alias
Create temp alias: alias newcommand=’yourcommand –arguments’
Remove temp alias: unalias newcommand
Aliases with switches: alias ‘rm –rf’="rm –rfv"
Disable an alias for the current session (ex. Preventing cp overwrite prompt): unalias cp / unalias <alias>
Temporarily Bypass an Alias:
- Precede term with a \
- Ex.: \rm
To Load your new aliases immediately from .bashrc: source ~/.bashrc or . .bashrc
Aliases, system-wide for all users, edit:
- /etc/bashrc
- Then Add this, if it’s not there already, to your .bashrc file:
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
Fi
Some Examples:
- alias l.='ls -d .' # Show ONLY hidden files.
- alias lx='ls -X' # ls, sort by extension.
- alias duh='du -h -max-depth=1' # Total size of this directory.
- alias ll='ls -hlrt --group-directories-first --color=auto' # Directories at top, size in human readable
- alias gh='history|grep' # Grep History for term, usage: gh vi
Finding Rogue Alias Declarations:
- If you checked for the offending alias in all the usual places: ~/.bashrc, ~/.bash_profile, /etc/bashrc and /etc/profile and it's not there, use this command to search /etc: grep -r '^alias <command>' /etc, ex: grep -r '^alias ll' /etc
In RHEL 7 for example the Alias 'll' with defaults of '-l --color=auto', lives in: /etc/profile.d/colorls.sh. So if your Alias is being overridden, check under /etc/profile.d/ first.
Apache / httpd
Restart Apache: apachectl restart
Alternate: service httpd restart
Apache Version: apachectl –v or apachectl –V (Verbose output including the compile settings)
Apache Version on other systems: try httpd –v or apache2 –v or apache2ctl –v
Test Apache / HTTP configuration file for errors: apachectl configtest
RHEL 7 / CentOS 7:
- Start Apache at Boot: systemctl enable httpd.service
- Disable Apache Start at Boot: systemctl disable httpd.service
- Start Apache: systemctl start httpd.service , options: < start | stop | restart >
- To verify that the httpd service is running: systemctl is-active httpd.service
Apache HTML files
/var/www/html or /usr/local/apache/htdocs (See User Administration below)
Authentication – setup
To setup LDAP or authentication types, in general, use:
- authconfig-gtk (GUI)
- authconfig (Text based)
bmon – Command Line
Powerful Network Bandwidth Monitoring and Debugging Tool for Linux: bmon
Command Line Switch (-p): bmon -p <network interface to display>
Command Line Switch (-b): bmon -b <Use Bits per Second (Mb, Kb) instead of Bytes per Second (Mib, Kib)>
Interface Command: d - for Detailed statistics
Interface Command: i - for additional Information
Interface Command: Shift+q - for Quick reference
Bookmark – Command Line, Terminal
To bookmark the current directory use: pushd .
To return to the bookmarked directory use: popd
Change a user password
passwd
Check your environment, path variables
env
Command line Calendar
To display the prev, cur, next month calendar: cal -3
To display the Year calendar: cal –y
Command line editors
pico, nano, vi, vim
Compare Files (diff)
cmp file1 file2
- No output if files are same
- If different, lists the byte number and line #
diff file1 file2
- No output if files are same
- If different, lists differing lines
diff --ignore-space-change file1 file2
- a.k.a. -b
- Ignores changes in amount of white space between files
- See here
diff --side-by-side –-suppress-common-lines file1 file2
- --side-by-side a.k.a. -y
- Offers a 2-column view of the files showing differences
- Can create: alias diffs=’diff –side-by-side –suppress-common-lines’
Console Resolution – changing
Changing Framebuffer or Text Console Display Line Resolution:
- If using grub, edit /boot/grub/menu.lst add vga=791 (or other value) after the end of the Kernel line
- If using lilo, edit lilo.conf and use vga=ext
Copy – Copy files and Directories
Recursive Copy All files in Current Dir to /tmp: cp –r * /tmp
CPU Information
Number of CPUs: nproc
Get CPU information: cat /proc/cpuinfo
CPU Information / Cores / Threads per Core / etc.: lscpu
Is this Server a Virtual Machine?: dmidecode | grep –i product
Get the number of CPUs: grep –i "physical id" /proc/cpuinfo | sort –u | wc -l
Is Hyperthreading enabled? Show Threads Per Core: lscpu | grep –i thread
XSOS tool for sysadmins (shows all this + more): wget people.redhat.com/rsawhill/rpms/latest-xsos.rpm
Crontab, List crontab files
User crontab files are kept in: /var/spool/cron
crontab –lu <username>
- –r to remove current crontab
- –e to edit current crontab
- –l to list the crontab file
- # to comment a line
Crontab Positions and what they mean (1 2 3 4 5 6-task):
1 = Minute (0-59)
2 = Hour (0-23, 0=Midnight)
3 = Day of Month (1-31)
4 = Month (1-12)
5 = Day of Week (0-6, Sunday=0)
6 = The Task (command) to Run at that Time
Ex.: Delete all files in your tmp folder every morning at 4:45am, Mon-Fri: "45 4 * * 1-5 rm /home//tmp/*"
Ex.: to run a job every 5 minutes: "*/5 * * * * /my/command"
Note: It’s best to use the full path to any commands given, ex: /usr/bin/rm /home//tmp/*
Note: If you don’t want an e-mail sent every time a cron job runs use: "45 4 * * * rm /home//tmp/*>/dev/null 2>&1"
Note: To collect the cron execution in a log file: "45 4 * * * rm /home//tmp/*>/home//cronlogs/clean_tmp_dir.log"
Current Login Session Info
who –umH or w
Cut
Say you have a text file with lines of e-mail addresses and you only want the login names:
Ex. File.txt
mickeymouse@aol.com
minimouse@aol.com
donaldduck@aol.com
Run: cat File.txt | cut –d’@’ –f1
Where: d = delimiter, -f1 is the field number
Produces:
mickeymouse
minimouse
donaldduck
Date (Show Date and Time, Set Date and Time)
Show the Date and Time: date
Set the Date and Time: date –s "02/16/2006 16:11:00"
Delete / Remove a Directory and it’s contents
rm –r –v mydir/ = recursive, verbose
Delete a User
userdel (See User Administration below)
DHCPd
On Redhat 4 (Standard Install)
- Start: /usr/sbin/dhcpd or /etc/rc.d/init.d/dhcpd start
- Restart dhcpd: kill –SIGTERM <pid of dhcpd>
- pid found in: /var/run/dhcpd.pid
- Conf File: /etc/dhcpd.conf
- Leases File: /var/lib/dhcp/dhcpd.leases
If you wish to test the configuration for any oddities, you can start dhcpd with the debugging mode. Typing the command below will allow you to see exactly what is going on with the server. Boot up a client. Take a look at the console of the dhcp server and you will see a number of debugging messages appear on the screen:
Other Locations:
- dhcpd.conf = /etc/dhcpd/dhcpd.conf
- leases = /var/dhcpd/dhcpd.leases
Directory Listing All w/ Folder, Executable, Links, DIR
ls –alF
Show only Directories:
- ls –ld * / (Keeps color codings)
- ls –lF | grep ^d or ls –l | grep ^d
- find . –type d
Show only the Number of Directories: ls –lF | grep ^d | wc
Display File Size in Human Readable Format: ls –lh
Display File UID and GID instead of User and Group: ls –n
Display One File Per Line: ls –1
Disk space, file system disk space usage, file system type (ex. Ext3, etx4..)
Simple Summary of Disk Usage in the Current Folder: du –hs
Directory Summary of Specified Directory: du –hsc <mydir>, ex. du –hsc music
Directory Summary w/ Subdirectory Summary: du –hc <mydir w/ subdirs>, see abve
Directory Summary w/ Ind. File Summary: du –hac <mydir>
Display the Kernel Ring buffer (prints out Bootup messages)
dmesg
DNS (named)
DNS Server Control:
- service named start {start|stop|status|restart|condrestart|reload|probe}
- /etc/init.d/named start {see above}
Flush DNS Server Cache: rndc flush
Environment Variables
Export Environment Variables on System Reboot:
- Add something like this to /etc/profile:
- export WSHOME=/var/tomcat/webapps/idm
- export JAVA_HOME=/usr/java/jdk1.6.0_03
- export BASEDIR=/var/tomcat
- After reboot they will be exported system-wide
For Regular Users, Edit one of these files:
- /home/user/.bash_profile (~/.bash_profile) – this personal initialization file is executed when you log into the system
- /home/user/.basrc (~/.bashrc) – this is the individual per-interactive-shell startup file
- Note: then logoff and logon again or just run: . .bash_profile to reload environment changes
ethtool
Display or change Ethernet card settings
Can easily get your Link Speed, Duplex, etc.
fdisk, Display Drive / Partition information
fdisk –l
Alternatively: dmesg | grep hd or dmesg | grep sd
File Descriptors
To increase file descriptors on Red Hat systems:
- echo 64000 > /proc/sys/fs/file-max
- ulimit –n 64000
To increase file descriptors in the Kernel on Red Hat systems:
- add fs.file-max = 65536 to /etc/sysctl.conf
After making changes, reboot or sysctl –p
Check your user limits: Sign in as user, issue: ulimit –n
File Perusal Filter (Less), opposite of More
ls | less (less allows scrolling by line or page)
In less, use ‘/’ to search for a pattern: /searchterm
Default file system
RHEL5: ext3
RHEL6: ext4
RHEL7: xfs
File Type Determination
file <filename>
Find
Find all files w/ index in the name & htm in the extension, no regard to case:
- find / -iname "*index*.htm*" –print
Find all files or directories modified in the last 24 hours:
Search the whole file system for all files being modified / accessed on Jan 26,2006:
- touch –amt 200601260000 /tmp/ref1
- touch –amt 200601262359 /tmp/ref2
- find / -type f –newer /tmp/ref1 –a ! –newer /tmp/ref2
Find all .txt files and show file datetime stamp sorted:
- find / -iname "*.txt" | xargs ls -ltr
Find file by filename
whereis <filename>
Firewall (iptables)
/etc/sysconfig/iptables = firewall rules file
To Enable logging to an Alternate File (ex. Iptables.log) the default = /var/log/messages:
- Edit: /etc/syslog.conf
- Add this line to the end: kern.warning /var/log/iptables.log
- Restart syslog: /etc/init.d/syslog restart
To Enable iptables logging:
- Edit: /etc/sysconfig/iptables
- Add this line before the REJECT or DROP Line(s) – Log and Drop in that order:
- A RH-Firewall-1-INPUT –j LOG –log-prefix "** Denied Input **"
- A RH-Firewall-1-INPUT –j REJECT –reject-with icmp-host-prohibited
- Restart iptables: service iptables restart
To List iptable Rules with Line Numbers: iptables –L –line-numbers
RHEL / CentOS 7:
- systemctl status firewalld = Check the firewall status
- firewall-cmd --state = Checks if firewall-cmd can connect to the daemon
- systemctl disable firewalld = Disables the system firewall
- systemctl stop firewalld = Stop the firewall
- systemctl start firewalld = Start the firewall
Gawk – Pattern Matching
Return only the usernames (9th column) and Ips (11th column) for those people who were able to login to ssh by searching the secure.x files
- grep "Accepted password for" secure* | gawk ‘{print $9, $11}’
Graphical Login / startx - Kill the GUI
Enter a virtual terminal and then kill the GUI:
init 5 = starts GUI again
Ctrl-Alt-F7 is where the GUI usually is
Grep
Find all occurrences of in file(s), case-insensitive:
- grep –i “<string>” files.*
Find all IP’s in 192.215. range:
- grep "192\.195\." *
- Note: "." Is special char for any char
Find (using Extended Regular Expressions) this OR that, ignore case:
- grep –iE ‘this|that’ *
- Note: Can use egrep instead of –E
- egrep –v "this|that"
- Find everything but (-v) this OR that. This works great at the end of a tail –f
Grep for a word and show the lines around the matching line:
- grep –B1 –A2 "keyword" <file>
- Where B1 = 1 Line Before and A2 = 2 Lines After the Matching Line
More Examples
Groups
List of groups is in: /etc/group
Fields:
- group_name : password : group_id : group_list1 , group_list2
- Ex: cdrom:x:24:student1,student2
List Groups a User belongs to:
- groups <username> , Ex. groups root
Show group ID of user: id –g jdoe
Show group ID to Group Name of user: id –gn jdoe
Show group ID and supplementary groups of a user: id –Gn root
Create a New Group: groupadd gDevelopers
Gzip / Gunzip / Compress / Expand Files
gunzip myfiles.gz
Ex. Write the uncompressed contents of README.gz to standard output. Pipe it into a pager for easy reading of a compressed file:
- gunzip -c README.gz | more
History
Search History for command: history | grep –i "<search term>"
Execute a command by its number: !<history number>
Prevent Saving your history upon shell Exit: Log out using: kill -9 $$
To Manually Clear your history: Type: history –c
Reverse-Search-History (reverse-i-search):
- Ctrl-r
- Note: Esc to exit, Enter to execute
To Search History Forward
- edit ~/.inputrc (unless overridded w/ the env var $INPUTRC)
- "\C-f": history-search-backward
- "\C-g": history-search-forward
- Usage: type 1st few letters of a previous command, then press Ctrl-f/g until you find the command
To add Date and Time to bash History (bash > 3.0) for all users, edit /etc/profile (for individual users, edit the /etc/bashrc file):
- Ex: "582 Thu 10-16-2014 11:19:49am : history", to do this just add export HISTTIMEFORMAT="%a %m-%d-%Y %H:%M:%S%P : "
- To see the current History Time Format: echo $HISTTIMEFORMAT
- Format of date / time follows strftime, see here
Hostname / Machine Name
hostname
Update /etc/sysconfig/network to include: HOSTNAME=myserver.mydomain.com
Update /etc/hosts file to include: 192.168.1.1 myserver.mydomain.com myserver
Set hostname without rebooting: echo > /proc/sys/kernel/hostname
Verify hostname is set:
RHEL 7: /etc/hostname or hostnamectl
HTML Redirect
Redirect Code:
- <META HTTP-EQUIV=”Refresh” CONTENT=”5; URL=http://www.mynewredirect.com”>
- 5 = Wait 5 seconds before redirecting
- URL = URL to redirect to
- Place this between <head> and </head> tags
IOSTAT (CPU and I/O Stats for Devices & Partitions)
Prints CPU and Device I/O status, per second and overall: iostat
Display 3 reports at 1 second intervals for device sda and all it’s partitions: iostat –p sda 1 3
Ipconfig
Ifconfig
- ifconfig eth0 199.106.9.100 netmask 255.255.240.0 broadcast 199.106.8.255
- ifconfig eth0 up / down
- Show all Up interfaces: ifconfig –u
- Show all Down interfaces: ifconfig –d
- List all interfaces: ifconfig –l
ISO – Make DVD .iso out of CDs (RHEL 5 – 5 CDs into 1 DVD)
Create top directory, you will need almost 3gb of space:
- mkdir dvd
Create directories on which to mount the CD ISO images using loop device mounts:
- mkdir rhel5{1,2,3,4,5} rhel5-docs
Make an ISO out of each CD, drop ISO in correct directory:
- dd if=/dev/cdrom of=/dvd/rhel51/rhel51.iso
- dd if=/dev/cdrom of=/dvd/rhel52/rhel52.iso
- dd if=/dev/cdrom of=/dvd/rhel53/rhel53.iso
- dd if=/dev/cdrom of=/dvd/rhel54/rhel54.iso
- dd if=/dev/cdrom of=/dvd/rhel55/rhel55.iso
Mount the new ISO images using a loop device mount:
- mount –o ro,loop /dvd/rhel51/rhel51.iso rhel51
- mount –o ro,loop /dvd/rhel52/rhel52.iso rhel52
- mount –o ro,loop /dvd/rhel53/rhel53.iso rhel53
- mount –o ro,loop /dvd/rhel54/rhel54.iso rhel54
- mount –o ro,loop /dvd/rhel55/rhel55.iso rhel55
Copy the isolinux directory and the .discinfo from CD 1 to the current directory (i.e. dvd):
- cp –a rhel51/isolinux rhel51/.discinfo .
Edit the .discinfo file, replace forth line with 1-5, this will tell the .discinfo file that it’s looking at 5 CDs total:
- vi .discinfo, change line 4 to read 1,2,3,4,5
This is key, or you’ll get errors with mkisofs:
- rm isolinux/boot.cat, (if not, you will get an error about a null pointer having same rock ridge name boot.cat)
Create the DVD ISO Image (l for long filenames, J so windows can read the disc, -R for filenames, -v verbose, -V volume label):
- mkisofs –l –J –R –v –V "RHEL5" –o redhatesdvd.iso –b isolinux/isolinux.bin –c isolinux/boot.cat –no-emul-boot –boot-load-size 4 –boot-info-table –m TRANS.TBL –x rhel51/.discinfo –x rhel51/isolinux –graft-points rhel51 .discinfo=.discinfo isolinux/=isolinux Server/=rhel52/Server Server/=rhel53/Server Server/=rhel54/Server Server/=rhel55/Server VT/=rhel55/VT docs/=rhel5-docs
Create the DVD ISO Image for Oracle Enterprise Linux 4.7:
- mkisofs –l –J –R –v –V "OEL47" –o OEL47.iso –b isolinux/isolinux.bin –c isolinux/boot.cat –no-emul-boot –boot-load-size 4 –boot-info-table –m TRANS.TBL –x el1/.discinfo –x el1/isolinux –graft-points el1 .discinfo=.discinfo isolinux/=isolinux Enterprise/=el2/Enterprise Enterprise/=el3/Enterprise Enterprise/=el4/Enterprise Enterprise/=el5/Enterprise
Test Mount the new DVD ISO:
- mount –o loop myfile.iso /mnt/tmp
Burn the new DVD ISO with Nero and Install!
Links: http://www.mjmwired.net/resources/redhat8-dvd.html
Links: http://www.linuxquestions.org/questions/showthread.php?t=148702
Network Install Prep: http://www.redhat.com/docs//manuals/enterprise/RHEL-5-manual/Installation_Guide-en-US/s1-steps-network-installs-x86.html
ISO - Make a Backup of a DVD
DVD to .ISO: dd if=/dev/cdrom of=/path/dvd.iso status=progress
JAVA - Check Heap Size
Check heap size of a running process: jmap -heap <pid_of_tomcat_process>
Jobs – Background, Foreground, Killing
To background a process or job use the & after the command:
To foreground a process or job use:
- fg <job number>
- fg w/o a number brings most recently backgrounded process to the foreground
To list jobs currently running use:
To kill a job use – this will request the job shutdown and clean up it’s tmp files:
Note: If you’ve started a process in the foreground and you decide later that you’d like to background it, you can use Ctrl-Z to stop the process and then use "%&" on the command line to restart the process in the background
Jumbo Frames
Test it out: ifconfig eth0 mtu 9000
Make it permanent:
- >vi /etc/sysconfig/network-script/ifcfg-eth0
- Add: MTU=9000
- Restart Network: service network restart
Check the configured MTU via netstat: netstat -i
Check the MTU via ifconfig: ifconfig
To confirm the MTU used between two specific devices. Use ip command as follows:
- ip route get {IP-address}
- ex. ip route get 192.168.1.1
You may need to tune the application / network protocol such as NFS and SMB to take advantage of Jumbo Frames.
Add this to /etc/samba/smb.conf:
- read size = 262140
- max xmit = 262140
- socket options = TCP_NODELY SO_SNDBUF=262140 SO_RCVBUF=262140
Note: This sped up jumbo frames from 30-40MB/sec to 60-70MB/sec
Kernels - Removing Old and Unused Kernels on CentOS
By default CentOS will keep last 5 kernels installed on your system. This behavior is defined by installonly_limit=5 line within /etc/yum.conf file
Kill (terminate or signal a process)
Escalating Kills:
- kill PID
- kill 1435
- kill –INT 1435 (i.e. Kill -2)
- kill –HUP 1435 (i.e. Kill -1)
- kill –KILL 1435 (i.e. Kill -9)
Signals (a signal is what linux uses for sending information between processes or between the kernel and a process):
- 0 = NORMAL EXIT status
- 1 = SIGHUP (can be used to force a process to re-read it’s configuration files)
- 2 = SIGINT (ctrl-c like)
- 9 = SIGKILL (Asta-la-vista baby, don’t wait, die!)
- 15 = SIGTERM (Please will you exit now, as soon as you possibly can)
- Note: List all the signals: kill –l
To Kill a user (disconnect them), kill their shell process (ex. PID sshd: root@pts/0):
- ps wwaux | grep sshd
- kill PID
ldd – Print shared library dependencies
[root@myserver bin]# ldd uxwdog
libicuuc.so.2 => not found
libicui18n.so.2 => not found
libicudata.so.2 => not found
libplc4.so => /usr/lib/libplc4.so (0xb75d4000)
libplds4.so => /usr/lib/libplds4.so (0xb75d1000)
libnspr4.so => /usr/lib/libnspr4.so (0xb759f000)
libpthread.so.0 => /lib/tls/libpthread.so.0 (0xb758f000)
libdl.so.2 => /lib/libdl.so.2 (0xb758c000)
libcrypt.so.1 => /lib/libcrypt.so.1 (0xb755f000)
libresolv.so.2 => /lib/libresolv.so.2 (0xb754d000)
libstdc++-libc6.2-2.so.3 => /usr/lib/libstdc++-libc6.2-2.so.3 (0xb750b000)
libm.so.6 => /lib/tls/libm.so.6 (0xb74e9000)
libc.so.6 => /lib/tls/libc.so.6 (0xb73b0000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0xb75e9000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb73a7000)
If you have program libraries that are stored in different directories on the system other than /lib, you might need to add something like this to your .bashrc file:
- export LD_LIBRARY_PATH=/var/opt/sun/directory-server/lib/
List system PCI devices and all devices connected to them
lspci
Locale – Change your language locale, UTF-8 or not
If you see weird characters in your Shell client, check to see if your Linux locale is set to use en_US.UTF-8 and you can change it to en_US:
- See the current Locale: cat /etc/locale.conf OR localectl status
- Change Locale from en_US.UTF-8 to en_US: edit /etc/locale.conf OR localectl set-locale LANG=en_US
To fix Ubuntu Server Error via SSH: -bash: warning: setlocale: LC_ALL: cannot change locale (en_US)
- Edit the default locale: sudo vi /etc/default/locale and add the following:
- LANGUAGE=en_US.UTF-8
- LANG=en_US.UTF-8
- LC_ALL=en_US.UTF-8
- Run these commands:
- sudo locale-gen en_US.UTF-8
- sudo dpkg-reconfigure locales
Login Shell – User Login Shell
List available shells:
- cat /etc/shells OR
- chsh –l
Change a user’s Login Shell:
- chsh <user_name> /bin/bash
- ex. chsh jdoe /bin/bash
LogWatch
LogWatch configuration file: /etc/log.d/logwatch.conf
View / Change the Services LogWatch monitors: /etc/log.d/conf/services/.conf
LogWatch runs under cron.daily: /etc/cron.daily/00-logwatch (/etc/log.d/scripts/logwatch.pl)
To change what time cron.daily (hourly / weekly / monthly) runs: vi /etc/crontab
Ls – List Directory Contents
ls –d win* = (DOS) dir win*.*
ls –lh = lists files w/ Bytes, K units
ls –F = Marks directories w/ trailing /, marks executables w/ trailing *, marks smbolic links w/ trailing @
ls –ld */ = Show only directories (keep color codings)
MCPAN
Reconfigure MCPAN:
- Start CPAN: perl –MCPAN –e shell
- Enter this command: o conf init
Configure Perl CPAN URL List:
- Enter the shell: perl –MCPAN –e shell
- View current URL list: o conf urllist
- Erase list: o conf urllist shift
- Add new http URL: o conf urllist push http://mirror.hiwaay.net/CPAN/
- Save changes: o conf commit
MDADM / MDSTAT
View the status of all multi disk arrays: cat /proc/mdstat
View the status of a multi disk array: mdadm –detail /dev/md0
Rebuid array after receiving error message: Kicking non-fresh sdc1 from array!:
- Ex. Errors showing in /var/log/messages:
Dec 6 20:48:25 nas kernel: md: md0 stopped
Dec 6 20:48:25 nas kernel: md: bind
Dec 6 20:48:25 nas kernel: md: bind
Dec 6 20:48:25 nas kernel: md: kicking non-fresh sdc1 from array!
Dec 6 20:48:25 nas kernel: md: unbind
Dec 6 20:48:25 nas kernel: md: export_rdev(sdc1)
Dec 6 20:48:25 nas kernel: md: raid1 personality registered for level 1
Dec 6 20:48:25 nas kernel: raid1: raid set md0 active with 1 out of 2 mirrors
This can happen after a power failure or UPS problem. Try adding the kicked disk back into the array. This will rebuild the mirror from the good disk. It will take time.
- mdadm /dev/md0 –add /dev/sdc1
- mdadm –detail /dev/md0 (Will give the status of the Mirror)
- cat /proc/mdstat (Will show progress and details of the Mirror rebuild)
Memory (Investigate Memory Usage)
To Investigate Memory Usage on a Linux system you can use a few different tools:
- top
- free –mt (shows in MB w/ Totals)
- cat /proc/meminfo
- ps –eo vsz,ooki,pid,user –sort vsz
Use Watch to monitor Memory and Highlight Differences: watch –d free –mt
- Buffers = cache raw disk (or other blockdevice) blocks (like smartdrive)
- Cached = page cache use for filesystem-level caching, swapping, this is the disk cache
- Note: there should be very little unused memory available, Linux will cache most of the free RAM and free it up when applications need it. This causes disk IO, etc. to be read from cache instead which speeds up the system. Linux will also swap out processes that have been idle for awhile and free up more RAM for cache or applications – they will be swapped back in when they are needed.
- Linux considers unused memory as wasted memory.
mkdir
Create a directory and sub-directories:
- mkdir -p fruit/{apple,pear,peach}
Modules – Lists modules currently loaded into the kernel
lsmod
mod_rewrite – for Apache / Apache2
By default, Apache2 comes with mod_rewrite installed. To verify its existence, run:
- ls -l /etc/apache2/mods-available/r*
To enable and load mod_rewrite:
- sudo a2enmod rewrite
- Restart Apache: sudo service apache2 restart
To use it, in .htaccess to not dispaly .php extensions, add this to .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d # is not a directory
RewriteCond %{REQUEST_FILENAME}\.php -f # is an existing .php file
RewriteRule ^(.*)$ $1.php
motd – How to change the Message of the Day
vi /etc/motd
Cool ASCII Art Generator: Link. Very useful for Linux logon banners using Font: small, Character Width: Default, Character height: Default.
Mount
Cause all the file systems mentioned in fstab to be mounted as indicated (except those w/ noauto):
Mount CD-ROM:
- Create Mount Point Locally: mkdir /mnt/mycdrom
- Mount it: mount –t iso9660 –o ro /dev/cdrom /mnt/mycdrom
Mount USB device:
- RHEL7: list all drive partitions and their UUIDs: lsblk -f
- Mount the USB Device:
- find out if it’s recognized: lsusb or in tree form: lsusb -t
- find out device name: dmesg | tail
- Create mount point: mkdir /mnt/usb
- Mount it: mount –t vfat /dev/uba1 /mnt/usb
Mount a SAMBA share on Linux:
- mount –t cifs –o username=<username> //t2.worldnet.net/<sharename> /mnt/oracle
Mounted Devices – Display what’s mounted
- This displays all mounted file systems, the fs type, read/write status, etc. SCSI drives are denoted by ‘sd’, IDE by ‘hd’
- cat /proc/mounts
UnMount: umount uba1
Note: /etc/fstab defines mountable file systems & devices on startup. Edit this to make the mount available on startup
- vfat file system is MS Windows w/ long filename support
Show Databases:
mysql> show databases;
shell> mysqlshow –u root@<hostname>
Use a Database:
mysql> use <databasename>;
Show Database Tables:
mysql> show tables;
mysql> select * from mytable;
Dump Database:
shell> mysqldump –u <mysqlusername> -p <databasename> > mydb.sql;
Log in as root & use the mysql DB:
shell> mysql –user=root mysql
shell> mysql –u root@<hostname>
Add Users:
shell> grant all privileges on *.* to ‘<mysqlusername>’@’localhost’ identified by ‘mypassword’ with grant option;
Show mysql Users:
mysql> use mysql;
mysql> select host,user,password from user;
Create new Database:
mysql> create database <dbname>;
Import Database SQL Dump into new DB:
shell> mysql –u <mysqlusername> -p <databasename> < /tmp/mydb.sql
Remove all Records from a Table:
mysql> truncate table <tablename>;
Remove a Table:
mysql> drop table <tablename>;
Count Records:
mysql> select count(*) from <tablename>;
mysql> select count(username)from users;
Alter: Add a Column to a Table:
mysql> alter table <tablename> add column <newcolumn> char(25);
Select: Select from 2 Tables:
mysql> select employees.Firstname, employees.Lastname, vehicles.Car from employees, vehicles;
Show Version and Proc:
mysql> mysqladmin –u root –p version proc
MySQL Help, List Server-Side Help:
mysql> help contents
Name Resolution - Configure
/etc/hosts
/etc/resolv.conf
netstat - network connections, routing tables, interface stats, etc.
Show Listening Ports and Processess, numerically (i.e. not by service name):
Show only Listening TCP sockets::
Show only Listening UDP sockets::
Show only Listening UNIX domain sockets::
Note: netstat translates the default ports to the service name using the mappings from this file: /etc/services
Network Card Configuration via Command Line
Server Side, Edit /etc/sysconfig/network-scripts/ifcfg-eth0:
- Note: ONBOOT=YES or NO
- Note: IPADDR, NETMASK, GATEWAY
Save file and then: service network restart
NFS
Server Side, Start NFS:
- /sbin/service nfs status
- /sbin/service nfs start/stop/reload
- /sbin/chkconfig –level 345 nfs on
Server Side, edit: /etc/exports
- directory hostname(options)
- /homes slab2.abc.com(rwx,sync)
- /homes *.abc.com(rwx,sync)
Server Side, Notify NFS daemon of your change: /sbin/service nfs reload
Client Side:
- Client Side, Create mount point directory: mkdir /homes
- Client Side, Mount NFS directory: mount server:/homes /homes
- Client Side, Mount NFS via fstab: server:/homes /homes nfs rsize=8192,wsize=8192,timeo=14,intr
- Client Side, Mount NFS via autofs: use /etc/auto.master, /etc/auto.misc, etc.
Note: exportfs –a exports all directories in /etc/export
Note: exportfs –au un-exports all directories in /etc/export
NFS: Locking Down the Ports, Opening the Firewall - How can I configure a system as an NFS server which sits behind a firewall with NFS clients outside of the firewall?
Server Side, Create or Edit /etc/sysconfig/nfs:
# NFS port numbers
STATD_PORT=11002
STATD_OUTGOING_PORT=11003
MOUNTD_PORT=11004
RQUOTAD_PORT=11005
LOCKD_UDPPORT=30001
LOCKD_TCPPORT=30000
Server Side (may not need this): reboot
Server Side, Check the Port Assignments: rpcinfo –p localhost
Server Side, Open these Ports in the Local Firewall:
111: portmap (tcp/udp)
2049: nfs (tcp/udp)
4045: nfs lock manager port (tcp) ?? may not need this port
30000: example lockd (tcp)
30001: example lockd (udp)
11002: example statd/status (tcp/udp)
11003: example statd/status outgoing (tcp/udp)
11004: example mountd (tcp/udp)
11005: example rquotad (tcp/udp)div>
NFS Troubleshooting
Server-Side:
- Display NFS Activity: nfsstat –s
- Display all remote mounts: showmount –a
- Display only the names of the directories mounted by the clients: showmount –d
- Display list of the file systems exported by the server: showmount –e
Client-Side:
- Display information on the file systems mounted remotely, mount point, amount of available space: df –hF nfs
- Display NFS activity on Client: nfsstat –c
NetworkManager on CentOS / RHEL 7.x
Service
- Display service information: systemctl status NetworkManager
- Enable service at Boot: systemctl enable NetworkManager
- Disable service at Boot: systemctl disable NetworkManager
- Service other: systemctl start|stop|restart NetworkManager
Common Commands:
- Display General Network Status: nmcli general status
- Display List of NetworkManager-recognized Devices and their current Status: nmcli device status
- Display Device Connection Status: nmcli con show
- Display Detailed Device and Connection Information: nmcli device show
- Disconnect a Device (ex. ifconfig eth0 down): nmcli device disconnect ens32
- Connect a Device (ex. ifconfig eth0 up): nmcli device connect ens32
NTP Server Setup (UDP 123)
Setting up Linux as a Time Server:
- Install latest version of ntp (rpm –qa | grep ntp)
- Edit /etc/sysconfig/iptables add upd access for port 123 (ntp)
- Make sure Service Starts on boot in current runlevel: chkconfig ntpd on
- Modify /etc/ntp.conf (add time servers, add restrictions for local network access)
- ntpdate –b pool.ntp.org (initial sync, done the first time before ooking the daemon, do NOT need to do each time the daemon starts)
- Start Service: service ntpd start
- Verify it’s running: pgrep ntpd
- Verify it’s listening: netstat –tuna
- Check how it’s synchronized: ntpq –p
Indication That Your Time Server is Working:
- The delay and offset values should NOT be 0 and the Jitter values should be under 100
Telltale Sign Your Server is Not Synchronizing:
- All remote servers have jitters of 4000 w/ delay and reach values of 0
Note: Your internal workstation computers will not be able to use the server as a synchronization source until the LOCAL(0) clock has stable time. This may take up to 15 minutes after starting the NTP daemon
Time Servers:
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
server pool.ntp.org
Working Configuration File: ntp.conf
NTP Server Tools
It may take a number of minutes for the clock to synchronize. You can use the ntpdc command to view information about ntpd’s status. It can be used in interactive mode, by simply entering ntpdc, or invoked with the –c switch to run the commands from the shell prompt.
Note: these commands will only work on a server running ntpd, i.e. a Time Server, not a Client
Here is a list of useful ntpdc commands:
- ntpdc –c listpeers (list known peers)
- ntpdc –c peers (list known peers & their state summary)
- ntpdc –c sysinfo
- ntpdc –c sysstats (print stats counters maintained in the protocol module)
- ntpdc –c iostats (print stats counters maintained in the input-output module)
Oracle
Get Oracle Version Number: select banner from v$version;
OS / Kernel Version
uname –sr = kernel name, kernel release
uname –r = kernel release number
uname –v = kernel version
cat /etc/xxxxx-release = where xxxxx is redhat, fedora, etc. this shows what OS and version is installed
Pam.d (Auto-create Home Directories on a Server when Logging in using LDAP authentication)
Each client is responsible thru pam.d to create their own home folder when they log in to a server using ldap.
Make sure each client uses authconfig to use the LDAP server (use MD5 passwords, Use Shadow Passwords, Use LDAP Authentication, Local authorization is sufficient)
When the client logs in, the client pam uses the ldap attribute called: homedirectory as the path to create their home directory.
To enable the client to create their home directory based on that ldap attribute, you add this line to: /etc/pam.d/system-auth:
- session required /lib/security/$ISA/pam_mkhomedir.so skel=/etc/skel
- Note: you can add this to the end to auto-set the umask: umask=0077 (Which gives 700 to the home directory)
Here’s the Step by Step along with setting up permissions ACL on the home directory: Document
Password – change users password
passwd username
Lock a User Account: passwd –l username
Unlock a User Account: passwd –u username
Set User Account Expiration: usermod –e 07/23/2006 username
Path, Setting your Path
export PATH=$PATH:/my/new/directory1/:/two
Enter this each time you login or add to your .bashrc file so it will stick on subsequent logins
Adding a ‘.’ As the last entry in the PATH means current directory for a program name. Thus preventing you from having to type ‘./myprogram’ to execute a program. Just type ‘myprogram’
Perl – Installing Modules
Manual Way:
- Download perl-ldap from cpan
- gunzip –c perl-ldap-0.29.tar.gz |tar xvf –
- cd perl-ldap-0.29
- perl Makefile.PL
- make
- make install
Easy Way:
- perl –MCPAN –e ‘install Net::LDAP’
Perl – Check for Existence of a Perl Module on your System
Does a Module Exist:
- An easy way to check for the existence of a Perl module on your system (technically, in Perl’s @INC array, a list of directories Perl searches when attempting to load modules) is to run perl –e ‘use module;’
- Example: perl –e ‘use HTML::Parser;’
- If nothing is returned, Perl was able to locate the module. Otherwise, you will see Can’t locate HTML/Parser.pm in @INC.
View @INC array (to see where Perl is searching for it’s modules): perl –V
Permissions
User / Owner (you)
Group (a group of other users that you set up)
Other / World (anyone else browsing on the file system)
The value of each digit is set according to what rights each of the types of people above have to manipulate that file.
Permissions are set according to numbers. Read is 4. Write is 2. Execute is 1. The sums of these numbers give combinations of these permissions:
- 0 = no permissions; person cannot read, write, or execute the file
- 1 = execute only
- 2 = write only
- 3 = write and execute (1+2)
- 4 = read only
- 5 = read and execute (4+1)
- 6 = read and write (4+2)
- 7 = read and write and execute (4+2+1)
Ex. chmod 700 myfileonly.html
Permissions: Change the group of a file:
- chgrp <newgroup> <filename>
- Change Group to <gName> in this Folder Recursively: chgrp –R <gName> .
Permissions: Change the owner of a file:
- chown <newuser> <filename>
PGREP – Show Process ID
pgrep looks through currently running processes & lists the PID’s which match the selection criteria
PHP – php.ini
vi /etc/php.ini
Postfix
Postfix mail system commands below are reserved for superuser / root users only.
sudo postfix reload (Re-read configuration files, Running processes terminate at earliest convienence)
sudo postfix status (Indicates if postfix is running, if so its PID)
sudo postfix stop (Stops postfix in an orderly fashion)
sudo postfix start (Starts postfix and runs a configuration check)
sudo systemctl restart postfix (Restarts postfix using systemctl)
sudo postfix check (Runs a configuration check)
Note: Postfix configuration files are: /etc/postfix/main.cf and /etc/postfix/master.cf
Power Off / Shutdown / Reboot
poweroff (turns off computer)
shutdown –r now (reboots)
reboot (reboots)
Print Screen (PrtScn) – in X
Capture the entire screen: press "PrtScn" button
Capture where Mouse points to: press "Alt+PrtScn" button
Process Status
ps
Processes – Show
ps –A –-sort command / cmd, Ex. ps -A --sort=uid,cmd or ps -A --sort=pid
ps –A | grep httpd
ps –wwaux
Show in Tree Form: pstree
Return to Your Home Directory
cd ~
Root Password, Forgot Root Password
http://www.creativelogichome.com/unix/unixrpw.htm
Route – Adding / Deleting
Add a Static Route to the 10.199.1.0 Network Using the Gateway of 192.54.86.51:
- route add –net 10.199.1.0 netmask 255.255.255.0 gw 192.54.86.51
Delete that Static Route to the 10.199.1.0 Network Using the Gateway of 192.54.86.51:
- route del –net 10.199.1.0 netmask 255.255.255.0 gw 192.54.86.51
Show the Current Routes:
Note: To Make the Routes Permanent (so they stick when the box is rebooted):
- add the "route add" command(s) to the bottom of /etc/rc.local file
Routing Table, Display Kernel IP Routing Table
netstat –nr
route –v
RPM
Query version of a package:
- rpm –q <package>
- ex. rpm –q kernel (displays installed kernels)
Install a package:
Force Install of package:
- rpm –ivh -force <package>
List contents of a package (shows files and file destination paths):
- rpm –q –filesbypkg –p <package>
- rpm –qpl <package>
Remove / Erase a package:
Show all installed packages:
Show where package was installed (ex. Pine):
Following command can be used to distinguish between a 32-it or 64-bit package:
- rpm –qa –queryformat "%{NAME}-%{VERSION}-%{RELEASE} (%{ARCH})\n" | grep libaio-0.3
RSYNC – backup
rsync –av source/ destination/
- Trailing slash on the source matters, if omitted, produces destination/source/<files>
rsync -av --delete source/ destination/
- --delete deletes any file from destination/ that is not in source/ any longer.
- By default if a file is deleted from source/ and had already been rsync’d to destination/ the copy in destination/ will not be removed
rsync –n –av –delete source/ destination/
- The –n command will do nothing but display what rsync *would* do
Switches:
- --stats gives some file-transfer statistics
- --exclude ‘*.txt’ will exclude all .txt files
- --progress shows progress during transfer
- --exclude-from ‘/home/backup/exclude.txt’ excludes all files listed in exclude.txt, ex:
- myBadDirectory
- public_html/database.*
- downloads/*
Run Levels - (Runlevel)
Ctrl-Alt-F1 = switch to console
- init 1 = console / single user
- init 3 = full multiuser, stops X server
- init 5 = Start X server, X11
- cat /etc/inittab = displays runlevels in file
- change default run level /etc/inittab, line: id:5:initdefault:
RHEL / CentOS 7:
- systemctl get-default = Check your current runlevel settings
- If current setting is: graphical.target then Linux will boot into GUI Mode
- If current setting is: multi-user.target then Linux will boot into NON-GUI Mode
- systemctl set-default multi-user.target = After this command and a reboot, Linux will book into Non-GUI (ex. init 3) runlevel
Running Remote X Applications
On local machine, log into GUI, open terminal window:
- ssh –X blah@xxx.xxx.xxx.xxx to securely run remote x applications
echo $DISPLAY to see what display is being exported
Run remote X Applications – Export Display
On local machine:
- Start xterm
- xhost remote.machine.ip
On Remote Machine:
- export DISPLAY=local.machine.ip:0
Samba
List info about machines that respond to SMB name queries on a subnet. Use this to see if your local host smb is started.
Connect to Samba Share:
- smbclient //192.168.1.1/<sharename> - U <username>
List Local Samba Shares (w/o password):
Create a samba password:
- On the samba server: smbpasswd –a <username>
Samba configuration file:
Scheduling Jobs
at <time> = runs commands at specified time
atq = lists pending commands
atrm <job> = cancels pending jobs
batch = runs commands when system load permits
SCP (Secure Copy) – Remote File Copy, uses SSH
scp –P <target port> <file1> <user@host>:<location on host>
Ex. scp –P 42XXX myfile.tar.bz2 uers@remotesystem.worldnet.net:/home/oracle
Copy an entire Directory (all files below, recusively (-r) AND preserve modification times (-p)) to a Target system directory (If target directory doesn't exist, it will be created (-r)):
- scp -rp localFolderAndFilesWithin/ user@remoteserver.org:/remoteFolder/
- Note: This will copy all the contents to: /remoteFolder/localFolderAndFilesWithin/
Copy a file From a Remote Server to Your Local Server
- scp user@remoteserver.org:/file/to/copy.txt /local/system/copy/
Screen – Screen Manager w/ VT100 / ANSI Terminal Emulation
Install: yum install screen
Screen Commands from within the Root Terminal:
- Start: screen
- Start using a session_name: screen -S myname
- Attach to a Screen: screen -r <session_name> OR <session_ID>
- Reattach to a single Screen Session: screen -r
- -- If you try to reattach and you get get an error about no screens to attach to, first detach, then reattach: screen -d -r <session_name>
- Force Detach the Screen: screen -x -R
- Create and Name a screen Session: screen -S <session_name>
- Create and Name a Screen Session and Name the Terminal: screen -S <session_name/ID> -t <terminal_name>
- Kill / Quit a Screen Session using Name: screen -S <session_name> -X quit
- List Screens: screen -list OR screen -ls
- Set a Title for your Screen session: screen -t <title>
- To Join a Screen that is already attached (ex. for training / shadowing): screen -x <session_name/ID>
- How to tell if you are in a Screen Session: Ctrl-a t
Screen Commands from within a Screen Session:
- Name your Screen Session: Ctrl-a : sessionname myname
- Create a new Window: Ctrl-a c
- Exit the current Window / Session: exit
- Kill the current Window / Session: Ctrl-a k
- Kill current and All Sessions: Ctrl-a \
- Lock your Screen Session: Ctrl-a x
- Switching between Windows: Ctrl-a n
- Switching between Current and Previous Windows: Ctrl-a Ctrl-a
- Detach from a Screen Session: Ctrl-a d
- List Screens: screen -list OR screen -ls
- Logging your Screen Output: Ctrl-a H
- Set ACTIVITY alert for a window: Ctrl-a M
- Set INACTIVITY alert for a window: Ctrl-a _
- Show Status Bar: Ctrl-a w
Screen Scrollback Buffer:
- Increase Screen scrollback buffer while in a screen: Ctrl+A : then type: scrollback 10000
- -- to scroll while in a screen: Ctrl+A ESC then type use the mouse wheel to scroll. To exit scrolling mode press:ESC
Script – Make a typescript of a terminal session
This command makes a typescript of everything printed on your terminal:
- script
- Note: To Exit: Ctrl-D
Search through files to find text (fgrep)
fgrep "search_word" *.*
fgrep = grep –F
Sed – Search and Replace within Files (ex. *.html)
This command will search all .html files and replace 'foo' with 'bar'
- sed –i 's/foo/bar/g' *.html
- Note: Before you run this command make sure grep returns what you expect: grep "foo" *.html
If you want to get sed to make a copy of the original file prior to the change do:
- sed –i.bak 's/foo/bar/g' *.html
- Note: each backup will be named *.html.bak
Sendmail
Make changes to the /etc/mail/sendmail.mc file, then compile with:
- m4 sendmail.mc > sendmail.cf
If you get this error: "sendmail.mc:10: m4: Cannot open /usr/share/sendmail-cf/m4/cf.m4: No such file or directory", then:
- Install sendmail-cf using: yum install sendmail-cf
Send Mail from the Command Line:
- usr/sbin/sendmail –t
- To: sysadmins@mydiego.edu
- From: ocsinfra@mydiego.edu
- Subject: OCSINFRA: Gone to Heaven
- The CPU Load on OCSINFRA has caused a FATALITY. OCSINFRA is now D.E.A.D and has Gone to Heaven
- .
..OR..
Sendmail - Configure to Send Outgoing Messages
/etc/hosts file: xxx.xxx.xxx.xxx mail_hostname
/etc/mail/sendmail.mc file: define(`SMART_HOST',`mail_hostname')
Recompile sendmail.mc: m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
Restart sendmail: service sendmail restart
Add this line to /etc/hosts.allow: sendmail : localhost : ALLOW
How To:
- Check Sendmail Process: ps -ef | grep sendmail
- How to see the mail queue: mailq
- Monitoriing Sendmail Log Activity: tailf /var/log/maillog
- Sendmail Log Rotation: vi /etc/logrotate.d/syslog
SELinux
Check SELinux Status:
Disable SELinux:
- vi /etc/sysconfig/selinux
- Change line to: SELINUX=disabled
Note: If you changed from Enabled to Disabled or vice versa, you need to restart the machine for the change to take effect.
Services
Apache = httpd
DHCP Client = dhclient
DNS Server = named
Firewall = iptables
- iptables –list
- service iptables status = shows rules
Services – updates and queries runlevel information for system services
chkconfig
List which services are available and in which runlevel they are started:
Update:
- Ex. chkconfig –-level 3 smb on|off|reset
List all services that are turned on in runlevel 5:
- chkconfig –-list | grep ‘5:on’ | sort
Delete / Remove a service from chkconfig management and any symbolic links in /etc/rc[0-6].d which pertain to it are removed:
- chkconfig –-del <service_name>
Text GUI for managing which services are started in the current runlevel, can use the –level to modify other runlevels:
Services, Start, Stop, Restart
service <service_name> start|stop|restart
- Ex. service httpd restart
To check the Status of a Service:
RHEL 7 / CentOS 7:
- Get the Status: systemctl status xxxxx.service | xxxxx
- Ex. systemctl status network.service or systemctl status network
- Restart the Service: systemctl restart xxxxx.service | xxxxx
- Start the Service: systemctl start xxxxx.service | xxxxx
- Stop the Service: systemctl stop xxxxx.service | xxxxx
SFTP (Secure File Transfer Program)
To open a secure, interactive FTP session that is encrypted: sftp user@server.com
Once authenticated, use regular FTP commands
Shell Commands: Bash, Bash Command Line Editing Commands
Bash readline:
- Move to Beginning of Line: Ctrl-a
- Move to End of Line: Ctrl-e
- Move Backward a word: Esc b
- Move Forward a Word: Esc f
- Move Backward a Character: Ctrl-b
- Move Forward a Character: Ctrl-f
- Clear the Screen, reprint the current line at the top: Ctrl-l
- Delete / Kill the text from the current cursor position to the End of the Line: Ctrl-k
- Delete / Kill backward from cursor to Beginning of the line: Ctrl-u
- Move to Previous History Command (up): Ctrl-p
- Move to Next History Command (down): Ctrl-n
- Reverse Search History (up): Ctrl-r
- Forward Search History (down): Ctrl-s
- Display your Shell Version: Ctrl-x, Ctrl-v
- Repeat last command: !!
- Terminate the command: Ctrl-c
- Delete from under the cursor: Ctrl-d
- Backspace: Ctrl-h
- Search the history backwards with multi occurrence: Ctrl-R
- Swaps last two chars in line: Ctrl-t
- Delete last word in line: Ctrl-wli>
- Move between BOL and current cursor position: Ctrl-xx
- Show possible hostname completions: Ctrl-x @
- Paste what you Cut (ctrl-k): Ctrl-y
- Suspend/ Stop the command: Ctrl-z
- Scroll Screen Up: Ctrl-PageUp
- Scroll Screen Down: Ctrl-PageDn
- Scroll Screen Up, by Line: Shift-PageUp
- Scroll Screen Down, by Line: Shift-PageDn
To Enable VI style Key Bindings: set –o vi, press Esc to activate VI style Editing
To Enable Emacs Bindings (default): set –o emacs
To list all Bindings: bind –p
Single User Mode
Edit Kernel line, add "single" at the end, boot the modified kernel line. In GRUB:
- 'e'
- select kernel line, press 'e'
- add single, ' single' at EOL
- ENTER
- 'b' to boot it
smartctl
Verify the manufacturer, model, and SMART capability, and look at the current state of health (as last recorded):
SSH - Change Terminal Title
To have your hosting provider set your linux terminal title to username@host:directory, add this to your hosted accounts ~/.bashrc:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
- Last tested on Ubuntu Mate 20.04
SSH (OpenSSH Remote Login Client)
To execute a command on a remote machine without logging into a shell prompt:
- ssh user@server.com ls /var/log
Use your OpenSSH Private Key to Login to a Server that has your Public Key (default is ~/.ssh/id_rsa):
- ssh -i /path/to/id_rsa-private-key user@server.com
SSH (Generating Authorization Key Pairs)
Starting with OpenSSH 3.0, SSH protocol 1 and 2 share these files:
- ~/.ssh/authorized_keys
- ~/.ssh/known_hosts
- /etc/ssh/ssh_known_hosts
- Note: If you want to reinstall Linux and save your generated key pairs, backup the .ssh directory in all users homes folders, reinstall, copy the directories back
Starting with OpenSSH 2.9, the default keygen uses RSA
Note: A passphrase is a string of words and characters used to authenticate a user. Passphrases differ from passwords in that you can use spaces or tabs in the passphrase. Passphrases are generally longer than passwords because they are usually phrases instead of a single word.
Generating Authorization Key Pairs – prevents having to use password each time you ssh, scp, or sftp into a remote machine
Keys MUST be generated for each user. Follow these steps as the user who wants to connect to a remote machine (for ex. If you complete these steps as root, only root will be able to use the keys):
Client (source) Machine:
- Run: ssh-keygen -b 2048 –t rsa
- Save the key to default location
- Enter passphrase, or blank for none
- Re-enter passphrase
- NOTE: The public key is now located in ~/.ssh/id_rsa.pub. The private key (identification) is now located in ~/.ssh/id_rsa
- Copy the contents of ~/.ssh/id_rsa.pub (your public key) to ~/.ssh/authorized_keys on the remote (destination) machine you want to connect to. If authorized_keys doesn’t exist, create it.
- Ex. ssh-copy-id user@123.45.56.78
- OR cat id_rsa.pub >> /root/.ssh/authorized_keys
General Process: Generate keys on the Client, Copy the client .pub key to the desired user (their .ssh/authorized_keys file) who you want to connect as on the remote server
- After generating keys, you can delete .ssh/id_rsa.pub on the client, but you cannot delete the private key (id_rsa) on the client, if you do, you cannot authenticate keylessly. If you want a different local / client user to be able to login to the remote server (as that same remote user), you can copy the other users private key to the new users .ssh/id_rsa file. Not advised though.
Using the Keys:
- Specify a different private key to login to a server that has your public key: ssh -i /path/to/id_rsa-private-key user@server.com
Getting / Comparing the Public Key from the Private Key:
- This command reads the Private Key and print the Public Key: ssh-keygen -yf /path/to/id_rsa-private-key
SSH Terminal Character Encoding
If you see characters such as: †in your SSH session, it's the terminal program's character encoding that neets to be set to UTF-8
- In PuTTY check in: Settings -> Window -> Translation
- In SecureCRT check in: Session Options -> Terminal -> Appearance -> Character encoding
SSH Daemon – sshd
Disable direct ssh Root login:
- Add: PermitRootLogin no to /etc/ssh/sshd_config
- restart sshd
Check SSL Certificate Expiration Date:
echo | openssl s_client -connect hostname.xxx.xxx:port 2>/dev/null | openssl x509 -noout -dates
Dump SSL Certificate Data:
openssl s_client -showcerts -connect hostname.xxx.xxx:port
Startup – Xwindows (Windows Startup Folder Equivalent)
To start a script or program when the user logs on using startx (KDE / GNOME) place a script here:
Ex. To Start Synergy client:
- Create synergy.sh script:
- #!/bin/sh
- /usr/bin/synergyc –daemon <server>
- chmod 755 synergy.sh
- Reboot and enjoy!
SUDO
Config File is: /etc/sudoers
Edit the Config File using visudo
- visudo uses editor stored in environment var VISUAL, can set using: export VISUAL=”pico –w”)
- To change visudo editor from nano to vim, type: sudo update-alternatives --config editor) on Ubuntu / Raspberry Pi, etc.
Create User Groups under “User Alias Specification” section:
Give Groups permissions in “User Privilege Specification” section:
Execute command as user (use users pass): sudo vi /etc/sudoers
Swap File Usage
To monitor Swap Space Usage: swapon –s
..or..: cat /proc/swaps
Syslog
To disable /var/log/messages output
- vi /etc/syslog.conf – look for line next to /var/log/messages and comment it out
- service syslog restart – for changes to take effect
SystemD
System Service Management, using the systemctl action service pattern:
- systemctl start <service> - Use it to start a service. Does not persist after reboot
- systemctl stop <service> - Use it to stop a service. Does not persist after reboot
- systemctl restart <service> - Use it to restart a service
- systemctl reload <service> - If the service supports it, it will reload the config files related to it w/o interrupting any process that is using the service
- systemctl status <service> - Shows the status of a service. Tells whether a service is currently running
- systemctl enable <service> - Turns the service on, on the next reboot or on the next start event. It persists after reboot
- systemctl disable <service> - Turns the service off on the next reboot or on the next stop event. It persists after reboot
- systemctl is-enabled <service> - Check if a service is currently configured to start or not on the next reboot
- systemctl is-active <service> - Check if a service is currently active
- systemctl show <service> - Show all the information about the service
- sudo systemctl mask <service> - Completely disable a service by linking it to /dev/null; you cannot start the service manually or enable the service
- sudo systemctl unmask <service> - Removes the link to /dev/null and restores the ability to enable and or manually start the service
Note: Systemd provides a standard process for controlling what programs run when a Linux system boots up. While systemd is compatible with SysV and Linux Standard Base (LSB) init scripts, systemd is meant to be a drop-in replacement for these older ways of getting a Linux system running.
Systemd, which was created by Red Hat's Lennart Poettering and Kay Sievers, does more than start the core programs running. It also starts a journal of system activity, the network stack, a cron-style job scheduler, user logins, and many other jobs. That may sound good to you, but some developers hate it.
System Uptime
uptime
Tail
Outputs the last part of files
-f = output appended data as the file grows; follow output
Ex. tail –f /var/dhcpd/dhcpd.leases
Tar / Archiving Files
Tar:
- NOTE: By default, tar will preserve file permissions and ownership when creating the archive. To extract file permissions and ownership, you will need to run tar as root when extracting, since changing file ownership usually requires superuser privileges.
- Compress a tar/gzipped archive: tar –czvf archive.tar.gz files
- Decompress a tar/gzipped archive: tar –xzvf archive.tar.gz - this filters .tar through gzip first
- Ex. tar –cvf mej.tar *.doc where cvf = create verbose file
Tar a Directory:
- move to a superior (parent) directory: tar -cvf mej.tar mydirectory
- To exclude a folder: tar --exclude mydirectory/logs -cvf mej.tar mydirectory
- To exclude a file pattern: tar --exclude=*.log.gz -czvf shib4x.tar.gz shibboleth-idp
UnTar:
- Extract an entire archive in current directory: tar –xvf mej.tar
- xvf = extract verbose file
- Extract specific files in archive: tar –xvf mej.tar 2.doc
- Extract specific directories in an archive (ex. Mydir1 inside of mydir):
- tar –xvvf mej.tar mydir/mydir1
- Extract the archive but strip leading path. Ex. archive begins with /public_html/myfiles/.. will produce myfiles/…
- tar -–strip-components=1 –xzvf mej.tar.gz
Append / Add files to Tar:
- tar –rvf mej.tar 5.doc where rvf = append verbose file
List Files in Tar:
- tar –tvf mej.tar where tvf = list verbose file
Backup: Compare contents of a .tar with your backup directory:
- tar –fd myhomebackupdir.tar /home/*
Backup: Easily add files not found in your backup .tar to the .tar:
- tar –rvf myhomebackupdir.tar /home/*
http://www.gnu.org/software/tar/manual/
Tar Pipe
cd <source_directory>
- tar cvf - . | (cd /<target_directory> ; tar xvf -)
Tar Pipe w/ Exclude File:
- cd <source_directory>
- create exclude.lst file to hold files / directories to exclude from taring
- echo "./mydir" or "./.myhiddendir" > exclude.lst
- create target_directory
- from the source_directory:
- tar cXvf exclude.lst - . | (cd /target_directory ; tar xvf -)
- Note: switch order matters!
Terminal Type (Checking your Terminal)
echo $TERM
Note: PuTTY uses: xterm, while others use ansi
Terminal Colors (SSH)
Change the Dark Blue directory color (XTERM color):
- vi /etc/DIR_COLORS (Search for #directory and change DIR 01;34 to DIR 01;33 (for yellow instead of blue)
- Attribute Colors: 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
- Background Colors: 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
- Text Colors: 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
- Examples: .tar 47;35 (magenta text on white background) DIR 00;33 (bright/bold yellow)
Note: then logoff and logon again. If that doesn’t work, also edit: /etc/DIR_COLORS.xterm and try again
Text File Conversions (Unix to Windows, Windows to Unix)
Convert a text file from Windows/DOS to UNIX:
- tr –d '\015' < winformat.txt > unixformat.txt
Convert a text file from UNIX to Windows/DOS:
- sed –d 's/$/\r/' unixformat.txt > winformat.txt
Time (Benchmarking tool)
Runs the specified program command with arguments and upon finishing, time writes a message to STDOUT giving timing statistics about the program.
1. Prints the elapsed real time between invocation & termination
2. Prints the user CPU time
3. Prints the system CPU time
time traceroute www.google.com
Time Server – Manually set the host clock via time server
ntpdate time.windows.com
Query TS, doesn’t set clock: ntpdate –q <timeserver>
Query the hosts CMOS clock: hwclock –show
Top – Display Linux Tasks
To sort by CPU (or other Field): Shift+f (or Shift+o), then K for %CPU, P makes Top order by CPU, W saves the configuration
Note: in RHEL 7 (procps-ng version 3.3.10), you can use the arrow keys to choose sort fields when in field management mode.
When Viewing Top in RHEL 7:
- Arrow Up / Down: Moves the process list up or down
- Arrow Left / Right: Moves the process columns left or right
Users
users = list current users
who = displays who is on the system
w = displays who is on the system and what they are doing
last = indicates last logins of users and ttys
Undo typing in shell / terminal (deletes entire line)
Ctrl-u
Uniq – Unique
Removing Duplicate Lines with: uniq
- cat <filewithduplicates> | uniq
Display only the Unique Lines
- cat <filewithduplicates> | uniq -u
Display only the Duplicate Lines
- cat <filewithduplicates> | uniq -d
Display Number (count) of Unique Lines
- cat <filewithduplicates> | uniq –uc
Display Number (count) of Duplicate Lines
- cat <filewithduplicates> | uniq –dc
Display Unique Lines in messages, skip field 3 (i.e. ignore unique timestamp field)
- uniq –f 3 /var/log/messages
Display Unique Lines in messages, skip field 3 and 9 more characters from there (i.e. ignore unique timestamp field + 9 characters)
- uniq –f 3 –s 9 /var/log/messages
User Administration (Add / Delete / Modify / Change password / Switch)
Add a new user: useradd
- –c Add a comment (any string for a short description of the login, ex. Full Name of user)
- –d home directory
- –s starting shell / program
- –p password
- –g primary group assigned to the user
- –G other groups the user belongs to
- –m create the user’s home directory
- ex. useradd –m –c "Homer Simpson" hsimpson -p Password
- ex. useradd –gusers –Gmgmt –s/bin/ –pxxxx –d/home/roger –m roger
Modify a user: usermod
- -a (append) –d (homedir), -s (login shell), -p (password), -g (initial login group), -G (supplementary groups)
- ex. usermod –G others roger
- Add user to the sudo group: usermod –aG sudo roger
Rename a user: usermod –l
- ex. usermod –l <newUsername> <oldUsername>
Delete a user: userdel
- –r remove home directory
- ex. userdel –r roger
User’s password: passwd
- option: user’s name
- ex. passwd roger
Force User to Change Password at Next Login:
Switch to a Users: su
Add a group: groupadd
Delete a group: groupdel
User / Group File Information:
- User names and primary groups are stored in /etc/passwd
- Passwords for each user is stored in /etc/shadow
- only edit this file by using the passwd command
- Group information is stored in /etc/group
- When a new user is created, the default files and directories that are created are stored in /etc/skel
- You can modify this directory to fit your needs
- Modifications only affect new users
Vi (vim) – text editor
VIM Complete
Hilight / Visual Mode:
- Cut = c (c$ to end of line)
- Copy = y (y$ to end of line)
- Paste = p (P = before cursor)
- Delete = d (d$ to end of line)
- V = visual Line mode
- Ctrl-V = visual Block mode
As you Type in Insert Mode:
- Back Space / Erase = Ctrl-H
- Line Kill = Ctrl-U
- Word Kill = Ctrl-W
Insert Mode:
- a = Append, moves cursor 1 position right before inserting (A = appends at end of line)
- o = Inserts a blank line under (O = above) current cursor position
Command Mode:
- Delete Everything from your current line to end: dG
- Delete Everything from your current line to the TOP of the file: dgg
- Delete a Character = x
- Delete a Word = dw
- Delete a Line = dd
- Undo a command = u
- Save the current file As another file, and begin editing that file = :sav <another_file>
- Save the current file contents to another file, continuing editing current file = :w <another_file>
- Save certain lines = :1,10w stuff.txt
- Status line = :f or Ctrl-G
- Move to Beginning of File (BOF) = 1G
- Move to End of File (EOF) = G
- Move to top of screen = H
- Move to middle of screen = M
- Move to lower portion of screen = L
- Move forward (down) a page = Ctrl-F
- Move backward (up) a page = Ctrl-B
- Move to Beg of Line = 0 (zero)
- Move to End of Line = $
- Move to First Line of the file = 1G
- Move to Last Line of the File = G
- Move to Line 10 = :10 or 10G
- Read a file = :r stuff.txt
- Scroll Down Half a Window = Ctrl-D
- Scroll Up Half a Window = Ctrl-U
- Execute command = :! Ls
- Get Version of VI = :ver
- Word Count = :%s///gn
Shell
Settings:
- Show Line Numbers = :set number
- No Line Numbers = :set nonumber
- Show Status Line = :set laststatus=2
- Stop Status Line = :set laststatus=0
- Show Special Characters = :set list
- Stop Special Characters = :set nolist
Windowing:
- Split Window = :sp
- Move up a window = Ctrl-W j
- Move down a window = Ctrl-W k
- Highlight Search Option: :set hlsearch
- Incremental Searches: :set incsearch
- Redraw Screen = Ctrl-L
Search / Replace:
- Delete all ^M = :%s/Ctrl-VCtrl-M//g
- CaSE Sensitivity: /\Csmith will find "Smith", "Smithsonian", etc.
- CaSE InSensitivity: /\cjohn will find "john", "John", "JOHN", "Johnson”, "johnSON", etc.
Cursor Position:
- Store current position in the 't' mark = mt
- Go to the line stored in the 't' mark : 't
- Note: 't' can be any character, think of it as a location buffer. Ex ma, then 'a
Other:
- You Mistakenly Edit a ReadOnly File but need to save it now: :w !sudo tee % >/dev/null
- ~/.vimrc comment line, use 1 double-quote followed by comment text = " Comment text
- Change background color to black if it's grey, while inside vi: :colo torte
- Turn syntax highlighting on, while inside vi: :syn on
VMSTAT (Reports Virtual Memory Stats)
Display a Quick Summary: vmstat –s
Display in 1 second intervals, 5 times: vmstat 1 5
VNC Server
On the Linux Server:
- Configure Firewall
- Open Port: 59xx, where xx = the display number. Default Port is 5901
To start KDE or Gnome in VNC:
- Edit /root/.vnc/xstartup
- Uncomment 2 top lines
- Add at end: "startx &" for gnome or "startkde &" for KDE
- vncserver
- set password
- if you need to change it use: vncpasswd
- if you want to delete it: rm /root/.vnc/passwd
- Note the Display number (:1)
On VNC Client:
- <vncserverIP:display number>
- To Kill a VNC desktop that was started with vncserver (this kills the Xvnc process)
- vncserver –kill:display#
- Ex: vncserver –kill :1
Install VNC Server on Ubuntu MATE using Desktop Display:
- 1. Install Ubuntu Mate 18.04 LTS
- 2. Install VNC Server: sudo apt-get install vnc4server
- 3. Start the Server: vncserver :1
- 4. Kill the Server: vncserver -kill :1
- 5. Edit the generated configuration file:
- 5.1 sudo vi ~/.vnc/xstartup, add these 2 lines at the bottom of the file:
- 5.2 unset DBUS_SESSION_BUS_ADDRESS
- 5.3 mate-session
- 6. Start the server: x0vncserver -passwordfile ~/.vnc/passwd -display :0
- 6.1 To start the server in the background: x0vncserver -passwordfile ~/.vnc/passwd -display :0 >/dev/null 2>&1 &
- 7. Check if your server is running: fuser -vn tcp 5900
- 8. Connect from Windows or other OS by using: VNC Viewer (RealVNC)
- 9. To stop the server, find the x0vncserve process ID, then kill -9 <pid>
- Note: x0vncserver will use the screen geometry of the actual display.
- Note: x0vncserver is supplied w/ vnc4server package
VSFTP
By default, vsftpd displays directory listings in GMT, to set this to list files in your local time, use:
- echo "use_localtime=YES" >> /etc/vsftpd/vsftpd.conf
- service vsftpd restart
Wall (Send a Message to Everybody’s Terminal)
To send a broadcast message to everyone’s terminal: wall –n message ctrl-D
Without –n the banner reads: ex.: "Broadcast message from root (pts/2) (Sat Jul 15 10:11:58 2006):"
With –n the banner reads : "Remote broadcast message (Sat Jul 15 10:12:51 2006):"
Watch
Executes a program periodically, showing output fullscreen
To watch the contents of a directory change every 15 seconds:
Who is logged in and What they are doing
w
Wireless configuration
iwconfig
Wireless Monitoring:
- Show the Link Quality, Signal Level and Noise Level: iwconfig wlan0
- Show the same info as above, in different format: cat /proc/net/wireless
- Continuously monitor the Wireless Connection: watch -n 1 cat /proc/net/wireless
- To see the associated SSID: iwgetid
- To see more detailed wireless information: iwlist
Write (Send a Message to another user)
Usage: write user [ttyname]: write root pts/2 message
Your Identity, Your Group, etc.
id
Yum
Exclude Package(s) from Updating: yum update –exclude=389-*
List Installed Packages: yum list installed
Install packages automatically without asking any confirmation: yum –y install updates
Remove a Package: yum remove package_name
Update a Package: yum update package_name
Search for a Specific Package in the Repository: yum list package_name
Search for a Package, w/o knowing Exact Name: yum search package
List Information about a Package: yum info package
Find which Package a Specific File belongs to: Ex. yum provides /etc/httpd/coonf/httpd.conf
List Enabled Package Repositories in your System: yum repolist
List all Enabled and Disabled Repositories in your System: yum repolist all
Install a Package from a Specific Repository: Ex. yum –-enablerepo=epel install phpmyadmin
Temporarily allow a repo and install php from it: Ex.yum –-enablerepo=remi install php
Temporarily disable a repo: Ex. yum –-disablerepo=epel-testing
Permanently enable a repo. Here’s a remi example::
- vi /etc/yum.repos.d/remi.repo
- Change enabled=0 to enabled=1
Clean the Yum Cache: yum clean all
View Yum History – List all Yum Operations
- yum history (works w/ RHEL 6+)
- or cat /var/log/yum.log (RHEL 5+, 6+)
View Update History Information by ID: yum history info <ID>
Undo / Rollback a Transaction ID: yum history undo <ID>
VMWare: Extending a logical volume in a virtual machine running Red Hat or Cent OS
LVM – Expanding the Disk Size in Vmware:
- Expand the drive size (Disk Capacity) in VMWare
- Boot the OS, ID the device name and confirm the new disk size: fdisk –l (/dev/sda by default will be expanded)
- Create a new Primary Partition: fdisk /dev/sda
- p (you’ll see all the existing partitions, not the new space yet)
- n (create a new primary ookingn)
- p (it will auto-select the partition for you, ex. 4)
- Enter (default 1st cylinder)
- Enter (default last cylinder)
- p (now you’ll see the new space as the new partition, ex. /dev/sda4)
- t to change system’s partition ID to LVM
- <new_partition_number>, ex. 4
- 8e to change the Hex Code of the partition to Linux LVM
- w to Wrtie change to the partition table
- Reatart the VM
- fdisk –l (check to see the new partition, ex. /dev/sda4 is LVM w/ Id 8e)
- Convert the new partition to a physical volume: pvcreate /dev/sda4
- Extend the volume with the new partition / Physical volume: vgextend VolGroup00 /dev/sda4
- Confirm: vgdisplay – look for VG Size
- Verify how many physical extents are available to the VG by ooking at the "Free PE / Size" line of the vgdisplay command
- Extend the Logical Volume in order to use the new underlying storage we expanded: lvextend –L+<#G> /dev/VolGroup00/LogVol00 – where #G is size found in Step 9. OR extend by the amount of free space on the volume: lvextend /dev/VolGroup00/LogVol00 /dev/sda4
- Expand the ext3 filesystem online, inside the Logical Volume: resize2fs /dev/VolGroup00/LogVol00
- Verify extra space: df –h /
zip
Test the integrity of a zip file (verify contents): unzip -t <filename>.zip
More Unix Commands
UNIX COMMANDS continued…
Top