2007/09/27

PostgreSQL Tips and Tricks


# Log in to a postgreSQL database
psql -U username dbname

# Get list of databases.
SELECT datname FROM pg_database;
# or
\l
# or
psql -l

# Get size of tables, sorted in descending order.
SELECT relname, relpages,reltuples FROM pg_class ORDER BY relpages DESC;

# Show tables in a database.
select * from information_schema.tables where table_schema='public' and table_type='BASE TABLE';
# or
\dt

# Show structure of a table.
\d tablename

psql Commands

General

\c[onnect] [DBNAME|- [USER]]connect to new database (currently "dfdata")
\cd [DIR]change the current working directory
\copyrightshow PostgreSQL usage and distribution terms
\encoding [ENCODING]show or set client encoding
\h [NAME]help on syntax of SQL commands, * for all commands
\qquit psql
\set [NAME [VALUE]]set internal variable, or list all if no parameters
\timingtoggle timing of commands (currently off)
\unset NAMEunset (delete) internal variable
\! [COMMAND]execute command in shell or start interactive shell

Query Buffer

\e [FILE]edit the query buffer (or file) with external editor
\g [FILE]send query buffer to server (and results to file or pipe)
\pshow the contents of the query buffer
\rreset (clear) the query buffer
\s [FILE]display history or save it to file
\w FILEwrite query buffer to file

Input/Output

\echo [STRING]write string to standard output
\i FILEexecute commands from file
\o [FILE]send all query results to file or |pipe
\qecho [STRING]write string to query output stream (see \o)

Informational||

\d [NAME]describe table, index, sequence, or view
\d{t|i|s|v|S} [PATTERN] (add "+" for more detail)list tables/indexes/sequences/views/system tables
\da [PATTERN]list aggregate functions
\db [PATTERN]list tablespaces (add "+" for more detail)
\dc [PATTERN]list conversions
\dClist casts
\dd [PATTERN]show comment for object
\dD [PATTERN]list domains
\df [PATTERN]list functions (add "+" for more detail)
\dg [PATTERN]list groups
\dn [PATTERN]list schemas (add "+" for more detail)
\do [NAME]list operators
\dllist large objects, same as \lo_list
\dp [PATTERN]list table, view, and sequence access privileges
\dT [PATTERN]list data types (add "+" for more detail)
\du [PATTERN]list users
\llist all databases (add "+" for more detail)
\z [PATTERN]list table, view, and sequence access privileges (same as \dp)

Formatting

\atoggle between unaligned and aligned output mode
\C [STRING]set table title, or unset if none
\f [STRING]show or set field separator for unaligned query output
\Htoggle HTML output mode (currently off)
\pset NAME [VALUE]set table output option
(NAME := {format|border|expanded|fieldsep|footer|null| | |numericlocale|recordsep|tuples_only|title|tableattr|pager})
\tshow only rows (currently off)
\T [STRING]set HTML tag attributes, or unset if none
\x
toggle expanded output (currently off)

Copy, Large Object

\copy ...perform SQL COPY with data stream to the client host
\lo_export LOBOID FILE
\lo_import FILE [COMMENT]
\lo_list
\lo_unlink LOBOIDlarge object operations


2007/09/14

Simple expect ssh example

This expect script would be called from a shell script, and would ssh to the host passed as an argument (argv), perform the command specified, and disconnect. (Thanks, Tiger O.)

#!/usr/bin/expect

set timeout 1
set cmd {uname -a}

spawn ssh root@$argv
expect_after eof { exit 0 }


## interact with SSH
expect "yes/no" { send "yes\r" }
expect "password:" { send "rootpasswd\r" }

expect "# "
send "$cmd\r"
expect "$cmd\r"
expect "(.*)\r"
send "exit\r

2007/07/25

120 VAC Outlet / Plug wiring

First of all, don't follow this -- get a qualified electrician to do your work. Doing it yourself, or using this information, may get you or someone else killed. This is my personal reminder note.

The three slots/holes and their attachment points are:

Silver color screws, this is where your grounded leg {aka neutral} wire goes, this by North America standards should be a white wire, however it can be white or gray. (looking at the front face of an outlet, with the ground on bottom, this is the slot/screw on the left).

