array_rand() not really random

array_rand() not really random

Let’s face it, it’s not very random.

to fix it
before sending your array to array_rand() do this

srand();shuffle($array_name);

Reset OS X Password Without an OS X CD

Here’s how to reset your OS X password without an OS X CD. You need to enter terminal and create a new admin account:

Reboot
Hold apple + s down after you hear the chime.

When you get text prompt enter in these terminal commands to create a brand new admin account (hitting return after each line):

mount -uw /
rm /var/db/.AppleSetupDone
shutdown -h now

After rebooting you should have a brand new admin account. When you login as the new admin you can simply delete the old one and you’re good to go again!

MySQL: recover lost root password

Log in as root and stop the mysql daemon.

service mysqld stop

Then start up the mysql daemon and skip the grant tables which stores the passwords and other priviledge information

mysqld_safe --skip-grant-tables &

Now you should be able to connect to mysql without a password.

mysql --user=root mysql
mysql> update user set Password=PASSWORD('new password') where user='root';
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit

and then restart the mysql daemon (it will stop the mysql-safe) as you would normally do

service mysqld start

Red Hat, OEL 5,6 vlan tagging

Red Hat, OEL 5,6 vlan tagging

vlan tagging can only be set up on a virtual interface, and the 8021q driver must be present

For this document we will use the following addresses

Physical: 172.22.130.80 255.255.254.0 gateway: 172.22.130.1
Virtual: 192.168.72.11 255.255.255.0 gateway: 192.168.72.2 vlan: 4

1. First check if the 8021q driver is installed

# lsmod | grep 8021q
#
Nope, not there, so we install it

# modprobe 8021q
# lsmod | grep 8021q
8021q 21088 0
garp 6692 1 8021q
#

2. now for the physical device
# cat /etc/sysconfig/network-scripts/ifcfg-eth0
# Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet
DEVICE=eth0
BOOTPROTO=none
#HWADDR=00:1E:C9:3C:93:78
ONBOOT=yes
IPADDR=172.22.130.80
NETMASK=255.255.254.0
GATEWAY=172.22.130.1
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes

3. create a second ifcfg file using device.vlan

# cat /etc/sysconfig/network-scripts/ifcfg-eth0.4
# Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet
DEVICE=eth0.4
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.72.11
NETMASK=255.255.255.0
GATEWAY=192.168.72.2
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes
vlan=yes

Make sure you have the tag "vlan=yes" and that there is no HWADDR tag

4. Add the driver to the tcp/ip stack with vconfig (vconfig add device vlan)

# vconfig add eth0 4

5. routing. Linux sets as default the first gateway that connects. In this example we set the
first gateway in /etc/sysconfig/network-scripts/ifcfg-eth0 (GATEWAY=172.22.130.1). But we have
to set up a persistant route (lives after reboot) so that traffic goes where it needs to go. So
we create a persistant route file.

# cat /etc/sysconfig/network-scripts/route-eth0
default via 172.22.130.1 dev eth0
172.0.0.0/8 via 172.22.130.1 dev eth0
192.168.72.0 via 192.168.72.2 dev eth0.4
#

6. restart networking

# service network restart

7. check our routing tables

# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.72.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0.4
172.22.130.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0.4
172.0.0.0 172.22.130.1 255.0.0.0 UG 0 0 0 eth0
0.0.0.0 192.168.72.2 0.0.0.0 UG 0 0 0 eth0.4

AIX printing

Printing

TERMS:
print job                A print job is a unit of work to be run on a printer. The system assigns a unique job number to it.
queue                    It is where a print job is directed. (It is a stanza in the /etc/qconfig file.)
queue device             The stanza in the /etc/qconfig. It specifies the /dev file (printer device) that should be used.
qdaemon                  It runs in the background and controls the queues.
print spooler            A spooler does not normally know what type of job it is queuing. It provides spooling function for any type of jobs.
printer backend          It is a collection of programs called by the spooler’s qdaemon command to manage a print job.
                         It reports paper out, cleans up after a print job is cancelled, initializes the printer before printing …

FILES:

/etc/qconfig             queue configuration files
/var/spool/*             spooling directories
/var/spool/qdaemon/*     temporary enqueued files (spooling: makes a copy here of the printed file until the job has printed)

————————————

Spooler functions and services

The base operating system spooler is a collection of programs, configuration files and data files, which provides the following functions or services:
– construction of queues (whose function is to process jobs in specific ways)
– serial access through a queue to a device (such as a printer), avoiding simultaneous use of a single device or program by multiple users
– allows users to submit jobs (usually but not always printer jobs) to a queue for processing
– allows users to query the status of queues through status files
– allows users to control the availability of queues and the status of jobs

The base operating system spooler is not specifically a print job spooler but a generic spooling system that can be used for queuing various types of jobs, including print jobs to a printer queue. The spooler does not know what type of job it is queuing. When a queue is created, the function of the queue is defined by the spooler backend for that queue. For example, if a queue is created and the queue backend is set up to be piobe(the default printer I/O backend for local printer queues), the queue is a print queue. Likewise, if the queue backend is set up to be cc (or any other compiler), the queue is for compiler jobs. When the spooler’s qdaemon component selects a job from a queue, it processes the job by invoking the queue’s backend.

To accomplish its tasks, the base operating system spooler has four basic parts:
1. The enq command is the entry point to the spooler, and it is the beginning of any spooler activity. This command accepts requests for job processing.

2. The qdaemon is responsible for accepting/tracking jobs submitted to the spooler by enq command.  It is one of the points-in-between in the spooler process.

3. The spooler backend is a collection of programs invoked by the spooler’s qdaemon command to process a job in some queue. The backend sends output to a specific device, such as a printer. When the backend is piobe, it involves a printer. The backend is one of the points-in-between as well as the ending, because the backend contains the specific process that will deliver the processed job to its final destination.

4. The configuration file, /etc/qconfig, describes the configuration of available queues and devices. The enq and the qdaemon command see this file.

————————————

qdaemon process

The qdaemon is a process that runs in the backgroundand controls the queues. (A queue is a location to which you direct a print job.) When you turn your system on, the startsrc command starts qdaemon.

The qdaemon keeps track of the print requests in the /var/spool/lpd/qdir directory and ensures that the jobs are sent to the proper printer at the proper time. It also keeps track of the status of the printers and stores printer usage data for system accounting purposes. This information is held in the /var/spool/lpd/stat directory and can be accessed using the enq -A command. If the qdaemon is stopped, it is restarted by srcmstr (stopsrc/startsrc).

————————————

/etc/qconfig file

The/etc/qconfig file is the most important file in the spooler domain. It describes all of the queues defined to the base operating system. A queue is a named, ordered list of requests for a specific device. A device is something (either hardware or software) that can handle those requests one at a time. The queue provides serial access to the device.

Each queue must be serviced by at least one device; often it can be handled by more than one device.

Each queue is represented by a pair of stanzas. The first stanza in a pair is referred to as the queue stanza; the second stanza in a pair is referred to as the device stanza.

queue_pr1a:               <–queue stanza header (queue name), user can submit jobs to this name
        device = hp@pr1a  <–device name (link to device stanza), shows how the device stanza will be named

hp@pr1a:                   <–device stanza header (queue device name), device to which the corresponding queue stanza provides serial access
        file = /var/spool/lpd/pio/@local/dev/hp@pr1a.domain.com#hpJetDirect#9100    <–path to real device
        header = never                                                                 (If OS sees lp1, file parameter is /dev/lp1)
        trailer = never
        access = both
        backend = /usr/lib/lpd/pio/etc/piojetd pr1a.domain.com 9100                 <–full path to a program (backend)

Additional note:
– There can be more than one queue device associated with a single queue.
– There is no file entry in the/etc/qconfigfile when you are using a remote printer. The queue directs the file to the server.

Both the enq command and the qdaemon command read the /etc/qconfig file when they start.

The qdaemon starts with startsrc and reads the ASCII version of /etc/qconfig and automatically creates a binary version of it: /etc/qconfig.bin.

The enq command starts each time someone requests a print job. The enq command automatically converts the ASCII /etc/qconfig file to binary format (/etc/qconfig.bin)  when the binary version is missing or older than the ASCII version. Therefore, if you change the /etc/qconfigfile, the enq command reads the new version of the configuration file the next time it runs.

Commands wich make changes in /etc/qconfig (mkque, rmque….) are recommended to run during slow or off-peak time. If manual editing of the /etc/qconfig file is necessary, you can first issue the enq -G command to bring the queuing system and the qdaemon to a halt after all jobs are processed. Then you can edit the /etc/qconfig file and restart the qdaemon with the new configuration.

————————————

Local and remote printers

local printer:
A local printer is a real printer attached to a local host, for which there is a local queue. All jobs submitted to this queue are processed and printed on the host on which the queue exists. (If you have a network printer, but you create a queue locally, it can be considered as a local printer.)

remote printer:
A remote printer is a real printer attached to a remote host. The queue for a remote printer specifies a backend whose function is to send the spooled job from the local host across the network to the remote host. All jobs submitted to this queue, on the local host, are sent across the network to the remote host where they are processed and printed.

————————————

Printing process:

1. A front-end print command (such as qprt, lp or enq) initiates a request.

   Four commands can be used to submit a job to the base operating system spooler. These are lp, lpr, qprt, and enq.
   – lp originated with AT&T System V
   – lpr originated with BSD
   – qprt and enq originated with the base operating system

   While a user can use any one of these four commands to submit a job to the spooler, the true entry point to the spooler is the enq command.
   All of lp, lpr, and qprt are front ends to enq. lp, lpr, and qprt all parse their arguments and compose a call to enq.

2. If not enq was used, all the other comands are invoking enq command and translate the flags to enq compatibility.

3. enq creates a JDF file (Job Description File) in /var/spool/lpd/qdir. It conatins file name, flags, what qdaemon can understand

4. enq then signals qdaemon that a job has been queued

5. qdaemon will examine /etc/qconfig.bin (compiled version of /etc/qconfig) and the JDF file to determine how to handle the print job
   (If /etc/qconfig is younger than /etc/qconfig.bin the qdaemon creates a new version of /etc/qconfig.bin before printing anything.)

6. qdaemon invokes the backend program (contained in /etc/qconfig file)
   (If the job is spooled with pipe (e.g. an output is piped to enq) or enq is called with -c flag, data first copied into a temp file.)
   (This temp file is stored in /var/spool/qdaemon and then the name of the temp file is passed to the backend.)

   Backend program:
   – for remote printing is "rembak"
   – for local printing is "piobe" (printer input/output backend)

   If it is a remote printing (rembak is invoked):
   – The rembak program transmits the print job to a remote server over the TCP/IP network.
   – On the remote server, lpd daemon monitors port 515, and when it receives a remote print request, it places the job in the local queue.
   – The print request is then processed by the qdaemon on the print server and passes the request to the piobe backend on the print server.

7. Backend program (piobe) processes the file and sends it, along with control information, to the printer

8. The printer then receives a data stream containing the contents of the file and the control information specified with the qprt command

9. When backend program exits, qdaemon checks exit code of the backed. If it is 0 job completed successfully

————————————

Remote printing (Don’t confuse with network printing)
(If you have a network printer, it can be considered as a local printer as you create a queue locally.)

Remote printing allows different computers to share printers. To use remote printing facilities, computers must be connected through TCP/IP and must support the required TCP/IP applications, such as the lpd daemon.

lpd daemon

Although local and remote print jobs are submitted with the same commands, they are processed differently. After a print job has been transmitted to a remote host, it is no longer managed by the local print spooling subsystem.

The lpd daemon is part of the TCP/IP system group. Any host on a TCP/IP network can run the lpd daemon, and any host can send print requests to any other host on the network (if the host is currently running lpd). As a security measure, the lpd daemon forks a child process that checks each remote print request against two database files: the /etc/hosts.equiv file and the/etc/hosts.lpd file.

/etc/hosts.equiv:    defines which computers are allowed to execute certain commands on a local host without supplying a password.
/etc/hosts.lpd:      defines which computers are allowed to execute print commands on a local host without supplying a password.

(If the name of the host submitting the print request is not in the /etc/hosts.lpd file, the print request is rejected.)

The lpd daemon on the remote print server monitors port 515 for print requests. When the lpd daemon receives a print request from a valid host, it places the request in the specified queue. The lpd daemon places files specified in print requests in the directory /var/spool/lpd. The print request is then managed by the qdaemon and the appropriate backend (usually piobe) on the remote server.

The/etc/locks/lpd file contains the process ID of the currently running instance of the lpd daemon. If a machine running the lpd daemon becomes inoperable, the ID for the lpd daemon might have to be removed before the system is restarted. The error messages "lpd: lock file or duplicate daemon" indicate that the ID must be removed.

lpd daemon can be controlled by stopsrc/startsrc -s lpd

————————————

# lssrc -g spooler
Subsystem         Group            PID          Status
 qdaemon          spooler          27132086     active        <–schedules printing jobs enqueued by the enq command
 lpd              spooler          30736618     active        <–remote print server, monitors port 515 placing requests in /var/spool/lpd
 writesrv         spooler                       inoperative   <–allow users to send messages to a remote system and receive responses by write command

————————————

Configuring a new printer queue (with a printer):

AIX places each print job into a queue to await printer availability. When a job is done system processes the next job in the queue. This process continues
until each job in the queue has been printed.

You need some info prior to configure:
– printer queue name (you should know if it is PS (postScript) or PCL (Printer Command Language))
– printer model
– if it is a network printer ip address and port (this IP should be resolved by DNS or /etc/hosst file)

1. smitty printer -> Print Spooling -> Add a Print Queue
2. choose if it is local, remote or network (HP Jetdirect) printer
3. choose printer type (if network printer I usually choose "Do NOT make this system a BOOTP/TFTP server")

For a network printer it looks like this:

  Description                                         Hewlett-Packard Color LaserJet 4700

  Names of NEW print queues to add
     HP-GL/2                                         []
     PCL                                             []
     PostScript                                      [NEW_QUEUE_NAME]

  Printer connection characteristics
*    HOSTNAME of the JetDirect Card                  [HOSTNAME_OF_PRINTER]
*    PORT                                            [9100]                               

————————————

COMMANDS:

lsallq                             list print queues only
/usr/lib/lpd/pio/etc/piolsvp -p    list print queues, printers and description (good for checking if PostScript is used)
enq -AsW                           list all print queues with status information

    DEV_BUSY:    printer device is currently is in use (wait for finishing or cancel the job or process that is using the printer port)
    DEV_WAIT:    queue is waiting on the printer because the printer is offline, out of paper, jammed, or the cable is loose…
                 (You can move queued jobs to another queue with command enq, after problem is corrected, move any unprinted jobs back.)
    DOWN:        if the printer device signals or appears to be off, the queue will go into the DOWN state
                 (After correcting the problem queue must be manually brought up before it can be used again.)
    HELD:        print job is held. The print job cannot be processed by the spooler until it is released
    QUEUED:      print file is queued and is waiting in line to be printed
    READY:       everything involved with the queue is ready to queue and print a job
    RUNNING:     print file is printing

lpstat -t -p<printer name>  list info about the printer and submitted jobs to it
enq -d                      it will digest /etc/qconfig and /etc/qconfig.bin will be created (if /etc/qconfig.bin is older than /etc/qconfig)

qadm -U <QueueName>         start a print queue (queue status will show READY)
qadm -D <QueueName>         stop a print queue (queue status will show DOWN)
qadm -G                     gracefully brings down the queuing system (Ends qdaemon process after all currently running jobs are finished.)

qprt -PQueueName FileName   create and queue a print job to print the file you specify
cat file > dev/lp0          prints out the file (this bypasses the queuing system and helps narrow the problem)

qmov                        moves print jobs to another queue
qcan -x 123                 cancel job number 123 on whichever printer the job is on (smitty qcan)
qcan -X -P lp0              cancel all jobs queued on printer lp0

rmquedev -d <device name>   removes a printer device from the system configuration by deleting the device stanza
                            Deleting a printer does not remove any print queues that send print jobs to that printer.

rmque -q <queue name>       remove a printer queue from the system (smitty rmque) (All queue devices must be deleted with the rmquedev prior to this)
                            If the selected queue has only one printer, the queue and its printer are removed.
                            If the queue has more than one printer, only the selected printer is removed.

————————————

Checking which flag/argument is passed to enq command:

All front-end commands are entry points to enq. These commands will translate its flags/arguments to those flags/arguments which can be used by enq:
qprt, qadm, qmov, qcan, lp, lpr, enable, disable —> enq

The following method will show what is passed to enq exactly:

1. mount /bin/echo /bin/enq                <–this makes possible that a fron-end command calls the echo command instead of enq

2. try any front-end command:
qprt -Pasc -p12 -s courier /etc/motd       <–qprt submits a print job to the queue "asc", requests to print /etc/motd file in Courier 12 font

3. on the output you will see:                     <–it will show the argument vector which is generated by qprt command
-P asc -o -p -o 12 -o -s -o courier /etc/motd      <–without echo this would be executed by enq

4. umount /bin/enq                                 <–make sure you don’t forget this, otherwise spooler will be disabled

————————————

POTENTIAL SOFWARE PROBLEMS:

-check qdaemon           (lssrc -s qdaemon, startsrc – qdaemon)
-/etc/qconfig            (look at the contents to make sure it is not corrupt)
-lpstat->enable queuename ensure the queue is enabled, if not enable it
-/tmp , /var             make sure they are not full

————————————

STEPS OF SETTING UP REMOTE PRINTING:
 – smitty mkhostslpd     on the print server, set up client authorization (define the clients in /etc/host.lpd)
 – smitty mkitab_lpd     on the print server starting the lpd daemon
                         (start/stopsrc also good, just with smitty make entry in inittab which will keep it after restart)
 – smitty spooler        -> Add a Print Queue -> Standard.. (This adds a remote queue on the client)
                         (then name the local(client) queue name, name of the printer server, name the queue on the print server)

————————————
CANCEL A PRINT JOB:
1.lpstat                 <–it shows the job number
root@aix1: /home/guest # lpstat
Queue   Dev   Status    Job Files              User         PP %   Blks  Cp Rnk
——- —– ——— — —————— ———- —- — —– — —
lp0     lp0   Running   99  walrus             team01        1      1    1    1

2.qcan                  <–cancels a print job
qcan -x 99              <–99 is the job number

————————————

SAP PRINTER PROBLEM:
1. check spooler
aix0001:/home/root > lssrc -g spooler
Subsystem         Group            PID          Status
 qdaemon          spooler          13260        active
 writesrv         spooler          17806        active
 lpd              spooler          20658        active

2. get printer status
aix0001:/home/root > lpstat -p22P1
Queue   Dev   Status    Job Files              User         PP %   Blks  Cp Rnk
——- —– ——— — —————— ———- —- — —– — —
22P1    hp@22 READY

restart printer queue in smitty spooler or if this does not help, restart qdaemon

Clearing an AIX print queue

Problem

You have jobs stuck in the print queue. You want to clear the queues and remove all jobs.

Solution

You have to stop all processes and remove the files from spooling directories.

Probably worth taking a backup of these files first. All at own risk.

Example

1.


stopsrc -cs qdaemon # bring down qdaemon and clear qdforks.
stopsrc -s lpd

2.


rm /etc/qconfig.bin # compiled /etc/qconfig

3.


rm /var/spool/lpd/qdir/* # queue requests; JDF

4.


rm /var/spool/lpd/stat/* # info on status of devices

5.


rm /var/spool/lpd/pio/msg* # error message files.

6.


rm /var/spool/qdaemon # temp copies of queue jobs

7.


rm /var/spool/lpd/* # temp copies of remote jobs

8.


ps -ef | grep pio # kill any of these processes; look for piobe, pioformat, pioout

9.


ps -ef | grep qd # kill any of these processes; look for qdforks.

10.


startsrc -s qdaemon # restarting qdaemon
startsrc -s lpd # restarting lpd

11.


lssrc -s qdaemon #look for active
ps -ef | grep qdaemon
lssrc -s lpd # look for active
ps -ef | grep lpd

12.


ps -ef | grep srcmstr # if there are 2 running, kill -9 one of them with higher PID.

13.

As a last resort – reboot

Cleaning up /installp/ppc

/usr/sys/inst.images/installp/ppc can really chew up disk space with ,bff files.

First, check to see if they were installed

(note: the -p option does a pretend install)

update_all -d /usr/sys/inst.images/installp/ppc -p

then check the update log

more /var/adm/ras/install_all_updates.log

If it’s old stuff go ahead and recover disk space!

lsof primer

lsof is the sysadmin/security ?ber-tool. I use it most for getting network connection related information from a system, but that’s just the beginning for this powerful and too-little-known application. The tool is aptly called lsof because it "lists open files". And remember, in UNIX just about everything (including a network socket) is a file.

Interestingly, lsof is also the Linux/Unix command with the most switches. It has so many it has to use both minuses and pluses.

usage: [-?abhlnNoOPRstUvV] [+|-c c] [+|-d s] [+D D] [+|-f[cgG]]
 [-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+|-M] [-o [o]]
 [-p s] [+|-r [t]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [--] [names]

As you can see, lsof has a truly staggering number of options. You can use it to get information about devices on your system, what a given user is touching at any given point, or even what files or network connectivity a process is using.

For me, lsof replaces both netstat and ps entirely. It has everything I get from those tools and much, much more. So let’s look at some of its primary capabilities:

Key Options

It’s important to understand a few key things about how lsof works. Most importantly, when you’re passing options to it, the default behavior is to OR the results. So if you are pulling a list of ports with -i and also a process list with -p you’re by default going to get both results.

Here are a few others like that to keep in mind:

  • default : without options, lsof lists all open files for active processes
  • grouping : it’s possible to group options, e.g. -abC, but you have to watch for which options take parameters
  • -a : AND the results (instead of OR)
  • -l : show the userID instead of the username in the output
  • -h : get help
  • -t : get process IDs only
  • -U : get the UNIX socket address
  • -F : the output is ready for another command, which can be formatted in various ways, e.g. -F pcfn (for process id, command name, file descriptor, and file name, with a null terminator)

Getting Information About the Network

As I said, one of my main usecases for lsof is getting information about how my system is interacting with the network. Here are some staples for getting this info:

Show all connections with -i

Some like to use netstat to get network connections, but I much prefer using lsof for this. The display shows things in a format that’s intuitive to me, and I like knowing that from there I can simply change my syntax and get more information using the same command.

# lsof -i

COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
dhcpcd 6061 root 4u IPv4 4510 UDP *:bootpc
sshd 7703 root 3u IPv6  6499 TCP *:ssh (LISTEN)
sshd 7892 root 3u IPv6  6757 TCP 10.10.1.5:ssh->192.168.1.5:49901 (ESTABLISHED)

Get only IPv6 traffic with -i 6

# lsof -i

Show only TCP connections (works the same for UDP)

You can also show only TCP or UDP connections by providing the protocol right after the -i.

# lsof -iTCP

COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
sshd 7703 root 3u IPv6 6499 TCP *:ssh (LISTEN)
sshd 7892 root 3u IPv6 6757 TCP 10.10.1.5:ssh->192.168.1.5:49901 (ESTABLISHED)

Show networking related to a given port using -i :port

Or you can search by port instead, which is great for figuring out what’s preventing another app from binding to a given port.

# lsof -i :22

COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
sshd 7703 root 3u  IPv6 6499 TCP *:ssh (LISTEN)
sshd 7892 root 3u  IPv6 6757 TCP 10.10.1.5:ssh->192.168.1.5:49901 (ESTABLISHED)

Show connections to a specific host using @host

This is quite useful when you’re looking into whether you have open connections with a given host on the network or on the internet.

# lsof -i@172.16.12.5

sshd 7892 root 3u IPv6 6757 TCP 10.10.1.5:ssh->172.16.12.5:49901 (ESTABLISHED)

Show connections based on the host and the port using @host:port

You can also combine the display of host and port.

# lsof -i@172.16.12.5:22

sshd 7892 root 3u IPv6 6757 TCP 10.10.1.5:ssh->192.168.1.5:49901 (ESTABLISHED)

Find listening ports

Find ports that are awaiting connections.

# lsof -i -sTCP:LISTEN

You can also do this by grepping for "LISTEN" as well.

# lsof -i | grep -i LISTEN

iTunes     400 john   16u  IPv4 0x4575228  0t0 TCP *:daap (LISTEN)

Find established connections

You can also show any connections that are already pinned up.

# lsof -i -sTCP:ESTABLISHED

You can also do this just by searching for "ESTABLISHED" in the output via grep.

# lsof -i | grep -i ESTABLISHED

firefox-b 169 john  49u IPv4 0t0 TCP 1.2.3.3:1863->1.2.3.4:http (ESTABLISHED)

User Information

You can also get information on various users and what they’re doing on the system, including their activity on the network, their interactions with files, etc.

Show what a given user has open using -u

# lsof -u john

-- snipped --
Dock 155 john  txt REG   14,2   2798436   823208 /usr/lib/libicucore.A.dylib
Dock 155 john  txt REG   14,2   1580212   823126 /usr/lib/libobjc.A.dylib
Dock 155 john  txt REG   14,2   2934184   823498 /usr/lib/libstdc++.6.0.4.dylib
Dock 155 john  txt REG   14,2    132008   823505 /usr/lib/libgcc_s.1.dylib
Dock 155 john  txt REG   14,2    212160   823214 /usr/lib/libauto.dylib
-- snipped --

Show what all users are doing except a certain user using -u ^user

# lsof -u ^john

-- snipped --
Dock 155 jim  txt REG   14,2   2798436   823208 /usr/lib/libicucore.A.dylib
Dock 155 jim  txt REG   14,2   1580212   823126 /usr/lib/libobjc.A.dylib
Dock 155 jim  txt REG   14,2   2934184   823498 /usr/lib/libstdc++.6.0.4.dylib
Dock 155 jim  txt REG   14,2    132008   823505 /usr/lib/libgcc_s.1.dylib
Dock 155 jim  txt REG   14,2    212160   823214 /usr/lib/libauto.dylib
-- snipped --

Kill everything a given user is doing

It’s nice to be able to nuke everything being run by a given user.

# kill -9 `lsof -t -u john`

Commands and Processes

It’s often useful to be able to see what a given program or process is up to, and with lsof you can do this by name or by process ID. Here are a few options:

See what files and network connections a named command is using with -c

# lsof -c syslog-ng

COMMAND    PID USER   FD   TYPE     DEVICE    SIZE       NODE NAME
syslog-ng 7547 root  cwd    DIR    3,3    4096   2 /
syslog-ng 7547 root  rtd    DIR    3,3    4096   2 /
syslog-ng 7547 root  txt    REG    3,3  113524  1064970 /usr/sbin/syslog-ng
-- snipped --

See what a given process ID has open using -p

# lsof -p 10075

-- snipped --
sshd    10068 root  mem    REG    3,3   34808 850407 /lib/libnss_files-2.4.so
sshd    10068 root  mem    REG    3,3   34924 850409 /lib/libnss_nis-2.4.so
sshd    10068 root  mem    REG    3,3   26596 850405 /lib/libnss_compat-2.4.so
sshd    10068 root  mem    REG    3,3  200152 509940 /usr/lib/libssl.so.0.9.7
sshd    10068 root  mem    REG    3,3   46216 510014 /usr/lib/liblber-2.3
sshd    10068 root  mem    REG    3,3   59868 850413 /lib/libresolv-2.4.so
sshd    10068 root  mem    REG    3,3 1197180 850396 /lib/libc-2.4.so
sshd    10068 root  mem    REG    3,3   22168 850398 /lib/libcrypt-2.4.so
sshd    10068 root  mem    REG    3,3   72784 850404 /lib/libnsl-2.4.so
sshd    10068 root  mem    REG    3,3   70632 850417 /lib/libz.so.1.2.3
sshd    10068 root  mem    REG    3,3    9992 850416 /lib/libutil-2.4.so
-- snipped --

The -t option returns just a PID

# lsof -t -c Mail

350

Files and Directories

By looking at a given file or directory you can see what all on the system is interacting with it–including users, processes, etc.

Show everything interacting with a given directory

# lsof /var/log/messages/

COMMAND    PID USER   FD   TYPE DEVICE   SIZE   NODE NAME
syslog-ng 7547 root    4w   REG    3,3 217309 834024 /var/log/messages

Show everything interacting with a given file

# lsof /home/john/firewall_whitelist.txt

Advanced Usage

Similar to tcpdump, the power really shows itself when you start combining queries.

Show me everything john is doing connected to 1.1.1.1

# lsof -u john -i @1.1.1.1

bkdr   1893 john 3u  IPv6 3456 TCP 10.10.1.10:1234->1.1.1.1:31337 (ESTABLISHED)

Using the -t and -c options together to HUP processes

# kill -HUP `lsof -t -c sshd`

lsof +L1 shows you all open files that have a link count less than 1

This is often (but not always) indicative of an attacker trying to hide file content by unlinking it.

# lsof +L1

(hopefully nothing)

Show open connections with a port range

# lsof -i @fw.google.com:2150=2180

Conclusion

This primer just scratches the surface of lsof’s functionality. For a full reference, run man lsof or check out the online version.