Need to grab IP of visitors from the Apache logs

15,282

Apache already logs the IP of each visitor by default. You can get the list of unique visitors from that file already by combining awk and sort like:

awk '{print $1}' <log_path> | sort -u

where is the path to the apache log which is /var/log/httpd/access_log on Red Hat type systems and /var/log/apache2/access.log on Ubuntu types.

Of course, you con't have to get them unique, so you could drop the sort if you don't want that.

Edit:

As @facundo-victor pointed out if you do want unique visitors we can do it all with awk and save the extra process by keeping track of what we've seen and only printing them the first time like so:

awk '{if (!unique[$1]++) {print $1}}' <log_path>

though they'll be in the order they first appear in the log file, not ascii sorted.

Also, this assumes that the first field in the log is the IP address, which is the default for many newer versions of Apache, but doesn't have to be true.

Share:
15,282

Related videos on Youtube

stacy
Author by

stacy

Updated on September 18, 2022

Comments

  • stacy
    stacy over 1 year

    I want to store the IP of the visitors to my website, and I want to use PHP. Should I use cron for it or how will be the visitors' IP will be automatically stored?

    • Admin
      Admin over 8 years
      They're probably already in the apache log file, can you just access that to get them?
    • Admin
      Admin over 8 years
      Hi Eric, Could you please tell me how do I do it ?? with scripts or any other option ?
    • Admin
      Admin over 8 years
      Assuming the default log for apache you could get all the unique visitors with something like awk '{print $1}' /var/log/httpd/access_log | sort -u assuming a Red Hat location, for Ubuntu type systems it'd be /var/log/apache2/access.log
  • Facundo Victor
    Facundo Victor over 8 years
    Eric, that is ok, but the log file format may not be the same for every server (https://httpd.apache.org/docs/1.3/logs.html). Also, using "awk", you can print different IP addresses like this: awk '{ if (!unique[$1]++) {print $1}}' <log_path>