Equipment grounding screw, this is where the circuit grounding conductor wire will be attached, this on most general purpose circuits will be a bare wire (although an equipment grounding conductor can be bare or green), this bare or green wire is also connected to a grounding screw on the back of the electrical box (if the electrical box in use is metallic)

Brass color screws, this is where the ungrounded leg [aka hot conductor] wire is attached, the most frequently used wire colors are black & red but can be any color in rainbow but white, gray, bare or green.

Do a smoke-test with something unimportant; don't touch it while testing it. Measure potential between the new ground and a known good ground.

2007/07/18

Windows Updates from the command line with wuauclt.exe

wuauclt.exe has these parameters (not all are verified. gleaned from various posts on the web.)

/configlist - lists WUAUCLT configuration./installAUclient - Install the correct AU client by force
/installAUclientFromMicrosoft - This option causes the system to contact either the confiugred WSUS server, or Microsoft's WU server, and to reinstall forefully the latest version of the AU client.
/clearlogfile - clears the client update log file
/clearandsavelogfile - saves the current client update log file to a named file, then clears the update log.
/downloadnow - initiates an immiate downoad of any requried update using BITS
/downloanowfast - initiates an initiates an immiate downoad of any requried update using HTTP.
/stopdownload - stops any AU updates being downloaded (either using HTTP, or BITS).
/TestWSUSServer - checks connection with configured WU Server
/DetectNow
/ResetAuthorization
/RunHandlerComServer
/RunStoreAsComServer
/ShowSettingsDialog
/ResetEulas
/DemoUI
/FastCountdown
/FakeData
/FakeReboot
/SkipEulas

2007/07/12

Samba with idmap RID on CentOS

For some reason, the CentOS authconfig-tui never works for me out of the box. And there doesn't appear to be correct error handling for it, such as "failed to join domain" -- it acts like everything is okay, and then it doesn't work.

I use the IDMAP_RID option to map user accounts within a single AD to unix user ID's.

Ensure that you have krb5-libs, samba-common, pam_krb5, krb5-workstation, samba-client, and krb5-auth-dialog installed.

Most of these are case-sensitive. The example NETBIOS domain name is "mydomain". Full DNS domain name is "mydomain.com". DC's/KDC's are dc1.mydomain.com, dc2.mydomain.com, etc.

/etc/pam_smb.conf
MYDOMAIN
dc1.mydomain.com
dc2.mydomain.com

Then run "ln -sf system-auth-ac /etc/pam.d/system-auth"
mkdir /var/cache/samba/smb_krb5

/etc/pam.d/system-auth-ac
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth required pam_env.so
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid >= 500 quiet
auth sufficient pam_krb5.so use_first_pass
auth sufficient pam_winbind.so use_first_pass
auth required pam_deny.so

account required pam_unix.so broken_shadow
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 500 quiet
account [default=bad success=ok user_unknown=ignore] pam_krb5.so
account [default=bad success=ok user_unknown=ignore] pam_winbind.so
account required pam_permit.so
assword requisite pam_cracklib.so try_first_pass retry=3
password sufficient pam_unix.so md5 shadow nullok try_first_pass use_authtok
password sufficient pam_krb5.so use_authtok
password sufficient pam_winbind.so use_authtok
password required pam_deny.so

session optional pam_keyinit.so revoke
session required pam_limits.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_krb5.so


/etc/nsswitch.conf
passwd: files winbind
shadow: files winbind
group: files winbind
hosts: files dns
bootparams: nisplus [NOTFOUND=return] files
ethers: files
netmasks: files
networks: files
protocols: files
rpc: files
services: files
netgroup: files
publickey: nisplus
automount: files
aliases: files nisplus
publickey: nisplus
automount: files nisplus
aliases: files nisplus

/etc/krb.conf
MYDOMAIN.COM
MYDOMAIN.COM dc1.mydomain.com:88
MyDOMAIN.COM dc2.mydomain.com:88
MYDOMAIN.COM dc1.mydomain.com:749 admin server

