Some Computer Hints


Below I give some computer related hints. I hope they prove useful to you. If you have any questions, please feel free to mail me.

  1. UNIX and Shell: System Commands · Shell
  2. HP-UX: Startup · System Management · Patch Management · Useful Utilities · Others
  3. Linux: General · Red Hat Linux · Bash
  4. Perl
  5. C Programming Language
  6. Windows: Registry Settings · Daylight Saving Time Adjustment · Others

Note: Improper or incorrect use of the commands and procedures given in this page may result in data loss or damages in your operating system. Please be careful especially when you run these commands on your system with administrative privileges.


1. UNIX AND SHELL

See also Rosetta Stone for UNIX for a chart listing command equivalents of various UNIX flavors.

System Commands

• Use [] in grep to find a process and not include the grep command itself when you pipe ps -ef output to grep:

For example:

ps -ef | grep inet[d]

will normally display one line like this:

    root   938     1  0  Dec  6  ?         0:36 /usr/sbin/inetd

but, just:

ps -ef | grep inetd

will generally display the grep process also:

    root   938     1  0  Dec  6  ?         0:36 /usr/sbin/inetd
    root  5494  5398  0 18:45:05 pts/5     0:00 grep inetd

Shell (POSIX, ksh)

• Use the IFS shell variable to split a line into fields:

grep root /etc/passwd | IFS=: read user x1 uid gid x2 home shell
print $uid $home

• To send all output (stdout and stderr) generated by a command to the same file use: command >file 2>&1. To send all output (stdout and stderr) generated by a command to a file and to the terminal (stdout) use: command 2>&1 | tee file.

• The following String Substitution Operators can be used:

${varname:-value}
Return value of varname if it exists and it is not null; otherwise return value.
${varname:=value}
Return value of varname if it exists and it is not null; otherwise set varname to value and return value.
${varname:?message}
Return value of varname if it exists and it is not null; otherwise print varname: message and abort current command or script. Default message is parameter null or not set.
${varname:+value}
Return value, if varname exists and it is not null; otherwise return null.

Note that if the colon (:) is omitted, then only existence test is done and varname is not tested for nullness.

• The following Pattern-matching Operators can be used:

${varname#pattern}
If pattern matches the beginning of varname's value, delete the shortest part that mathes and return the rest.
${varname##pattern}
If pattern matches the beginning of varname's value, delete the longest part that mathes and return the rest.
${varname%pattern}
If pattern matches the end of varname's value, delete the shortest part that mathes and return the rest.
${varname%%pattern}
If pattern matches the end of varname's value, delete the longest part that mathes and return the rest.

Examples:

var=variable
print ${var#*a}
riable
print ${var##*a}
ble
print ${var%a*}
vari
print ${var%%a*}
v

• Use the command expr index string string2 to display the numerical position in string of first character in string2 that matches.

• The command expr substr string position length extracts length characters of substring from string starting at position.

• An exec >filename command redirects stdout to a designated file. This sends all command output that would normally go to stdout to that file. To resume output enter exec >/dev/tty.


2. HP-UX

Startup

• Put startup scripts for CDE in /etc/dt/config/Xsession.d.

• To activate command history control, add the following lines to .kshrc:

export EDITOR=vi
export HISTFILE=$HOME/.sh_history

include the following line in $HOME/.profile:

export ENV=$HOME/.kshrc

and add the following line to $HOME/.Xdefaults:

*loginShell: True

System Management

• System serial number can be found in the file /var/opt/ignite/local/manifest/manifest.seed or (on some systems) can be obtained as follows:

echo 'selclass qualifier system;info;wait;infolog' | cstm | grep "System Serial Number"

• To find out the CPU speed of your system execute:

echo itick_per_usec/D | adb -k /stand/vmunix /dev/kmem

You can use machinfo | grep speed on Itanium systems.

• To find out the number of CPUs on your system execute:

echo runningprocs/D | adb -k /stand/vmunix /dev/mem

or use the top command.

• To find the total amount of physical memory configured on your system, run one of the commands:

echo 'selclass qualifier memory;info;wait;infolog' | cstm | grep 'Total Configured'
dmesg | grep Physical
grep Physical /var/adm/syslog/syslog.log

• To see the exact configuration of the memory chips in your system, try echo 'selclass qualifier memory;info;wait;infolog' | cstm.

• To find out your operating system version use uname -a or something like this: swlist -l product | grep "Operating System".

• The command model or getconf MACHINE_MODEL will return the hardware model of your system.

• To find whether your operating system is 32-bit or 64-bit, try the commands getconf KERNEL_BITS or file /stand/vmunix. To determine whether your hardware is 64-bit capable or not, run getconf HW_32_64_CAPABLE (1 means 64-bit only, 2 means 32-bit only, and 3 means 32-bit and 64-bit) or run getconf HW_CPU_SUPP_BITS. Note that, even if your system is 64-bit capable, it may not be supported by HP for 64-bit operation.

• To display current kernel configuration (drivers, tunable parameters, etc.) use the command /usr/lbin/sysadm/get_sysfile /stand/vmunix. The output should be the same as the contents of the file /stand/system.

• To display and modify variables (like the primary and alternate boot path) in stable storage use the command setboot.

• Startup configurations for network cards reside on the files /etc/rc.config.d/hp*conf. Use sam or smh to configure your network cards. The lanscan command will list the network cards on your system along with their name (like lan0). To see the current speed of a network card use lanadmin -x 0 where 0 is the number coming after lan. To change the speed execute lanadmin -X speed 0 where speed is one of 100HD, 100FD, 10HD or 10FD and 0 is the number coming after lan in your network card name.

• To verify LAN connectivity with link-level loopback (i.e., below IP level) enter linkloop -i 0 remote_station_addr where 0 is the number coming after lan in your network card name and remote_station_addr is the "MAC address" of the remote system's network card (which can be found using the command lanscan there). linkloop is similar to the ping command which is used at IP level.

• To delete removed hardware (shown as NO_HW in ioscan output) execute rmsf -H HW_Path, where HW_Path is the path shown at ioscan output.

• The following procedure can be used to change the order (i.e., instance number) of devices. Changing the instance number affects the device name (like the x in /dev/lanx, /dev/rmt/x... or /dev/dsk/cxt...). This way you can reorder the devices and make for example two systems "similar" (in other words, having the same device names).

· Create a temporary file on / containing current configuration:

ioscan -kf | grep -e INTERFACE -e DEVICE | grep -v target | \
 awk '{printf "%s %s %s\n",$3,$1,$2}' >/infile

· Edit /infile and change instance numbers (last column) as you wish, but avoid duplication of them on two devices.

· Rename current ioconfig files and reboot system:

mv /etc/ioconfig /etc/ioconfig.save
mv /stand/ioconfig /stand/ioconfig.save
shutdown -ry 0

· Interrupt boot process, and boot in single user mode. Due to the missing ioconfig files, the system will come to an ioinitrc prompt.

· Recreate new ioconfig files from scratch: /sbin/ioinit -c and press Ctrl-D to continue boot process.

· Make sure the system is booted in single user mode: init s.

· Apply the ioconfig change with your prepared infile: ioinit -f /infile -r.

· The system will reboot using information in /infile with the new instance numbers.

· If you want, you can remove old device files using for example: rmsf /dev/rmt/*. And then re-create new device files using: insf -e.

· Check device names with lssf and instance numbers with ioscan.

• To get information on current states of all N_ports connected to a TACHYON Fibre Channel host bus adapter, try /opt/fcms/bin/fcmsutil /dev/td2 get remote all.

• To obtain a network trace on the current system use the following method:

Turn on trace with the following command:

nettl -tn pduin pduout -s 1024 -e ns_ls_tcp -f /tmp/nettrace -tm 99999

Turn off trace using:

nettl -tf -e ns_ls_tcp

Finally filter and convert the trace to readable format:

netfmt -F -l -N -f /tmp/nettrace.TRC0 -c /tmp/filter.txt >/tmp/out.txt

Here the file filter.txt can contain lines like the following to select "remote login" (tcp port number 513) communication with remote system having IP 10.16.74.3 only:

filter tcp_sport 513
filter tcp_dport 513
filter ip_saddr 10.16.74.3
filter ip_daddr 10.16.74.3

• To find the process which uses the most CPU during the last scheduling interval enter:

UNIX95=  /bin/ps -eo pcpu,pid,comm | sort -n | tail -1

• For simple disk I/O performance monitoring use commands like:

iostat 2 10 | grep 'c0t5d0' | grep -v '   0   '
sar -d 2 10 | grep -e Aver -e 'c0t5d0'

• To disable dtlogin (CDE) so nobody can login through X on the system, comment out the line DESKTOP=CDE in file /etc/rc.config.d/desktop and run the command /sbin/init.d/dtlogin.rc stop.

• To disable services provided through inetd (e.g., telnet, ftp etc.) do modifications on files /etc/inetd.conf and/or /var/adm/inetd.sec.

• To see if your system rebooted or paniced, type tail /etc/shutdownlog.


Patch Management

• To check whether swinstall installed and configured all packages successfully run the command

swlist -l fileset -a state | grep -v configured | grep -v '^#'

It should display nothing.

• You can use the show_patches to display a patch list. For example, the command show_patches -s shows which patches have been superseded.

• To save disk space on the volume where /var/adm/sw resides, you can "commit" all installed patches. First run the following commands and record their outputs:

swlist -l patch \*.\*,c=patch | grep "superseded *$" | wc -l
swlist -l patch \*.\*,c=patch | grep "committed *$" | wc -l
swlist -l patch \*.\*,c=patch | grep "applied *$" | wc -l

then use either one of the following commands

swmodify -x patch_commit=true "PH??_?????.*"
swmodify -x patch_commit=true \*

to commit all patches. Finally run the above swlist commands once more and compare the results.

• You can use also the cleanup -c 1 command to commit all superseded patches.

• If you want to add a reboot script and customize the reboot process of the swinstall command (for the cases it automatically reboots the system after patch installation), add the line swagent.reboot_cmd = your_reboot_script to the end of the file /var/adm/sw/defaults. The following are additional recommended options to be added to this file:

swinstall.retry_rpc = 9
swinstall.rpc_timeout = 5
swinstall.agent_timeout_minutes = 100
swinstall.polling_interval = 60

Useful Utilities

• The lsof command can be used to list files, sockets, etc opened by processes. This is a very handy command.

• The pstre command can be used to get a graphical list of processes of a "process branch." For example:

pstre -p 21476

Others

• To copy all files from /source directory to /dest directory use the following commands:

cd /source
find . -depth -xdev | cpio -paduxvlm /dest

• To copy files to a remote system called dest_sys, use this:

cd /source
(find . -depth -xdev | cpio -coax) | remsh dest_sys "cd /dest; cpio -icdmula"

• To use compression while copying a large file to another system:

gzip -vc file | remsh dest_sys "gunzip - >/dest_dir/file"

• Use the mt offl command to unload a tape from drive /dev/rmt/0m. There is no reverse command for this!


3. LINUX

General

• The grep -w command form matches whole words only.

• To copy all files from /source directory to /dest directory use the following commands:

cd /source
find . -xdev | cpio -pduvlm /dest
cd /source
find . -type d -exec chmod --reference='{}' /dest/'{}' \;
find . -type d -exec chown --reference='{}' /dest/'{}' \;

• The shred command can be used to securely erase a file by overwriting it multiple times with random bit patterns before deleting it.

strace is the Linux equivalent of truss, i.e., a diagnostic and debugging tool for tracing system calls and signals. The simplest way of invoking it is strace command.

• Adding an appropriate entry to /etc/logrotate.conf makes it possible to manage personal log files, as well as system-wide ones.

tac is the inverse of cat, listing a file backwards from its end. rev reverses each line of a file and outputs to stdout; this is not the same effect as tac, as it preserves the order of the lines, but flips each one around.

• The pidof command identifies the process ID (PID) of a running process. For example, /sbin/pidof crond will return the process ID of crond (cron daemon). Note that, pidof resides under the /sbin directory.

dumpe2fs dumps to stdout very verbose filesystem information. For example, run /sbin/dumpe2fs /dev/hda1. Note that, dumpe2fs resides under the /sbin directory.


Red Hat Linux

• Below are given some system management commands. Most are graphical. On old versions of Red Hat Linux replace the system prefix with redhat.

setup General Setup (TUI)
hwbrowser Hardware Browser
system-config-authentication Authentication Configuration
authconfig Authentication Configuration (TUI)
system-config-boot Boot Loader Configuration
system-config-date
system-config-time
Time and Date Properties
system-config-display Display Settings
system-config-httpd HTTP Configuration
system-config-keyboard Keyboard Configuration
system-config-language Language Configuration
system-config-lvm Logical Volume Management
system-config-mouse Mouse Configuration
system-config-network Network Configuration
system-config-network-cmd Network Configuration (command-line)
system-config-network-druid Network Hardware Configuration
system-control-network Network Device Control
system-config-nfs NFS Server Configuration
system-config-packages Package Management
system-config-printer Printer Configuration
system-config-printer-tui Printer Configuration (TUI)
system-config-rootpassword Root Password Entry
system-config-samba Samba Server Configuration
system-config-securitylevel Security Level ("firewall") Configuration
system-config-securitylevel-tui Security Level ("firewall") Configuration (TUI)
system-config-services Services (xinetd & init.d) Configuration
system-config-soundcard Audio Devices Configuration
system-config-users User Manager
system-logviewer Log Viewer
gnome-system-monitor GNOME System Monitor
mkbootdisk Create a boot disk (command-line)

• To display Red Hat Release use cat /etc/redhat-release.

• To make updates from web run up2date.

• To list installed packages enter rpm -qa.

• To display all kernel parameters execute /sbin/sysctl -a. To make kernel parameter changes (permanently) edit /etc/sysctl.conf file.

• For hardware information use lspci -vv.

• To see your ethernet interface speed use a command like mii-tool -v eth0.

• Important system information can be obtained from the "files" under /proc/ directory. For example enter cat /proc/meminfo for current memory usage information; or cat /proc/swaps for a list of swap devices. As another example, the file /proc/bus/usb/devices contains information about the USB ports on the system. For example, Spd=12 indicates USB 1.1 ports, while Spd=480 indicates USB 2.0 ports.

• Disk information can be obtained with fdisk -l.

• To get hardware disk information try the commands smartctl -a /dev/hda or hdparm -iv /dev/hda.

• For file system check use the command e2fsck -cttv /dev/hdxy.

• To instal GRUB on first disk enter /sbin/grub-install --recheck /dev/hda.

• To disable Ctrl+Alt+Del combination on the console edit the /etc/inittab file, change the lines:

# Trap CTRL-ALT-DELETE
ca::ctrlaltdel:/sbin/shutdown -t3 -r now

to

# Disable CTRL-ALT-DELETE
ca::ctrlaltdel:/bin/echo "<ctrl><alt><del> disabled"

and enter the command kill -HUP 1 or init q.

• To check service status use service --status-all. To restart a service (for example, xinetd) enter /sbin/service xinetd restart.

• To check whether daemons are enabled or not (at specific runlevels) execute chkconfig --list. For example: chkconfig --list | grep -e http -e smb -e mysql. To enable a service at a specific level, (for example http) run chkconfig --level 5 httpd on. The /etc/sysconfig/ directory contains service parameter files.

• To mount a Windows share (using Samba) enter the command mount -t smbfs -o username=domain\\user //computer/share /localdirectory.

• To allow root access for rlogin, rsh, and rexec add the following lines to /etc/securetty:

rexec
rsh
rlogin

• To configure sendmail edit /etc/mail/sendmail.mc and execute make -C /etc/mail. Also edit /etc/aliases and run newaliases.

• To make your system an NTP client, add the following lines to /etc/ntp.conf:

server tick.usno.navy.mil
restrict 192.5.41.40 mask 255.255.255.255 nomodify notrap noquery

Additional NTP servers may be added. The make your system an NTP server, add the following lines to /etc/ntp.conf:

restrict 10.0.0.0 mask 255.0.0.0 notrust nomodify notrap nopeer

assuming your network has the following addresses: 10.*.*.*. You can restart ntpd using the command service ntpd restart. To view the status of your NTP server connections run ntpq -c peers.

• To enable XDMCP on your system, set Enable=true under section [xdmcp] in file /etc/X11/gdm/gdm.conf and then run gdm-restart. See http://www.netsarang.com/products/xmg_faq.html.


Bash

• There is an important difference between Bash and POSIX Shell. The commands:

grep root /etc/passwd | IFS=: read user x1 uid gid x2 home shell
echo $uid $home

do not produce the desired output. The read command runs in a subshell and the values it reads are lost when we come to the echo command. Solutions to this problem are as follows:

{
IFS=: read user x1 uid gid x2 home shell
} <<EOT
$(grep root /etc/passwd)
EOT

or

{ IFS=: read user x1 uid gid x2 home shell; } <<<$(grep root /etc/passwd)

• The command command &>filename redirects both the stdout and the stderr of command to filename.

• Use the -e option with echo to print escaped characters. For example, echo -e "\v\v\v\v" prints vertical tabs.

• The following String Substitution Operators can only be used in Bash:

${varname:position:length}
Extract length characters of substring from the value of varname starting at position. 0 is the first character position.
${varname/substring/replacement}
Replace first match of substring with replacement.
${varname//substring/replacement}
Replace all matches of substring with replacement.
${varname/#substring/replacement}
If substring matches front end of the value of varname, substitute replacement for substring.
${varname/%substring/replacement}
If substring matches back end of the value of varname, substitute replacement for substring.

• The /dev/urandom device-file provides a means of generating much more "random" pseudorandom numbers than the $RANDOM variable.

• To do random I/O in Bash, in other words to write at a specified place in a file, use something like in the following example:

echo 1234567890 >File   # Write string to "File"
exec 3<> File           # Open "File" and assign fd 3 to it
read -n 4 <&3           # Read only 4 characters
echo -n . >&3           # Write a decimal point there (on 5th character)
exec 3>&-               # Close fd 3.
cat File                # will return "1234.67890"

• You can use process substitution to eliminate the need of saving intermediate command outputs to temporary files. For example, to compare the contents of two directories (to see which filenames are in one, but not the other) execute diff <(ls first_directory) <(ls second_directory).

• You can use the "special device directory" /dev/tcp/ in Bash to do socket I/O. For example, to get current time from a time server (e.g. time.nist.gov) using "daytime" port (13) run cat </dev/tcp/time.nist.gov/13. To download a URL (e.g. this document) do this:

exec 5<>/dev/tcp/www.kadifeli.com/80
echo -e "GET http://www.kadifeli.com/fedon/hint.htm HTTP/1.0\n" >&5
cat <&5

4. PERL

• Use the following command to find the "age" of a file:

perl -e '$mtime = (stat($ARGV[0]))[9];
 $age = ($mtime) ? time - $mtime : -1;
 print "$age\n";' file_name

For example:

perl -e '$mtime = (stat($ARGV[0]))[9];
 $age = ($mtime) ? time - $mtime : -1;
 print "$age\n";' /etc/passwd

will return the number of seconds passed since /etc/passwd was updated.


• For more examples go to my Some Useful Perl Scripts page.


5. C PROGRAMMING LANGUAGE

Coming soon! ;)


6. WINDOWS

Registry Settings

WARNING: The following hints suggest some updates to your Windows Registry. If you make a mistake, you may damage your Windows. So, do not forget to back up your Registry before proceeding. I accept no responsibility!

• If you set the File Name Completion Character in Registry to Tab (whose decimal ASCII code is 9) you can enter the first few letters of a file or directory name in Windows Command Prompt (cmd.exe) and press Tab key to cycle through all file or directory names starting with these letters:

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009

• For security reasons, if you do want the last entered user name to be displayed in the Windows logon dialog box, set:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"DontDisplayLastUserName"="1"

• To disable Auto Insert Notification for CD-ROMs inserted into a drive, set:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Cdrom]
"AutoRun"=dword:00000000

• Suppose you are in Windows Explorer on a specific directory and you want to start Windows Command Prompt (cmd.exe) and go immediately to this directory. If you add the following into your Registry, you can right click on a directory and select Command Prompt Here from the pop-up menu:

[HKEY_CLASSES_ROOT\Folder\shell\DosHere]
@="Command &Prompt Here"
[HKEY_CLASSES_ROOT\Folder\shell\DosHere\command]
@="C:\\Windows\\System32\\cmd.exe"

• For security reasons, if you want to remove Windows Page File at shutdown, set:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management]
"ClearPageFileAtShutdown"=dword:00000001

• If you want to change the default application installation directory from C:\Program Files to, say something like D:\opt, set:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion]
"ProgramFilesDir"="D:\\opt"

• The display of xbitmaps is disabled in Internet Explorer SP2. To enable the display, set:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Security]
"BlockXBM"=dword:00000000

• Windows Remote Desktop is used to connect a Windows computer to another Windows computer. The default listening port is 3389 (hexadecimal 0D3D). To change this to say 1234 (hexadecimal 04D2), set:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp]
"PortNumber"=dword:000004D2

Daylight Saving Time Adjustment (for Old Versions of Windows)

• In most European countries, the day of switching from daylight saving time (DST) to normal time has changed. Before 1996, this was done on the last Sunday of September. However, since 1996, this is being done on the last Sunday of October. Some Windows versions still adjust the clock on the last Sunday of September. To correct this, some modifications in the Windows registry need to be done.

Below I give a procedure of how to do this for the time zone used in Turkey. Time zone for Turkey is specified by selecting "(GMT+02:00) Athens, Helsinki, Istanbul" and checking the "Automatically adjust clock for daylight saving changes" checkbox in the Time Zone tab of Date/Time Properties applet in Windows 95 Control Panel.

To shift the last day of DST from September to October you need to modify the binary value of key TZI in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones\GFT (for Windows 95) or HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\GFT Standard Time (for Windows NT 4.0) branch of your registry as follows:

USUAL WARNING: DO NOT FORGET TO BACK UP YOUR REGISTRY!!! I accept no responsibility!

0000   88 FF FF FF 00 00 00 00 
0008   C4 FF FF FF 00 00 0A 00
0010   00 00 05 00 03 00 00 00
0018   00 00 00 00 00 00 03 00
0020   00 00 05 00 02 00 00 00
0028   00 00 00 00

For reference, I give the exported list of all the keys in the related branch of my (Windows 95) registry below:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones\GFT]
"Display"="(GMT+02:00) Athens, Helsinki, Istanbul"
"Dlt"="GFT Daylight Time"
"Std"="GFT Standard Time"
"TZI"=hex:88,ff,ff,ff,00,00,00,00,c4,ff,ff,ff,00,00,0a,00,00,00,05,00,03,00,00,\ 
  00,00,00,00,00,00,00,03,00,00,00,05,00,02,00,00,00,00,00,00,00
"MapID"="-1,67"

After you do the registry update, you will need to reboot your computer and reselect the modified time zone from the Control Panel's Date/Time application to make sure that your computer works properly and the changes took effect. You can test the change by running a Perl script given in my Perl Scripts page.

Note that, the for the years before 1996, the day of switching from DST to normal time should be last Sunday of September and not of October; however as far as I know, there is no way to specify such historical time zone information in the Windows registry.


Others

• If you get the error message Windows Update cannot continue because a required service application is disabled, check that the service named Automatic Updates is enabled and also it is set to Automatic.

• If you want to add UNIX-like features to your Windows system, consider installing Cygwin. It is free, it contains many UNIX tools, it provides a substantial Linux API functionality and a GNU development and runtime environment.


© October 1998 - December 2007, Fedon Kadifeli.