/etc/krb5.conf
[logging]
default = FILE:/var/log/krb5libs.log
kdc = FILE:/var/log/krb5kdc.log
admin_server = FILE:/var/log/kadmind.log

[libdefaults]
default_realm = MYDOMAIN.COM
dns_lookup_realm = false
dns_lookup_kdc = false
ticket_lifetime = 24h
forwardable = yes

[realms]
MYDOMAIN.COM = {
kdc = dc1.mydomain.com:88
kdc = dc2.mydomain.com:88
admin_server = dc1.mydomain.com:749
}

[domain_realm]
domain.com = MYDOMAIN.COM
.domain.com = MYDOMAIN.COM

[kdc]
profile = /var/kerberos/krb5kdc/kdc.conf

[appdefaults]
pam = {
debug = false
ticket_lifetime = 36000
renew_lifetime = 36000
forwardable = true
krb4_convert = false
}

/etc/samba/smb.conf
#=======Global Settings =================
[global]

# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
workgroup = MYDOMAIN
netbios name = FILESERVER
realm = MYDOMAIN.COM
# server string is the equivalent of the NT Description field
server string = File Server
# Security mode. Defines in which mode Samba will operate
security = ADS
allow trusted domains = No
idmap backend = rid:DOMAIN=1000000-10000000
idmap uid = 1000000-10000000
idmap gid = 1000000-10000000
template shell = /sbin/nologin
winbind use default domain = Yes
winbind enum users = Yes
winbind enum groups = Yes
winbind nested groups = Yes
smb ports = 139
# Restrict what subnets can access this server
hosts allow = 192.168.1. 192.168.2. 192.168.3. 192.168.4. 192.168.5. 192.168.0. 127.

# If you want to automatically load your printer list rather
# than setting them up individually then you'll need this
load printers = no
domain master = no
preferred master = no
domain logons = no
wins support = no
wins proxy = no
dns proxy = no
password server = dc1.mydomain.com
# SHARE DEFINITIONS
[users]
path = /var/export/users
comment = user home dirs
public = no
writeable = yes
browseable = no
guest ok = no
printable = no
[team]
path = /var/export/team
comment = Team and Departmental Share
public = no
writeable = yes
browseable = yes
guest ok = no
write list = @Domain\ Users
valid users = +"DOMAIN\Domain Users" jdoe
#invalid users = @acc_T_Drive_Deny mdc
printable = no


Now, run "ntpdate dc1.mydomain.com", then configure and start ntpd (configure it to sync time from your DC's). Use ntpd -q and look for an asterisk to know when it has synchronized to the DC; it may take a few minutes. If your system clock gets more than 5 minutes out of sync with the DC's, then kerberos (and your authentication) will stop working.

TESTING
To test Kerberos functionality for authentication, run kinit " where is a user name on your AD domain.

To test ntpd functionality, run ntpd -q and look for an asterisk next to your DC.

To test that winbind is getting user and group info from AD, and that the system can use it, run "getent passwd" and "getent groups", and you should see your AD users and groups in there.

Note: for VMware server to work, you'll need a manual password entry for any user who will run vmware to be in /etc/passwd.


2007/06/28

How to process command-line args in bash scripts

while [ $# -gt 0 ]; do
case $1 in
--somevar)
SOMEVAR=$2
SOMEVARSTR="--somevar $2"
shift; shift
;;
--othervar)
OTHERVAR=$2
shift; shift
;;
--version)
VERSION=$2
shift; shift
;;
--debug)
DEBUGSTR="--debug"
shift
;;
*)
if [ -n "$TARGET" -o ! -d $1 ]; then
usage
fi
TARGET=$1
shift
;;
esac
done

2007/06/05

Gathering information on Windows Servers

Some of these tools require you to download the Windows (2003) support tools and install them on a Windows XP or 2003 computer that is a member of the domain; download the tools from http://support.microsoft.com/kb/892777 .

  • Remotely get replication info on a Windows server
    • repadmin /showattr ncobj:domain:
  • Remotely get the OS version and SP level of a Windows server (enter on one line)
    • repadmin /showattr ncobj:domain: /filter:"(&(objectCategory=computer)(primaryGroupID=516))" /subtree /atts:operatingSystem,operatingSystemVersion,operatingSystemServicePack
  • Verify DC replication
    • REPADMIN /REPLSUM /BYSRC /BYDEST /SORT:DELTAdcdiag
  • Verify DC configuration of all DCs in a forest:
    • dcdiag /v /e /n:domain_name
  • more to come

2007/05/07

Troubleshooting library issues in Linux

Linux (like Windows) programs can either be linked:
  • statically
    • can create much larger binaries
    • won't get stuck with problems about a library dependency not being met
    • any time an important fix is applied to the library against which it was compiled, you theoretically should rebuild all the binaries you built from it, to make sure they get the fix
  • dynamically (like a windows .dll, but they usually have a .so.* extension)
    • smaller binaries
    • sometimes have library/version dependency problems
    • updating the library has the effect of "fixing" all the binaries that use it dynamically
Generally, most systems prefer dynamically linked programs. However, some tools may require different versions of libraries than come by default on your distro. This can force one to write special wrappers, set up LD_LIBRARY_PATH, and have to troubleshoot annoying problems.

A few of the tools you might use in troubleshooting library problems are:

ldd
ldconfig
objdump

A few environment variables to consider:
LD_LIBRARY_PATH
LD_PRELOAD

2007/04/19

Create a minimal Xen domU template for CentOS

Create partitions for the domU. With LVM:
lvcreate --size 6G --name LV-server-root VG00
lvcreate --size 512M --name LV-server-swap VG00
mkfs.ext3 /dev/VG00/LV-server-root
mkswap /dev/VG00/LV-server-swap
mkdir /mnt/server
mount /dev/VG00/LV-server-root /mnt/server
mkdir -p /mnt/server/dev /mnt/server/etc /mnt/server/proc /mnt/server/var/lock/rpm /mnt/server/var/lib/rpm /mnt/server/var/log
MAKEDEV -d /mnt/server/dev -x random
MAKEDEV -d /mnt/server/dev -x console
MAKEDEV -d /mnt/server/dev -x zero
MAKEDEV -d /mnt/server/dev -x null
mount -t proc none /mnt/server/proc
wget http://isoredirect.centos.org/centos-5/5/os/x86_64/CentOS/centos-release-5-0.0.el5.centos.2.x86_64.rpm
rpm --initdb --root=/mnt/server
rpm -ivh --root=/mnt/server --nodeps centos-release*.rpm
yum groupinstall Core --installroot=/mnt/server
cd /mnt/server
vi etc/fstab etc/resolv.conf etc/sysconfig/network etc/sysconfig/network-scripts/ifcfg-eth0 etc/hosts
(hint: make those files look similar to the ones in the dom0)
cd /; umount /mnt/server
edit your domU config file, in /etc/xen.

2007/04/05

CentOS / RHEL Unsupported RAID/SATA/SCSI Controllers

So, I've got a Promise SuperTrak RAID controller. It uses the stex kernel module, which was supposedly added to CentOS 4.4. Well, when I went to install CentOS 4.4, and later CentOS 5 beta, the installer wouldn't load the driver, and so the array was not usable. Very frustrating. The vendor only has driver binaries for certain versions of certain OSes. It's a chicken-egg situation, if you don't want to first install to an IDE disk and then RSync it over.

The good news is, yes, the module (stex) is included in the RPM on the install CD, and you can load that module before the installer detects available disks.

To manually load the module, go in the installer to the screen just before you are presented with available disks and partitioning options. Then, press Ctrl-alt-f2, I think, to bring up a sh# prompt. Look at your mounted filesystems ("mount"). One of them points to the current running environment (I forget what it's called), and one of them points to the install media. Go to the install media, and find the kernel-*.rpm. install it with rpm -ivh --nodeps kernel-*.rpm (you may have to do the --root= option and specify the root of the running environment.). Then, cd to the lib/modules/`uname -r`/kernel/drivers/scsi directory, and either insmod stex.ko or modprobe stex.ko (or whatever module you're trying to use) . Voila, the module is loaded and your raid array/controller should have been detected now. Press Ctrl-Alt-F6 to get back to the (graphical) installation, and press "next" to detect available disks/partitions.
Wait until the scre