<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.howtogeek.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Sysadmin Geek</title>
	
	<link>http://sysadmingeek.com</link>
	<description>Your Complete IT Guide</description>
	<lastBuildDate>Wed, 08 Sep 2010 10:00:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.howtogeek.com/SysadminGeek" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="sysadmingeek" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Upload Files to an FTP Site via a Batch Script</title>
		<link>http://sysadmingeek.com/articles/upload-files-to-an-ftp-site-via-a-batch-script/</link>
		<comments>http://sysadmingeek.com/articles/upload-files-to-an-ftp-site-via-a-batch-script/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 10:00:42 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[Windows Server]]></category>
		<category><![CDATA[howtogeek]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=359</guid>
		<description><![CDATA[<p>Outside of email, probably the most common way to send files to a remote party is via FTP. While there are a plethora of FTP clients you can choose from, Windows has an little known and under utilized command line FTP utility built in. The beauty of this tool lies in it’s ability to be scripted which we have harnessed in the batch script below.</p>
<p>This script can be used from the command line as a ‘no questions asked’ method of uploading one or many files with a single command. Additionally, you can call this script from batch files to perform automated file uploads. A few uses for this include (but, of course, not limited to):</p>
<ul>
<li>Include in backup scripts to send data offsite.</li>
<li>Upload html/php/etc. files to a web server with a single command.</li>
<li>Create shortcuts to send a common group of files (such as a web site’s source pages).</li>
</ul>
<h2>Configuration</h2>
<p>The only configuration required is to set the FTP server connection information. Under the “Connection information” line, set the following:</p>
<ul>
<li>Server – The FTP Server you are uploading to. You can either enter the DNS name (ftp.myserver.com) or IP address (1.2.3.4).</li>
<li>UserName – Your user name for connecting to FTP server.</li>
<li>Password – Your password for connecting to the FTP server.</li>
</ul>
<p>Depending on your firewall settings, the first time you run this script you may be prompted to allow FTP to connect to the Internet. Setting this to never prompt you again should remove future warnings.</p>
<h2>The Script</h2>
<pre>@ECHO OFF
ECHO Upload to FTP
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

REM Usage:
REM UploadToFTP [/L] FileToUpload
REM
REM Required Parameters:
REM  FileToUpload
REM      The file or file containing the list of files to be uploaded.
REM
REM Optional Parameters:
REM  /L  When supplied, the FileToUpload is read as a list of files to be uploaded.
REM      A list of files should be a plain text file which has a single file on each line.
REM      Files listed in this file must specify the full path and be quoted where appropriate.

SETLOCAL EnableExtensions

REM Connection information:
SET Server=
SET UserName=
SET Password=

REM ---- Do not modify anything below this line ----

SET Commands="%TEMP%\SendToFTP_commands.txt"

REM FTP user name and password. No spaces after either.
ECHO %UserName%&#62; %Commands%
ECHO %Password%&#62;&#62; %Commands%

REM FTP transfer settings.
ECHO binary &#62;&#62; %Commands%

IF /I {%1}=={/L} (
   REM Add file(s) to the list to be FTP'ed.
   FOR /F "usebackq tokens=*" %%I IN ("%~dpnx2") DO ECHO put %%I &#62;&#62; %Commands%
) ELSE (
   ECHO put "%~dpnx1" &#62;&#62; %Commands%
)

REM Close the FTP connection.
ECHO close  &#62;&#62; %Commands%
ECHO bye    &#62;&#62; %Commands%

REM Perform the FTP.
FTP -d -i -s:%Commands% %Server%

ECHO.
ECHO.

REM Clean up.
IF EXIST %Commands% DEL %Commands%

ENDLOCAL</pre>
<h2>Links</h2>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/03/Script-UploadToFTP.zip">Download Upload to FTP Script from Sysadmin Geek</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/upload-files-to-an-ftp-site-via-a-batch-script/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>Outside of email, probably the most common way to send files to a remote party is via FTP. While there are a plethora of FTP clients you can choose from, Windows has an little known and under utilized command line FTP utility built in. The beauty of this tool lies in it’s ability to be scripted which we have harnessed in the batch script below.</p>
<p>This script can be used from the command line as a ‘no questions asked’ method of uploading one or many files with a single command. Additionally, you can call this script from batch files to perform automated file uploads. A few uses for this include (but, of course, not limited to):</p>
<ul>
<li>Include in backup scripts to send data offsite.</li>
<li>Upload html/php/etc. files to a web server with a single command.</li>
<li>Create shortcuts to send a common group of files (such as a web site’s source pages).</li>
</ul>
<h2>Configuration</h2>
<p>The only configuration required is to set the FTP server connection information. Under the “Connection information” line, set the following:</p>
<ul>
<li>Server – The FTP Server you are uploading to. You can either enter the DNS name (ftp.myserver.com) or IP address (1.2.3.4).</li>
<li>UserName – Your user name for connecting to FTP server.</li>
<li>Password – Your password for connecting to the FTP server.</li>
</ul>
<p>Depending on your firewall settings, the first time you run this script you may be prompted to allow FTP to connect to the Internet. Setting this to never prompt you again should remove future warnings.</p>
<h2>The Script</h2>
<pre>@ECHO OFF
ECHO Upload to FTP
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

REM Usage:
REM UploadToFTP [/L] FileToUpload
REM
REM Required Parameters:
REM  FileToUpload
REM      The file or file containing the list of files to be uploaded.
REM
REM Optional Parameters:
REM  /L  When supplied, the FileToUpload is read as a list of files to be uploaded.
REM      A list of files should be a plain text file which has a single file on each line.
REM      Files listed in this file must specify the full path and be quoted where appropriate.

SETLOCAL EnableExtensions

REM Connection information:
SET Server=
SET UserName=
SET Password=

REM ---- Do not modify anything below this line ----

SET Commands="%TEMP%\SendToFTP_commands.txt"

REM FTP user name and password. No spaces after either.
ECHO %UserName%&gt; %Commands%
ECHO %Password%&gt;&gt; %Commands%

REM FTP transfer settings.
ECHO binary &gt;&gt; %Commands%

IF /I {%1}=={/L} (
   REM Add file(s) to the list to be FTP'ed.
   FOR /F "usebackq tokens=*" %%I IN ("%~dpnx2") DO ECHO put %%I &gt;&gt; %Commands%
) ELSE (
   ECHO put "%~dpnx1" &gt;&gt; %Commands%
)

REM Close the FTP connection.
ECHO close  &gt;&gt; %Commands%
ECHO bye    &gt;&gt; %Commands%

REM Perform the FTP.
FTP -d -i -s:%Commands% %Server%

ECHO.
ECHO.

REM Clean up.
IF EXIST %Commands% DEL %Commands%

ENDLOCAL</pre>
<h2>Links</h2>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/03/Script-UploadToFTP.zip">Download Upload to FTP Script from Sysadmin Geek</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/upload-files-to-an-ftp-site-via-a-batch-script/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/upload-files-to-an-ftp-site-via-a-batch-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automating the Process of Deleting Old Log Files</title>
		<link>http://sysadmingeek.com/articles/automating-the-process-of-deleting-old-log-files/</link>
		<comments>http://sysadmingeek.com/articles/automating-the-process-of-deleting-old-log-files/#comments</comments>
		<pubDate>Tue, 07 Sep 2010 10:00:36 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[Windows Server]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=528</guid>
		<description><![CDATA[<p>Many services and programs out there produce log files as an audit trail for everything they are doing, however few have a function which removes these files as they outlive their usefulness. As a result, these log files sit on your system eating up space (sometimes more than you know) and cluttering directories for those times you need to access them.</p>
<p>So if you don’t need these files, why keep them? We are going to show you how to easily remove these old log files to keep you system nice and tidy.</p>
<p>Of course, while the we are covering below are immediately useful for managing log files, you can also apply the same techniques to any other type of “expiring” file (such as backups).</p>
<h2>Remove Files Based on Last Modified Date</h2>
<p>If you want to clear your existing log files based solely on the last modified date of the file, all you have to do is use the FORFILES command. For example:</p>
<blockquote><p>FORFILES /P &#8220;C:\LogFiles&#8221; /S /D -7 /C &#8220;CMD /C DEL /F /Q @PATH&#8221;</p></blockquote>
<p>The above command would delete all files from the “C:\LogFiles” folder, and all sub-folders which have not been modified in the last week.</p>
<p>The FORFILES command is pretty flexible with the search pattern and date functions. For example, in place of a number, you can enter a date such as ‘-1/13/2010’ to delete files last modified prior to the specified date.</p>
<p>To get all the details on what FORFILES can do, view the online help using the following command from the command prompt:</p>
<blockquote><p>FORFILES /?</p></blockquote>
<h2>Remove Files Based on a Date Pattern in the File Name</h2>
<p>Many applications and services produce log files based on a date pattern as to have one log file per day (i.e. Log100113.txt, Backup-2010-01-13.zip, etc.). For these types of files, it is preferable to delete based on the date of the file incorporated into the file name rather than the last modified date. This is useful for scenarios such as keeping all log files for the past 3 months. Unfortunately, Windows does not have a native command with this type of logic but with a batch script we can easily handle this task.</p>
<p>There are examples included in the usage comments on the script, so it should be pretty easy to figure out.</p>
<h3>The Script</h3>
<pre>@ECHO OFF
ECHO Delete By Date Pattern
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

REM Delete/Select files based on a date which utilizes MM and/or DD for file naming patterns.
REM
REM Usage:
REM DeleteByDatePattern {/M &#124; /D} NumberToKeep Path PatternPrefix PatternPostfix [/L &#124; /DEL]
REM    /M     Specifies the pattern being used is based on months.
REM    /D     Specifies the pattern being used is based on days.
REM    NumberToKeep
REM           The number of months (/M) or days (/D) to keep, including the current.
REM           For example, entering 1 keeps only the current month/day and 6 would keep the current minus 5.
REM    Path   The root location to search. Subdirectories will be searched.
REM    PatternPrefix
REM           The file search pattern placed before of the month/day when building the search string.
REM    PatternPostfix
REM           The file search pattern placed after of the month/day when building the search string.
REM    /L     (optional) Lists all files matching the pattern, but does not delete them.
REM    /DEL   (optional) Deletes all files matching the pattern.
REM
REM Examples:
REM    DeleteByDatePattern /M 3 "%WinDir%\system32\LogFiles" ex?? ??.log /DEL
REM       Deletes all IIS log files (Windows Server 2003) except for the current and previous two months.
REM    DeleteByDatePattern /D 7 "D:\Backup" *-????-??- .zip /DEL
REM       Deletes all zip files from the D:\Backup folder except for the current week.
REM       The file name pattern assumed above is "*-YYYY-MM-DD.zip"
REM    DeleteByDatePattern /M 0 "C:\" *( )* /L
REM       Prints a list of all files on the C drive matching the pattern: "*-MM-*" (where MM is replaced with 01-12)
REM    DeleteByDatePattern /D 14 "C:\Logs" Log-???? .txt
REM       Prints a list of all patterns which would be processed by the script.

SETLOCAL EnableExtensions EnableDelayedExpansion

REM Assumes your Windows Date/Time settings are set to 'DayOfWeek M/D/YYYY' format.
REM If your format is different, you will need to alter the variables below so they align.
FOR /F "tokens=1,2,3,4 delims=/ " %%A IN ('DATE /T') DO (
   SET Month=%%B
   SET Day=%%C
   SET Year=%%D
)

IF /I {%1}=={/M} (
   SET Keep=%Month%
   SET Max=12
)
IF /I {%1}=={/D} (
   SET Keep=%Day%
   SET Max=31
   REM Working off of the previous month's max days.
   SET /A PrevMonth=%Month%-1
   IF !PrevMonth! EQU 2 (
      SET Max=28
      REM Leap years... add more as needed.
      IF /I %Year% EQU 2012 SET Max=29
      IF /I %Year% EQU 2016 SET Max=29
   )
   IF /I !PrevMonth! EQU 4 SET Max=30
   IF /I !PrevMonth! EQU 6 SET Max=30
   IF /I !PrevMonth! EQU 9 SET Max=30
   IF /I !PrevMonth! EQU 11 SET Max=30
)
SET Current=%Keep%
SET /A Keep=%Keep%-%2+1

REM Determine the range to be removed.
SET /A RemoveHighStart=%Current%+1
IF /I %Keep% LSS 1 (
   SET RemoveLow=0
   SET /A RemoveHighEnd=%Keep%+%Max%-1
) ELSE (
   SET /A RemoveLow=%Keep%-1
   SET RemoveHighEnd=%Max%
)

REM Process all less than the low range.
FOR /L %%Z IN (1,1,%RemoveLow%) DO CALL <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess %%Z %3 %4 %5 %6
REM Process all greater than the high range.
FOR /L %%Z IN (%RemoveHighStart%,1,%RemoveHighEnd%) DO CALL <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess %%Z %3 %4 %5 %6

ENDLOCAL
GOTO End

 <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess
SET Key=0%1
SET Key=%Key:~-2%
SET Target="%~2\%~3%Key%%~4"
ECHO Target Pattern: %Target%

IF /I {%5}=={/L} DIR %Target% /B /S
IF /I {%5}=={/DEL} DEL /F /S /Q %Target%
GOTO End

:End</pre>
<h2>Automating the Process</h2>
<p>The FORFILES command is native to Windows, however the DeleteByDatePattern script should be placed in a folder defined in your Path variable (such as your Windows folder) so it can be called as though it were a native command. Once this is done, you can create a scheduled task which is either a single command (if you only need to delete from a single location) or a batch file (if you need to delete from multiple locations) which runs daily, weekly, monthly or whenever.</p>
<p>One more thing you can set and forget.</p>
<h2>Links</h2>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/04/Script-DeleteByDatePattern.zip">Download Delete By Date Pattern script from Sysadmin Geek</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/automating-the-process-of-deleting-old-log-files/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>Many services and programs out there produce log files as an audit trail for everything they are doing, however few have a function which removes these files as they outlive their usefulness. As a result, these log files sit on your system eating up space (sometimes more than you know) and cluttering directories for those times you need to access them.</p>
<p>So if you don’t need these files, why keep them? We are going to show you how to easily remove these old log files to keep you system nice and tidy.</p>
<p>Of course, while the we are covering below are immediately useful for managing log files, you can also apply the same techniques to any other type of “expiring” file (such as backups).</p>
<h2>Remove Files Based on Last Modified Date</h2>
<p>If you want to clear your existing log files based solely on the last modified date of the file, all you have to do is use the FORFILES command. For example:</p>
<blockquote><p>FORFILES /P &#8220;C:\LogFiles&#8221; /S /D -7 /C &#8220;CMD /C DEL /F /Q @PATH&#8221;</p></blockquote>
<p>The above command would delete all files from the “C:\LogFiles” folder, and all sub-folders which have not been modified in the last week.</p>
<p>The FORFILES command is pretty flexible with the search pattern and date functions. For example, in place of a number, you can enter a date such as ‘-1/13/2010’ to delete files last modified prior to the specified date.</p>
<p>To get all the details on what FORFILES can do, view the online help using the following command from the command prompt:</p>
<blockquote><p>FORFILES /?</p></blockquote>
<h2>Remove Files Based on a Date Pattern in the File Name</h2>
<p>Many applications and services produce log files based on a date pattern as to have one log file per day (i.e. Log100113.txt, Backup-2010-01-13.zip, etc.). For these types of files, it is preferable to delete based on the date of the file incorporated into the file name rather than the last modified date. This is useful for scenarios such as keeping all log files for the past 3 months. Unfortunately, Windows does not have a native command with this type of logic but with a batch script we can easily handle this task.</p>
<p>There are examples included in the usage comments on the script, so it should be pretty easy to figure out.</p>
<h3>The Script</h3>
<pre>@ECHO OFF
ECHO Delete By Date Pattern
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

REM Delete/Select files based on a date which utilizes MM and/or DD for file naming patterns.
REM
REM Usage:
REM DeleteByDatePattern {/M | /D} NumberToKeep Path PatternPrefix PatternPostfix [/L | /DEL]
REM    /M     Specifies the pattern being used is based on months.
REM    /D     Specifies the pattern being used is based on days.
REM    NumberToKeep
REM           The number of months (/M) or days (/D) to keep, including the current.
REM           For example, entering 1 keeps only the current month/day and 6 would keep the current minus 5.
REM    Path   The root location to search. Subdirectories will be searched.
REM    PatternPrefix
REM           The file search pattern placed before of the month/day when building the search string.
REM    PatternPostfix
REM           The file search pattern placed after of the month/day when building the search string.
REM    /L     (optional) Lists all files matching the pattern, but does not delete them.
REM    /DEL   (optional) Deletes all files matching the pattern.
REM
REM Examples:
REM    DeleteByDatePattern /M 3 "%WinDir%\system32\LogFiles" ex?? ??.log /DEL
REM       Deletes all IIS log files (Windows Server 2003) except for the current and previous two months.
REM    DeleteByDatePattern /D 7 "D:\Backup" *-????-??- .zip /DEL
REM       Deletes all zip files from the D:\Backup folder except for the current week.
REM       The file name pattern assumed above is "*-YYYY-MM-DD.zip"
REM    DeleteByDatePattern /M 0 "C:\" *( )* /L
REM       Prints a list of all files on the C drive matching the pattern: "*-MM-*" (where MM is replaced with 01-12)
REM    DeleteByDatePattern /D 14 "C:\Logs" Log-???? .txt
REM       Prints a list of all patterns which would be processed by the script.

SETLOCAL EnableExtensions EnableDelayedExpansion

REM Assumes your Windows Date/Time settings are set to 'DayOfWeek M/D/YYYY' format.
REM If your format is different, you will need to alter the variables below so they align.
FOR /F "tokens=1,2,3,4 delims=/ " %%A IN ('DATE /T') DO (
   SET Month=%%B
   SET Day=%%C
   SET Year=%%D
)

IF /I {%1}=={/M} (
   SET Keep=%Month%
   SET Max=12
)
IF /I {%1}=={/D} (
   SET Keep=%Day%
   SET Max=31
   REM Working off of the previous month's max days.
   SET /A PrevMonth=%Month%-1
   IF !PrevMonth! EQU 2 (
      SET Max=28
      REM Leap years... add more as needed.
      IF /I %Year% EQU 2012 SET Max=29
      IF /I %Year% EQU 2016 SET Max=29
   )
   IF /I !PrevMonth! EQU 4 SET Max=30
   IF /I !PrevMonth! EQU 6 SET Max=30
   IF /I !PrevMonth! EQU 9 SET Max=30
   IF /I !PrevMonth! EQU 11 SET Max=30
)
SET Current=%Keep%
SET /A Keep=%Keep%-%2+1

REM Determine the range to be removed.
SET /A RemoveHighStart=%Current%+1
IF /I %Keep% LSS 1 (
   SET RemoveLow=0
   SET /A RemoveHighEnd=%Keep%+%Max%-1
) ELSE (
   SET /A RemoveLow=%Keep%-1
   SET RemoveHighEnd=%Max%
)

REM Process all less than the low range.
FOR /L %%Z IN (1,1,%RemoveLow%) DO CALL <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess %%Z %3 %4 %5 %6
REM Process all greater than the high range.
FOR /L %%Z IN (%RemoveHighStart%,1,%RemoveHighEnd%) DO CALL <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess %%Z %3 %4 %5 %6

ENDLOCAL
GOTO End

 <img src='http://sysadmingeek.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> rocess
SET Key=0%1
SET Key=%Key:~-2%
SET Target="%~2\%~3%Key%%~4"
ECHO Target Pattern: %Target%

IF /I {%5}=={/L} DIR %Target% /B /S
IF /I {%5}=={/DEL} DEL /F /S /Q %Target%
GOTO End

:End</pre>
<h2>Automating the Process</h2>
<p>The FORFILES command is native to Windows, however the DeleteByDatePattern script should be placed in a folder defined in your Path variable (such as your Windows folder) so it can be called as though it were a native command. Once this is done, you can create a scheduled task which is either a single command (if you only need to delete from a single location) or a batch file (if you need to delete from multiple locations) which runs daily, weekly, monthly or whenever.</p>
<p>One more thing you can set and forget.</p>
<h2>Links</h2>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/04/Script-DeleteByDatePattern.zip">Download Delete By Date Pattern script from Sysadmin Geek</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/automating-the-process-of-deleting-old-log-files/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/automating-the-process-of-deleting-old-log-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automated Strategies for Managing Outdated Backup Files</title>
		<link>http://sysadmingeek.com/articles/automated-strategies-for-managing-outdated-backup-files/</link>
		<comments>http://sysadmingeek.com/articles/automated-strategies-for-managing-outdated-backup-files/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 10:00:51 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[Windows Server]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=933</guid>
		<description><![CDATA[<p>Backups are something which, usually, run on a very frequent schedule. If left unmanaged, a direct result of this is a large number files eating up a potentially large amount of hard drive space. Remembering to manually go in and remove backup files certainly is one method of management but shouldn’t be a long term strategy, especially when there are easy to implement automated procedures available.</p>
<p>There is no ‘one size fits all’ solution for automating the process of deleting expired backup files. Depending on the backup procedure (do you do weekly full and daily incrementals or daily full?) and file naming convention (does your backup file have the date as part of the file name or use the same file name every time?) of your resulting backup files, the applicable method differs.</p>
<p>We are going to point out several simple solutions which fit the most common backup scenarios, so odds are one will be right for you.</p>
<h2>Deleting by File Age or Date</h2>
<p><strong>When to use:</strong> Daily full backups.</p>
<p>Perhaps the simplest and most logical way to purge expired backups is to base the deletion process on the date of the backup file. We have <a href="http://sysadmingeek.com/?p=528">previously covered this topic</a> using log files as our target files, however it works just as well with backup files.</p>
<p>For example, to delete any files in the specified folder not <em>modified</em> within the past week, run this command:</p>
<blockquote><p>FORFILES /P &#8220;C:\Backups&#8221; /S /D -7 /C &#8220;CMD /C DEL /F /Q @PATH&#8221;</p>
</blockquote>
<p>Note the keyword above: modified. The ForFiles command is only capable of evaluating the modified file date as opposed to the created date which would be more applicable. Typically, however, you are probably not modifying a backup file after it is created so this will most likely not be an issue.</p>
<p>Alternately, if your backup file has some sort of numeric date pattern specified in the file name (i.e. Backup_2010-01-13.zip, BackupSet_100113_Full.zip, etc.), you can use the DeleteByDatePattern script we provided in the linked article to remove expired backups.</p>
<p>For example, to delete files older than 2 weeks matching a file name pattern like the following: “Backup_YYYY-MM-DD_(Full &#124; Incremental).zip”, you would use the command:</p>
<blockquote><p>DeleteByDatePattern /D 15 &#8220;C:\Backups&#8221; *-????-??- _*.zip /DEL</p>
</blockquote>
<p>Or if your file naming pattern is: “BackupSet_YYMMDD.zip”, you would use:</p>
<blockquote><p>DeleteByDatePattern /D 15 &#8220;C:\Backups&#8221; *-???? .zip /DEL</p>
</blockquote>
<p>Of course, adjust as needed but either of the methods above could easily be added to the start or end of your backup process to keep the number of backups stored manageable.</p>
<h2>Folder Rolling</h2>
<p><strong>When to use:</strong> Periodic full backups (weekly, bi-weekly, etc.) with daily incremental backups in between.</p>
<p>The idea behind “folder rolling” is that you store all of your current backup set (full backup + respective incrementals) in a single folder and then have several archive folders where your old backup sets are kept. Prior to a new backup set being created, you delete the folder contents containing oldest backup set and “roll” the contents of each folder down one.</p>
<p>For example, suppose we have a current backup folder with two archive folders. The batch script commands to perform the folder roll for this would be:</p>
<blockquote><p>DEL /F /Q &#8220;C:\Backups\2archive&#8221;<br />MOVE /Y &#8220;C:\Backups\1archive\*&#8221; &#8220;C:\Backups\2archive&#8221;<br />MOVE /Y &#8220;C:\Backupscurrent\*&#8221; &#8220;C:\Backups\1archive&#8221;</p>
</blockquote>
<p>You can add as many archive folders as needed. Just delete the contents of the lowest archive folder add a move command for each of the other archive folders.
<p>Again, this works best for situations where you create a periodic full backup and the a number of incremental backups up until your next full backup. Simply drop all your related backup files into a single folder and the run the folder roll script right before you create a new backup set.<br />
<h2>Backup9</h2>
<p><strong>When to use:</strong> Daily full backups or individual file backups.</p>
<p>Backup9 is a free command line utility developed by Gammadyne. Similar to the folder rolling process above, the idea behind this utility is simple in that when it is run, a copy of the target file is created with a number appended to the end. Additionally, you specify a cut-off of the number of copies to keep with the default being 9 (hence the name).</p>
<p>An example will best explain this process. Using the following command would produce the output below:</p>
<blockquote><p>BACKUP9 /A /L7 &#8220;C:\Backups\BackupFile.zip&#8221;</p>
</blockquote>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb.png" width="542" height="129"></a> </p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image1.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb1.png" width="428" height="301"></a> </p>
<p>If this command were run again, the following would happen:</p>
<ol>
<li>The number of files to keep (7 in our example) is evaluated and if there are currently that many copies, the last one is dropped.
<li>BackupFile.zip.bk7 is deleted.
<li>BackupFile.zip.bk6 is renamed to BackupFile.zip.bk7
<li>BackupFile.zip.bk[#] is renamed to BackupFile.zip.bk[#+1]
<li>BackupFile.zip.bk1 is renamed to BackupFile.zip.bk2
<li>BackupFile.zip is copied and named BackupFile.zip.bk1</li>
</ol>
<p>With the ability to keep up to 999 copies, this utility works very well if you have a file with a static name. You simply add the Backup9 command to the beginning or end of your backup process it takes care of keeping up with the appropriate number of archive copies.</p>
<h2>Belvedere Automated File Manager</h2>
<p><strong>When to use:</strong> Daily full backups.</p>
<p>Belvedere automated file manager is a utility which runs in the background monitoring file system active and performs configured actions when specified conditions are met. Among its many uses are cleaning up expired backup files.</p>
<p>The configuration of the rules are pretty straightforward. For example, to create a rule to delete backup files using a file name pattern such as “BackupSet_Jan13.zip” which are older than 2 weeks, you could use the following:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image2.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb2.png" width="632" height="428"></a> </p>
<p>While the basic function we are performing can easily be done with command line tools described above, the obvious difference is that Belvedere provides an easy to use graphical interface for those more comfortable with pointing and clicking.</p>
<p>Belvedere is designed as a desktop user application which runs from the system tray, however you can <a href="http://sysadmingeek.com/articles/using-srvstart-to-run-any-application-as-a-windows-service/">run Belvedere as a service</a> and use it on servers to perform this and other file monitoring operations.</p>
<h2>Conclusion</h2>
<p>While there are a myriad number of ways you can manage your backup expiration process, the methods we have described above are both flexible and easy to implement. With a bit of experimentation, find what works for you and go with it so you can just set it and forget it.</p>
<h2>Links</h2>
<p><a href="http://www.gammadyne.com/cmdline.htm#backup9">Download Backup9 from Gammadyne.com</a></p>
<p><a href="http://lifehacker.com/341950/belvedere-automates-your-self+cleaning-pc">Download Belvedere from Lifehacker.com</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/automated-strategies-for-managing-outdated-backup-files/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>Backups are something which, usually, run on a very frequent schedule. If left unmanaged, a direct result of this is a large number files eating up a potentially large amount of hard drive space. Remembering to manually go in and remove backup files certainly is one method of management but shouldn’t be a long term strategy, especially when there are easy to implement automated procedures available.</p>
<p>There is no ‘one size fits all’ solution for automating the process of deleting expired backup files. Depending on the backup procedure (do you do weekly full and daily incrementals or daily full?) and file naming convention (does your backup file have the date as part of the file name or use the same file name every time?) of your resulting backup files, the applicable method differs.</p>
<p>We are going to point out several simple solutions which fit the most common backup scenarios, so odds are one will be right for you.</p>
<h2>Deleting by File Age or Date</h2>
<p><strong>When to use:</strong> Daily full backups.</p>
<p>Perhaps the simplest and most logical way to purge expired backups is to base the deletion process on the date of the backup file. We have <a href="http://sysadmingeek.com/?p=528">previously covered this topic</a> using log files as our target files, however it works just as well with backup files.</p>
<p>For example, to delete any files in the specified folder not <em>modified</em> within the past week, run this command:</p>
<blockquote><p>FORFILES /P &#8220;C:\Backups&#8221; /S /D -7 /C &#8220;CMD /C DEL /F /Q @PATH&#8221;</p>
</blockquote>
<p>Note the keyword above: modified. The ForFiles command is only capable of evaluating the modified file date as opposed to the created date which would be more applicable. Typically, however, you are probably not modifying a backup file after it is created so this will most likely not be an issue.</p>
<p>Alternately, if your backup file has some sort of numeric date pattern specified in the file name (i.e. Backup_2010-01-13.zip, BackupSet_100113_Full.zip, etc.), you can use the DeleteByDatePattern script we provided in the linked article to remove expired backups.</p>
<p>For example, to delete files older than 2 weeks matching a file name pattern like the following: “Backup_YYYY-MM-DD_(Full | Incremental).zip”, you would use the command:</p>
<blockquote><p>DeleteByDatePattern /D 15 &#8220;C:\Backups&#8221; *-????-??- _*.zip /DEL</p>
</blockquote>
<p>Or if your file naming pattern is: “BackupSet_YYMMDD.zip”, you would use:</p>
<blockquote><p>DeleteByDatePattern /D 15 &#8220;C:\Backups&#8221; *-???? .zip /DEL</p>
</blockquote>
<p>Of course, adjust as needed but either of the methods above could easily be added to the start or end of your backup process to keep the number of backups stored manageable.</p>
<h2>Folder Rolling</h2>
<p><strong>When to use:</strong> Periodic full backups (weekly, bi-weekly, etc.) with daily incremental backups in between.</p>
<p>The idea behind “folder rolling” is that you store all of your current backup set (full backup + respective incrementals) in a single folder and then have several archive folders where your old backup sets are kept. Prior to a new backup set being created, you delete the folder contents containing oldest backup set and “roll” the contents of each folder down one.</p>
<p>For example, suppose we have a current backup folder with two archive folders. The batch script commands to perform the folder roll for this would be:</p>
<blockquote><p>DEL /F /Q &#8220;C:\Backups\2archive&#8221;<br />MOVE /Y &#8220;C:\Backups\1archive\*&#8221; &#8220;C:\Backups\2archive&#8221;<br />MOVE /Y &#8220;C:\Backupscurrent\*&#8221; &#8220;C:\Backups\1archive&#8221;</p>
</blockquote>
<p>You can add as many archive folders as needed. Just delete the contents of the lowest archive folder add a move command for each of the other archive folders.
<p>Again, this works best for situations where you create a periodic full backup and the a number of incremental backups up until your next full backup. Simply drop all your related backup files into a single folder and the run the folder roll script right before you create a new backup set.<br />
<h2>Backup9</h2>
<p><strong>When to use:</strong> Daily full backups or individual file backups.</p>
<p>Backup9 is a free command line utility developed by Gammadyne. Similar to the folder rolling process above, the idea behind this utility is simple in that when it is run, a copy of the target file is created with a number appended to the end. Additionally, you specify a cut-off of the number of copies to keep with the default being 9 (hence the name).</p>
<p>An example will best explain this process. Using the following command would produce the output below:</p>
<blockquote><p>BACKUP9 /A /L7 &#8220;C:\Backups\BackupFile.zip&#8221;</p>
</blockquote>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb.png" width="542" height="129"></a> </p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image1.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb1.png" width="428" height="301"></a> </p>
<p>If this command were run again, the following would happen:</p>
<ol>
<li>The number of files to keep (7 in our example) is evaluated and if there are currently that many copies, the last one is dropped.
<li>BackupFile.zip.bk7 is deleted.
<li>BackupFile.zip.bk6 is renamed to BackupFile.zip.bk7
<li>BackupFile.zip.bk[#] is renamed to BackupFile.zip.bk[#+1]
<li>BackupFile.zip.bk1 is renamed to BackupFile.zip.bk2
<li>BackupFile.zip is copied and named BackupFile.zip.bk1</li>
</ol>
<p>With the ability to keep up to 999 copies, this utility works very well if you have a file with a static name. You simply add the Backup9 command to the beginning or end of your backup process it takes care of keeping up with the appropriate number of archive copies.</p>
<h2>Belvedere Automated File Manager</h2>
<p><strong>When to use:</strong> Daily full backups.</p>
<p>Belvedere automated file manager is a utility which runs in the background monitoring file system active and performs configured actions when specified conditions are met. Among its many uses are cleaning up expired backup files.</p>
<p>The configuration of the rules are pretty straightforward. For example, to create a rule to delete backup files using a file name pattern such as “BackupSet_Jan13.zip” which are older than 2 weeks, you could use the following:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/07/image2.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/07/image_thumb2.png" width="632" height="428"></a> </p>
<p>While the basic function we are performing can easily be done with command line tools described above, the obvious difference is that Belvedere provides an easy to use graphical interface for those more comfortable with pointing and clicking.</p>
<p>Belvedere is designed as a desktop user application which runs from the system tray, however you can <a href="http://sysadmingeek.com/articles/using-srvstart-to-run-any-application-as-a-windows-service/">run Belvedere as a service</a> and use it on servers to perform this and other file monitoring operations.</p>
<h2>Conclusion</h2>
<p>While there are a myriad number of ways you can manage your backup expiration process, the methods we have described above are both flexible and easy to implement. With a bit of experimentation, find what works for you and go with it so you can just set it and forget it.</p>
<h2>Links</h2>
<p><a href="http://www.gammadyne.com/cmdline.htm#backup9">Download Backup9 from Gammadyne.com</a></p>
<p><a href="http://lifehacker.com/341950/belvedere-automates-your-self+cleaning-pc">Download Belvedere from Lifehacker.com</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/automated-strategies-for-managing-outdated-backup-files/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/automated-strategies-for-managing-outdated-backup-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Setup milter-greylist Spam Blocking in Sendmail</title>
		<link>http://sysadmingeek.com/articles/how-to-setup-milter-greylist-spam-blocking-in-sendmail/</link>
		<comments>http://sysadmingeek.com/articles/how-to-setup-milter-greylist-spam-blocking-in-sendmail/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 10:00:05 +0000</pubDate>
		<dc:creator>Thom Jones</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=948</guid>
		<description><![CDATA[<p>Virtually all linux distributions include sendmail as the default MTA. Which is okay &#8211; it has been around for a long time, is stable and it works great (although the postfix afficionados might disagree!).  But it has nothing built in for spam control which is good; it was not designed for that.  So you&#8217;ve installed spamassassin and it works good but you still are getting unflagged spam emails through.  Perhaps you need to try greylisting.</p>
<p>Greylisting is the process by which all email (unless specifically  whitelisted) gets initially rejected yet works within the parameters of the various RFCs to ensure eventual receipt of email.  The idea is that spammers will not attempt to reconnect to an email server that has rejected their offerings yet legitimate mail servers will. It isn&#8217;t foolproof &#8211; spammers are quick to adjust and greylisting has been around a long time.  But it does help.</p>
<p>This article is on how to install milter-greylist which was originally written by Emmanuel Dreyfus.  I will be concentrating with sendmail here but milter-greylist is also supported with postfix.  </p>
<p>First, check your dependencies.  From the README:</p>
<blockquote><p>Build dependencies:<br />
- flex (AT&#038;T lex cannot build milter-greylist sources)<br />
- yacc or bison (some older yacc will fail, use bison instead)<br />
- libmilter (comes with Sendmail, or with the sendmail-devel<br />
  package on RedHat, Fedora and SuSE. Debian and Ubuntu have it<br />
  in libmilter-dev)<br />
- Any POSIX threads library (Provided by libc on some systems)</p>
<p>Optional dependencies:<br />
- libspf2, libspf_alt or libspf, for SPF support<br />
- libcurl, for URL checks support<br />
- libGeoIP, for GeoIP support<br />
- libbind from BIND 9, for DNSRBL support, except if your system has a thread-safe DNS resolver built-in.</p></blockquote>
<p>But the configuration process will find anything that you don&#8217;t have installed and complain until the dependency is resolved.</p>
<p>Next, download the greylist-milter from  <a href="http://hcpnet.free.fr/milter-greylist/">http://hcpnet.free.fr/milter-greylist</a> and unpack the tarball. Then read the README file!  It includes a wealth of information that isn&#8217;t covered in this article especially for installs that want/need to include special features such as SPF support.  </p>
<p>And do the usual </p>
<blockquote><p>./configure<br />
./make<br />
./make install</p></blockquote>
<p>The standard install will put the binaries in /usr/local/bin, the database and pid file in /var/milter-greylist and the configuration file will be /etc/mail/greylist.conf.  Some startup scripts are included in the tarball but they are not installed automatically.  You will have to set it up in your /etc/init.d yourself if you want to use one.</p>
<p>You will then need to configure sendmail to actually use the milter.  In your sendmail.mc file, add the following (but pay close attention to the warnings in the README file if you are already using other milters in your installation!):</p>
<blockquote><p><code>INPUT_MAIL_FILTER(`greylist',`S=local:/var/milter-greylist/milter-greylist.sock')dnl<br />
define(`confMILTER_MACROS_CONNECT', `j, {if_addr}')dnl<br />
define(`confMILTER_MACROS_HELO', `{verify}, {cert_subject}')dnl<br />
define(`confMILTER_MACROS_ENVFROM', `i, {auth_authen}')dnl<br />
define(`confMILTER_MACROS_ENVRCPT', `{greylist}')dnl<br />
</code></p></blockquote>
<p>and reconfigure your sendmail.cf file:</p>
<blockquote><p><code>#m4 sendmail.mc > sendmail.cf</code></p></blockquote>
<p>Don&#8217;t restart your sendmail daemon just yet, however &#8211; we still have to modify the configuration for this to work properly.</p>
<p>Open /etc/mail/greylist.conf in your favorite editor (which, of course, is vi, right?).<br />
Uncomment or add the following:</p>
<blockquote><p><code>quiet<br />
greylist 7m<br />
dumpfreq 1d<br />
autowhite 10d</code></p></blockquote>
<p>In the above configuration, &#8216;quiet&#8217; will not include a time frame to retry submission.  This is good so that there is no way for spammers to know how long they will be blocked.  Greylisting will be for 7 minutes after which email from the source will be accepted, database contents will be dumped to the /var/milter-greylist/greylist.db once per day, and, once an email is accepted from a source, that source will be whitelisted for 10 days before being greylisted again.</p>
<p>Also create lists to whitelist your own networks to the configuration file:</p>
<blockquote><p><code>list "my network" addr { 127.0.0.1/8 10.230.1.0/24 192.168.1.0/24 }</code></p></blockquote>
<p>which will whitelist local, DMZ and internal networks (as an example &#8211; yours are probably different).  Notice the space between network addresses, <strong>not</strong> commas.<br />
Along with other external networks that are always trusted:</p>
<blockquote><p><code># Trusted networks to not greylist:<br />
list "trusted" addr { \<br />
        207.46.0.0/16 \       # Microsoft<br />
         72.33.0.0/16 \       # UW Madison<br />
}</code></p></blockquote>
<p>There is a fairly comprehensive list of &#8216;broken&#8217; mailer servers in the configuration file that are also always to be whitelisted since greylisting them would most likely result in never getting email from them.  You can add to that list as needed as well if you need to.</p>
<p>You will most likely be setting up greylisting as the default, so you may also want to whitelist certain users who never want email to be delayed (various pompous vice presidents, system alert addresses and the like):</p>
<blockquote><p><code># List of users that want whitelisting (if greylisting is the default):<br />
list "white users" rcpt { \<br />
        vp@domain.com \<br />
        sysadmin@domain.com \<br />
        postmaster@domain.com \<br />
} </code></p></blockquote>
<p>Notice the list names of &#8220;my network&#8221;, &#8220;trusted&#8221; and &#8220;white users&#8221; &#8211; you need to add these to the actual whitelisting config line:</p>
<blockquote><p><code># And here is the access list<br />
racl whitelist list "my network"<br />
racl whitelist list "broken mta"<br />
racl whitelist list "trusted"<br />
racl whitelist list "white users"</code></p></blockquote>
<p>Note:  You can also set this up to whitelist as the default in which case you would also create a &#8220;grey users&#8221; list of those folk you want to always be subject to greylisting.  Those would include errant users who post their work email address all over social network sites, sales web sites and newsletter subscriptions, of course.</p>
<p>And then configure the default operation of milter-greylist:</p>
<blockquote><p><code>racl greylist default</code></p></blockquote>
<p>(use racl whitelist default if you want whitelisting to be the default operation).</p>
<p>And then fire up your milter-greylist binary either using the /etc/init.d/milter-greylist startup script or by </p>
<blockquote><p><code>#milter-greylist -f /etc/mail/greylist.config</code></p></blockquote>
<p>at the command line.  There are a slew of other command line options (many of which duplicate parameters set in the conf file).  See </p>
<blockquote><p>man milter-greylist</p></blockquote>
<p>for further details.</p>
<p>And then restart your sendmail daemon and enjoy less spam coming into your mail server.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-setup-milter-greylist-spam-blocking-in-sendmail/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>Virtually all linux distributions include sendmail as the default MTA. Which is okay &#8211; it has been around for a long time, is stable and it works great (although the postfix afficionados might disagree!).  But it has nothing built in for spam control which is good; it was not designed for that.  So you&#8217;ve installed spamassassin and it works good but you still are getting unflagged spam emails through.  Perhaps you need to try greylisting.</p>
<p>Greylisting is the process by which all email (unless specifically  whitelisted) gets initially rejected yet works within the parameters of the various RFCs to ensure eventual receipt of email.  The idea is that spammers will not attempt to reconnect to an email server that has rejected their offerings yet legitimate mail servers will. It isn&#8217;t foolproof &#8211; spammers are quick to adjust and greylisting has been around a long time.  But it does help.</p>
<p>This article is on how to install milter-greylist which was originally written by Emmanuel Dreyfus.  I will be concentrating with sendmail here but milter-greylist is also supported with postfix.  </p>
<p>First, check your dependencies.  From the README:</p>
<blockquote><p>Build dependencies:<br />
- flex (AT&#038;T lex cannot build milter-greylist sources)<br />
- yacc or bison (some older yacc will fail, use bison instead)<br />
- libmilter (comes with Sendmail, or with the sendmail-devel<br />
  package on RedHat, Fedora and SuSE. Debian and Ubuntu have it<br />
  in libmilter-dev)<br />
- Any POSIX threads library (Provided by libc on some systems)</p>
<p>Optional dependencies:<br />
- libspf2, libspf_alt or libspf, for SPF support<br />
- libcurl, for URL checks support<br />
- libGeoIP, for GeoIP support<br />
- libbind from BIND 9, for DNSRBL support, except if your system has a thread-safe DNS resolver built-in.</p></blockquote>
<p>But the configuration process will find anything that you don&#8217;t have installed and complain until the dependency is resolved.</p>
<p>Next, download the greylist-milter from  <a href="http://hcpnet.free.fr/milter-greylist/">http://hcpnet.free.fr/milter-greylist</a> and unpack the tarball. Then read the README file!  It includes a wealth of information that isn&#8217;t covered in this article especially for installs that want/need to include special features such as SPF support.  </p>
<p>And do the usual </p>
<blockquote><p>./configure<br />
./make<br />
./make install</p></blockquote>
<p>The standard install will put the binaries in /usr/local/bin, the database and pid file in /var/milter-greylist and the configuration file will be /etc/mail/greylist.conf.  Some startup scripts are included in the tarball but they are not installed automatically.  You will have to set it up in your /etc/init.d yourself if you want to use one.</p>
<p>You will then need to configure sendmail to actually use the milter.  In your sendmail.mc file, add the following (but pay close attention to the warnings in the README file if you are already using other milters in your installation!):</p>
<blockquote><p><code>INPUT_MAIL_FILTER(`greylist',`S=local:/var/milter-greylist/milter-greylist.sock')dnl<br />
define(`confMILTER_MACROS_CONNECT', `j, {if_addr}')dnl<br />
define(`confMILTER_MACROS_HELO', `{verify}, {cert_subject}')dnl<br />
define(`confMILTER_MACROS_ENVFROM', `i, {auth_authen}')dnl<br />
define(`confMILTER_MACROS_ENVRCPT', `{greylist}')dnl<br />
</code></p></blockquote>
<p>and reconfigure your sendmail.cf file:</p>
<blockquote><p><code>#m4 sendmail.mc > sendmail.cf</code></p></blockquote>
<p>Don&#8217;t restart your sendmail daemon just yet, however &#8211; we still have to modify the configuration for this to work properly.</p>
<p>Open /etc/mail/greylist.conf in your favorite editor (which, of course, is vi, right?).<br />
Uncomment or add the following:</p>
<blockquote><p><code>quiet<br />
greylist 7m<br />
dumpfreq 1d<br />
autowhite 10d</code></p></blockquote>
<p>In the above configuration, &#8216;quiet&#8217; will not include a time frame to retry submission.  This is good so that there is no way for spammers to know how long they will be blocked.  Greylisting will be for 7 minutes after which email from the source will be accepted, database contents will be dumped to the /var/milter-greylist/greylist.db once per day, and, once an email is accepted from a source, that source will be whitelisted for 10 days before being greylisted again.</p>
<p>Also create lists to whitelist your own networks to the configuration file:</p>
<blockquote><p><code>list "my network" addr { 127.0.0.1/8 10.230.1.0/24 192.168.1.0/24 }</code></p></blockquote>
<p>which will whitelist local, DMZ and internal networks (as an example &#8211; yours are probably different).  Notice the space between network addresses, <strong>not</strong> commas.<br />
Along with other external networks that are always trusted:</p>
<blockquote><p><code># Trusted networks to not greylist:<br />
list "trusted" addr { \<br />
        207.46.0.0/16 \       # Microsoft<br />
         72.33.0.0/16 \       # UW Madison<br />
}</code></p></blockquote>
<p>There is a fairly comprehensive list of &#8216;broken&#8217; mailer servers in the configuration file that are also always to be whitelisted since greylisting them would most likely result in never getting email from them.  You can add to that list as needed as well if you need to.</p>
<p>You will most likely be setting up greylisting as the default, so you may also want to whitelist certain users who never want email to be delayed (various pompous vice presidents, system alert addresses and the like):</p>
<blockquote><p><code># List of users that want whitelisting (if greylisting is the default):<br />
list "white users" rcpt { \<br />
        vp@domain.com \<br />
        sysadmin@domain.com \<br />
        postmaster@domain.com \<br />
} </code></p></blockquote>
<p>Notice the list names of &#8220;my network&#8221;, &#8220;trusted&#8221; and &#8220;white users&#8221; &#8211; you need to add these to the actual whitelisting config line:</p>
<blockquote><p><code># And here is the access list<br />
racl whitelist list "my network"<br />
racl whitelist list "broken mta"<br />
racl whitelist list "trusted"<br />
racl whitelist list "white users"</code></p></blockquote>
<p>Note:  You can also set this up to whitelist as the default in which case you would also create a &#8220;grey users&#8221; list of those folk you want to always be subject to greylisting.  Those would include errant users who post their work email address all over social network sites, sales web sites and newsletter subscriptions, of course.</p>
<p>And then configure the default operation of milter-greylist:</p>
<blockquote><p><code>racl greylist default</code></p></blockquote>
<p>(use racl whitelist default if you want whitelisting to be the default operation).</p>
<p>And then fire up your milter-greylist binary either using the /etc/init.d/milter-greylist startup script or by </p>
<blockquote><p><code>#milter-greylist -f /etc/mail/greylist.config</code></p></blockquote>
<p>at the command line.  There are a slew of other command line options (many of which duplicate parameters set in the conf file).  See </p>
<blockquote><p>man milter-greylist</p></blockquote>
<p>for further details.</p>
<p>And then restart your sendmail daemon and enjoy less spam coming into your mail server.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-setup-milter-greylist-spam-blocking-in-sendmail/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/how-to-setup-milter-greylist-spam-blocking-in-sendmail/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Prevent Yum from Updating the Kernel</title>
		<link>http://sysadmingeek.com/articles/how-to-prevent-yum-from-updating-the-kernel/</link>
		<comments>http://sysadmingeek.com/articles/how-to-prevent-yum-from-updating-the-kernel/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 10:00:13 +0000</pubDate>
		<dc:creator>Thom Jones</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[updates]]></category>
		<category><![CDATA[yum]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=898</guid>
		<description><![CDATA[<p>When you&#8217;re running production servers, the one thing you don&#8217;t want to do is upgrade the kernel every time a new update comes out. Why? Because that&#8217;s the only Linux update operation that requires a reboot once it&#8217;s done—and in a production environment you often can&#8217;t have downtime.</p>
<h3>The Scenario</h3>
<p>So you finally have your rpm based server set, stable and secure.  Life is good and you don&#8217;t figure you have to do anything else for some time.</p>
<p>Then, for some reason, you run at the command line as root:</p>
<p>
<blockquote>#yum -y -d0 update</p></blockquote>
<p>Which just happens to supply an affirmative answer to all prompts for the yum command. Which also happens to run as quietly as possible. And which happens this time to include an update to the kernel packages.</p>
<p>And now things are not working correctly.  How could you have prevented this?</p>
<p>Although you obviously and desperately need a vacation now, you should revisit your system update schedule, your documentation (which, of course, is meticulous, current and readily available) and especially the configuration files that control yum.</p>
<p>But first, why wouldn&#8217;t you want to update the kernel?</p>
<ol>
<li>Things sometimes break.  An update might make modules or drivers incompatible so devices such as a wireless card are no longer functional.</li>
<li>Maintain versions across server populations.  This would certainly apply if you have a mix of different server distributions along with some home built boxes.</li>
<li>Compiled the kernel manually, thus bypassing the automatic configuration supplied by yum</li>
<li>You are horribly proud of your uptime so performing a reboot to activate the  new kernel would not be in your best interest.  So if you never reboot, there is never a need to update it.</li>
</ol>
<p>Why would you want to update the kernel?</p>
<ol>
<li>Primarily &#8211; security.  Kernels have holes just like applications and, if not patched, can provide opportunities for the compromising of the system by the bad guys.</li>
<li>Especially if you are not using a 3rd party repository, to keep your version as up to date as possible.  Major distros release patches to all of their included code including the kernel and strive to test it before release to ensure stability.  To not update is to lag behind which might make things more difficult when performing an upgrade to a major version release.</li>
<li>Taking advantage of a new feature (or to fix a previously broken one) would make you possibly more amenable to a kernel update.</li>
</ol>
<p>To update the kernel just do what you did above.  Or, better, eliminate the  command line switches so you have some control over the update process and can see what is happening.  Run:</p>
<p>
<blockquote>#yum update</p></blockquote>
<p>and follow the prompts.</p>
<h3>Preventing Yum from Updating the Kernel</h3>
<p>However, if you don&#8217;t ever want to just blindly have the kernel updated, you can add the following to your /etc/yum.conf file:</p>
<p>
<blockquote>exclude=kernel*</p></blockquote>
<p>Or, if you insist on using a vanilla configuration file and control everything via the CLI, use</p>
<p>
<blockquote>#yum &#8211;exclude=kernel* update</p></blockquote>
<p>Both of these methods will eliminate the kernel from being updated or even included in the potential update listing.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-prevent-yum-from-updating-the-kernel/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re running production servers, the one thing you don&#8217;t want to do is upgrade the kernel every time a new update comes out. Why? Because that&#8217;s the only Linux update operation that requires a reboot once it&#8217;s done—and in a production environment you often can&#8217;t have downtime.</p>
<h3>The Scenario</h3>
<p>So you finally have your rpm based server set, stable and secure.  Life is good and you don&#8217;t figure you have to do anything else for some time.</p>
<p>Then, for some reason, you run at the command line as root:</p>
<p>
<blockquote>#yum -y -d0 update</p></blockquote>
<p>Which just happens to supply an affirmative answer to all prompts for the yum command. Which also happens to run as quietly as possible. And which happens this time to include an update to the kernel packages.</p>
<p>And now things are not working correctly.  How could you have prevented this?</p>
<p>Although you obviously and desperately need a vacation now, you should revisit your system update schedule, your documentation (which, of course, is meticulous, current and readily available) and especially the configuration files that control yum.</p>
<p>But first, why wouldn&#8217;t you want to update the kernel?</p>
<ol>
<li>Things sometimes break.  An update might make modules or drivers incompatible so devices such as a wireless card are no longer functional.</li>
<li>Maintain versions across server populations.  This would certainly apply if you have a mix of different server distributions along with some home built boxes.</li>
<li>Compiled the kernel manually, thus bypassing the automatic configuration supplied by yum</li>
<li>You are horribly proud of your uptime so performing a reboot to activate the  new kernel would not be in your best interest.  So if you never reboot, there is never a need to update it.</li>
</ol>
<p>Why would you want to update the kernel?</p>
<ol>
<li>Primarily &#8211; security.  Kernels have holes just like applications and, if not patched, can provide opportunities for the compromising of the system by the bad guys.</li>
<li>Especially if you are not using a 3rd party repository, to keep your version as up to date as possible.  Major distros release patches to all of their included code including the kernel and strive to test it before release to ensure stability.  To not update is to lag behind which might make things more difficult when performing an upgrade to a major version release.</li>
<li>Taking advantage of a new feature (or to fix a previously broken one) would make you possibly more amenable to a kernel update.</li>
</ol>
<p>To update the kernel just do what you did above.  Or, better, eliminate the  command line switches so you have some control over the update process and can see what is happening.  Run:</p>
<p>
<blockquote>#yum update</p></blockquote>
<p>and follow the prompts.</p>
<h3>Preventing Yum from Updating the Kernel</h3>
<p>However, if you don&#8217;t ever want to just blindly have the kernel updated, you can add the following to your /etc/yum.conf file:</p>
<p>
<blockquote>exclude=kernel*</p></blockquote>
<p>Or, if you insist on using a vanilla configuration file and control everything via the CLI, use</p>
<p>
<blockquote>#yum &#8211;exclude=kernel* update</p></blockquote>
<p>Both of these methods will eliminate the kernel from being updated or even included in the potential update listing.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-prevent-yum-from-updating-the-kernel/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/how-to-prevent-yum-from-updating-the-kernel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Change Your Linux Hostname Without Rebooting</title>
		<link>http://sysadmingeek.com/articles/how-to-change-your-linux-hostname-without-rebooting/</link>
		<comments>http://sysadmingeek.com/articles/how-to-change-your-linux-hostname-without-rebooting/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 10:00:44 +0000</pubDate>
		<dc:creator>Thom Jones</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[General Networking]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=631</guid>
		<description><![CDATA[<p>If you&#8217;ve worked in the admin world for any length of time, you&#8217;ve probably run into an instance where you needed to change the hostnames on your server to match some corporate naming standard, but you can&#8217;t have downtime either. So how do you change the hostname without rebooting?</p>
<h3>Changing the Hostname</h3>
<p>First, you must change the config file that controls this.  The actual file and its location will vary across distributions.  In the Redhat derivatives, the file to modify is /etc/sysconfig/network so vi this file and change the line that reads HOSTNAME=</p>
<p>From this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap12.jpg"><img class="alignnone size-full wp-image-641" title="cap1" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap12.jpg" alt="" width="682" height="493" /></a></p>
<p>To this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap22.jpg"><img class="alignnone size-full wp-image-642" title="cap2" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap22.jpg" alt="" width="682" height="493" /></a></p>
<p>For SuSE distributions you would similarly change the /etc/HOSTNAME file while Debian admins would modify the /etc/hostname file to set the new name.</p>
<p>Next, the /etc/hosts file needs to be changed.  This is identical across all flavors and consists of using your favorite text editor and modifying the old hostname within.  Such as from this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap32.jpg"><img class="alignnone size-full wp-image-643" title="cap3" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap32.jpg" alt="" width="682" height="493" /></a></p>
<p>To this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap42.jpg"><img class="alignnone size-full wp-image-644" title="cap4" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap42.jpg" alt="" width="682" height="493" /></a></p>
<p>“But”, you mutter under your breath, “I just typed in `hostname` and got &#8216;Snoopy&#8217; as a result.  It doesn&#8217;t work!”.</p>
<p>What you need to know is that the previous steps are to permanently set the new name.  You are much too quick to judge, obviously.  So, continue on by entering (at the command line as root or a sudoer):</p>
<blockquote><p># hostname mdmvr14s9db</p></blockquote>
<p>This will set the hostname for now but the change is not saved (that is what the above steps are for, remember?).  Go ahead – test it.  Type in `hostname` (without the tickmarks ) and the command should return  &#8216;mdmvr14s9db&#8217; (without the single quotes).</p>
<p>Now let&#8217;s set it in stone.  If you are using chkconfig and service commands (RedHat family folk, usually), you can simply type</p>
<blockquote><p>#service network restart</p></blockquote>
<p>which will restart the network with the new host name.  The rest of you should be able to type</p>
<blockquote><p>#/etc/init.d/network restart</p></blockquote>
<p>to obtain the same results.</p>
<p>Then test again with the hostname command – you should get the new name returned.</p>
<p>This has been the easy part.  Hopefully, prior to starting this, you checked all application conf files for any hard coded reference to the new name and changed that as well.  And you need to then change your DNS &#8216;A&#8217; record to also reflect the new name.  And once you have restarted named with the new name on the DNS you will have succeeded in temporarily irritating around half of those 18,000 users previously mentioned who now can&#8217;t get to the server since the name has not propagated around the network yet. But this too shall pass as long as you hide long enough.</p>
<p>And at least you can keep the small stuffed plush Snoopy sitting at your desk to remind you of that gentler, simpler time.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-change-your-linux-hostname-without-rebooting/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve worked in the admin world for any length of time, you&#8217;ve probably run into an instance where you needed to change the hostnames on your server to match some corporate naming standard, but you can&#8217;t have downtime either. So how do you change the hostname without rebooting?</p>
<h3>Changing the Hostname</h3>
<p>First, you must change the config file that controls this.  The actual file and its location will vary across distributions.  In the Redhat derivatives, the file to modify is /etc/sysconfig/network so vi this file and change the line that reads HOSTNAME=</p>
<p>From this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap12.jpg"><img class="alignnone size-full wp-image-641" title="cap1" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap12.jpg" alt="" width="682" height="493" /></a></p>
<p>To this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap22.jpg"><img class="alignnone size-full wp-image-642" title="cap2" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap22.jpg" alt="" width="682" height="493" /></a></p>
<p>For SuSE distributions you would similarly change the /etc/HOSTNAME file while Debian admins would modify the /etc/hostname file to set the new name.</p>
<p>Next, the /etc/hosts file needs to be changed.  This is identical across all flavors and consists of using your favorite text editor and modifying the old hostname within.  Such as from this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap32.jpg"><img class="alignnone size-full wp-image-643" title="cap3" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap32.jpg" alt="" width="682" height="493" /></a></p>
<p>To this:</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/06/cap42.jpg"><img class="alignnone size-full wp-image-644" title="cap4" src="http://sysadmingeek.com/wp-content/uploads/2010/06/cap42.jpg" alt="" width="682" height="493" /></a></p>
<p>“But”, you mutter under your breath, “I just typed in `hostname` and got &#8216;Snoopy&#8217; as a result.  It doesn&#8217;t work!”.</p>
<p>What you need to know is that the previous steps are to permanently set the new name.  You are much too quick to judge, obviously.  So, continue on by entering (at the command line as root or a sudoer):</p>
<blockquote><p># hostname mdmvr14s9db</p></blockquote>
<p>This will set the hostname for now but the change is not saved (that is what the above steps are for, remember?).  Go ahead – test it.  Type in `hostname` (without the tickmarks ) and the command should return  &#8216;mdmvr14s9db&#8217; (without the single quotes).</p>
<p>Now let&#8217;s set it in stone.  If you are using chkconfig and service commands (RedHat family folk, usually), you can simply type</p>
<blockquote><p>#service network restart</p></blockquote>
<p>which will restart the network with the new host name.  The rest of you should be able to type</p>
<blockquote><p>#/etc/init.d/network restart</p></blockquote>
<p>to obtain the same results.</p>
<p>Then test again with the hostname command – you should get the new name returned.</p>
<p>This has been the easy part.  Hopefully, prior to starting this, you checked all application conf files for any hard coded reference to the new name and changed that as well.  And you need to then change your DNS &#8216;A&#8217; record to also reflect the new name.  And once you have restarted named with the new name on the DNS you will have succeeded in temporarily irritating around half of those 18,000 users previously mentioned who now can&#8217;t get to the server since the name has not propagated around the network yet. But this too shall pass as long as you hide long enough.</p>
<p>And at least you can keep the small stuffed plush Snoopy sitting at your desk to remind you of that gentler, simpler time.</p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-change-your-linux-hostname-without-rebooting/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/how-to-change-your-linux-hostname-without-rebooting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Diagnose Linux Server Load Problems with a Simple Script</title>
		<link>http://sysadmingeek.com/articles/diagnose-linux-server-load-problems-with-a-simple-script/</link>
		<comments>http://sysadmingeek.com/articles/diagnose-linux-server-load-problems-with-a-simple-script/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 10:00:12 +0000</pubDate>
		<dc:creator>Thom Jones</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[shell scripts]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=934</guid>
		<description><![CDATA[<p>If you have been an admin for any length of time, you have certainly discovered situations where a server spikes in CPU use or memory utilization and/or load levels.  Running `top` won&#8217;t always give you the answer, either.  So how do you find those sneaky processes that are chewing up your system resources to be able to kill &#8216;em?</p>
<p>The following script might be able to help.  It was written for a web server, so has some parts of it that are specifically looking for httpd processes and some parts that deal with MySQL.  Depending on your server deployment, simply comment/delete those sections and add others.  It should be used for a starting point.  </p>
<p>Prerequisites for this version of the script is some freeware released under the GNU General Public License called mytop (available at <a href="http://jeremy.zawodny.com/mysql/mytop/">http://jeremy.zawodny.com/mysql/mytop/</a>) which is a fantastic tool for checking how MySQL is performing.  It is getting old, but still works great for our purposes here.<br />
Additionally, I use mutt as the mailer &#8211; you may want to change the script to simply use the linux built in `mail` utility.  I run it via cron every hour; adjust as you see fit.  Oh &#8211; and this script needs to run as root since it does read from some protected areas of the server.</p>
<p>So let&#8217;s get started, shall we?</p>
<p>First, set your script variables:</p>
<blockquote><p><code>#!/bin/bash<br />
#<br />
# Script to check system load average levels to try to determine<br />
# what processes are taking it overly high...<br />
#<br />
# 07Jul2010  tjones<br />
#<br />
# set environment<br />
dt=`date +%d%b%Y-%X`<br />
# Obviously, change the following directories to where your log files actually are kept<br />
tmpfile="/tmp/checkSystemLoad.tmp"<br />
logfile="/tmp/checkSystemLoad.log"<br />
msgLog="/var/log/messages"<br />
mysqlLog="/var/log/mysqld.log"<br />
# the first mailstop is standard email for reports.  Second one is for cell phone (with a pared down report)<br />
mailstop="sysadmin@mydomain.com"<br />
mailstop1="15555555555@mycellphone.com"<br />
machine=`hostname`<br />
# The following three are for mytop use - use a db user that has decent rights<br />
dbusr="username"<br />
dbpw="password"<br />
db="yourdatabasename"<br />
# The following is the load level to check on - 10 is really high, so you might want to lower it.<br />
levelToCheck=10</code>
</p></blockquote>
<p>Next, check your load level to see if the script should continue:</p>
<blockquote><p><code># Set variables from system:<br />
loadLevel=`cat /proc/loadavg &#124; awk '{print $1}'`<br />
loadLevel=$( printf "%0.f" $loadLevel )</p>
<p># if the load level is greater than you want, start the script process. Otherwise, exit 0</p>
<p>if [ $loadLevel -gt $levelToCheck ]; then<br />
    echo "" > $tmpfile<br />
    echo "**************************************" >>$tmpfile<br />
    echo "Date: $dt                             " >>$tmpfile<br />
    echo "Check System Load &#038; Processes         " >>$tmpfile<br />
    echo "**************************************" >>$tmpfile</code>
</p></blockquote>
<p>And continue through the checks, writing the results to the temporary file.  Add or delete items from here where applicable to your situation:</p>
<blockquote><p><code>    # Get more variables from system:<br />
    httpdProcesses=`ps -def &#124; grep httpd &#124; grep -v grep &#124; wc -l`</p>
<p>    # Show current load level:<br />
    echo "Load Level Is: $loadLevel" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile</p>
<p>    # Show number of httpd processes now running (not including children):<br />
    echo "Number of httpd processes now: $httpdProcesses" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show process list:<br />
    echo "Processes now running:" >>$tmpfile<br />
    ps f -ef >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current MySQL info:<br />
    echo "Results from mytop:" >>$tmpfile<br />
    /usr/bin/mytop -u $dbusr -p $dbpw -b -d $db >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>Notice with the top command, we are writing to two temp files.  One is for the much smaller message to cell phone.  If you don&#8217;t want the urgency of cell phone alerts at three in the morning, you can take this out (and take out the second mailing routine later in the script).</p>
<blockquote><p><code><br />
    # Show current top:<br />
    echo "top now shows:" >>$tmpfile<br />
    echo "top now shows:" >>$topfile<br />
    /usr/bin/top -b -n1 >>$tmpfile<br />
    /usr/bin/top -b -n1 >>$topfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>More checks:</p>
<blockquote><p><code><br />
    # Show current connections:<br />
    echo "netstat now shows:" >>$tmpfile<br />
    /bin/netstat -p >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Check disk space<br />
    echo "disk space:" >>$tmpfile<br />
    /bin/df -k >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>Then write the temporary file contents to a more permanent log file and email the results to the appropriate parties.  The second mailing is the pared down results consisting simply of the standard out of `top`:</p>
<blockquote><p><code>    # Send results to log file:<br />
    /bin/cat $tmpfile >>$logfile</p>
<p>    # And email results to sysadmin:<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" -a $mysqlLog -a $msgLog $mailstop <$tmpfile<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" $mailstop1 <$topfile</p>
<p>    echo "**************************************" >>$logfile<br />
</code></p></blockquote>
<p>And then some housekeeping and exit:</p>
<blockquote><p><code>    # And then remove the temp file:<br />
    rm $tmpfile<br />
    rm $topfile<br />
fi</p>
<p>#<br />
exit 0 </code></p></blockquote>
<p>Hopefully this helps someone out there.  Fully assembled script is:</p>
<blockquote><p><code>#!/bin/bash<br />
#<br />
# Script to check system load average levels to try to determine what processes are<br />
# taking it overly high...<br />
#<br />
# set environment<br />
dt=`date +%d%b%Y-%X`<br />
# Obviously, change the following directories to where your log files actually are kept<br />
tmpfile="/tmp/checkSystemLoad.tmp"<br />
logfile="/tmp/checkSystemLoad.log"<br />
msgLog="/var/log/messages"<br />
mysqlLog="/var/log/mysqld.log"<br />
# the first mailstop is standard email for reports.  Second one is for cell phone (with a pared down report)<br />
mailstop="sysadmin@mydomain.com"<br />
mailstop1="15555555555@mycellphone.com"<br />
machine=`hostname`<br />
# The following three are for mytop use - use a db user that has decent rights<br />
dbusr="username"<br />
dbpw="password"<br />
db="yourdatabasename"<br />
# The following is the load level to check on - 10 is really high, so you might want to lower it.<br />
levelToCheck=10<br />
# Set variables from system:<br />
loadLevel=`cat /proc/loadavg &#124; awk '{print $1}'`<br />
loadLevel=$( printf "%0.f" $loadLevel )</p>
<p># if the load level is greater than you want, start the script process. Otherwise, exit 0</p>
<p>if [ $loadLevel -gt $levelToCheck ]; then<br />
    echo "" > $tmpfile<br />
    echo "**************************************" >>$tmpfile<br />
    echo "Date: $dt                             " >>$tmpfile<br />
    echo "Check System Load &#038; Processes         " >>$tmpfile<br />
    echo "**************************************" >>$tmpfile</p>
<p>    # Get more variables from system:<br />
    httpdProcesses=`ps -def &#124; grep httpd &#124; grep -v grep &#124; wc -l`</p>
<p>    # Show current load level:<br />
    echo "Load Level Is: $loadLevel" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile</p>
<p>    # Show number of httpd processes now running (not including children):<br />
    echo "Number of httpd processes now: $httpdProcesses" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show process list:<br />
    echo "Processes now running:" >>$tmpfile<br />
    ps f -ef >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current MySQL info:<br />
    echo "Results from mytop:" >>$tmpfile<br />
    /usr/bin/mytop -u $dbusr -p $dbpw -b -d $db >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current top:<br />
    echo "top now shows:" >>$tmpfile<br />
    echo "top now shows:" >>$topfile<br />
    /usr/bin/top -b -n1 >>$tmpfile<br />
    /usr/bin/top -b -n1 >>$topfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current connections:<br />
    echo "netstat now shows:" >>$tmpfile<br />
    /bin/netstat -p >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Check disk space<br />
    echo "disk space:" >>$tmpfile<br />
    /bin/df -k >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Send results to log file:<br />
    /bin/cat $tmpfile >>$logfile</p>
<p>    # And email results to sysadmin:<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" -a $mysqlLog -a $msgLog $mailstop <$tmpfile<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" $mailstop1 <$topfile</p>
<p>    echo "**************************************" >>$logfile</p>
<p>    # And then remove the temp file:<br />
    rm $tmpfile<br />
    rm $topfile<br />
fi</p>
<p>#<br />
exit 0 </code></p></blockquote>
<p><br/><a href="http://sysadmingeek.com/articles/diagnose-linux-server-load-problems-with-a-simple-script/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>If you have been an admin for any length of time, you have certainly discovered situations where a server spikes in CPU use or memory utilization and/or load levels.  Running `top` won&#8217;t always give you the answer, either.  So how do you find those sneaky processes that are chewing up your system resources to be able to kill &#8216;em?</p>
<p>The following script might be able to help.  It was written for a web server, so has some parts of it that are specifically looking for httpd processes and some parts that deal with MySQL.  Depending on your server deployment, simply comment/delete those sections and add others.  It should be used for a starting point.  </p>
<p>Prerequisites for this version of the script is some freeware released under the GNU General Public License called mytop (available at <a href="http://jeremy.zawodny.com/mysql/mytop/">http://jeremy.zawodny.com/mysql/mytop/</a>) which is a fantastic tool for checking how MySQL is performing.  It is getting old, but still works great for our purposes here.<br />
Additionally, I use mutt as the mailer &#8211; you may want to change the script to simply use the linux built in `mail` utility.  I run it via cron every hour; adjust as you see fit.  Oh &#8211; and this script needs to run as root since it does read from some protected areas of the server.</p>
<p>So let&#8217;s get started, shall we?</p>
<p>First, set your script variables:</p>
<blockquote><p><code>#!/bin/bash<br />
#<br />
# Script to check system load average levels to try to determine<br />
# what processes are taking it overly high...<br />
#<br />
# 07Jul2010  tjones<br />
#<br />
# set environment<br />
dt=`date +%d%b%Y-%X`<br />
# Obviously, change the following directories to where your log files actually are kept<br />
tmpfile="/tmp/checkSystemLoad.tmp"<br />
logfile="/tmp/checkSystemLoad.log"<br />
msgLog="/var/log/messages"<br />
mysqlLog="/var/log/mysqld.log"<br />
# the first mailstop is standard email for reports.  Second one is for cell phone (with a pared down report)<br />
mailstop="sysadmin@mydomain.com"<br />
mailstop1="15555555555@mycellphone.com"<br />
machine=`hostname`<br />
# The following three are for mytop use - use a db user that has decent rights<br />
dbusr="username"<br />
dbpw="password"<br />
db="yourdatabasename"<br />
# The following is the load level to check on - 10 is really high, so you might want to lower it.<br />
levelToCheck=10</code>
</p></blockquote>
<p>Next, check your load level to see if the script should continue:</p>
<blockquote><p><code># Set variables from system:<br />
loadLevel=`cat /proc/loadavg | awk '{print $1}'`<br />
loadLevel=$( printf "%0.f" $loadLevel )</p>
<p># if the load level is greater than you want, start the script process. Otherwise, exit 0</p>
<p>if [ $loadLevel -gt $levelToCheck ]; then<br />
    echo "" > $tmpfile<br />
    echo "**************************************" >>$tmpfile<br />
    echo "Date: $dt                             " >>$tmpfile<br />
    echo "Check System Load &#038; Processes         " >>$tmpfile<br />
    echo "**************************************" >>$tmpfile</code>
</p></blockquote>
<p>And continue through the checks, writing the results to the temporary file.  Add or delete items from here where applicable to your situation:</p>
<blockquote><p><code>    # Get more variables from system:<br />
    httpdProcesses=`ps -def | grep httpd | grep -v grep | wc -l`</p>
<p>    # Show current load level:<br />
    echo "Load Level Is: $loadLevel" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile</p>
<p>    # Show number of httpd processes now running (not including children):<br />
    echo "Number of httpd processes now: $httpdProcesses" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show process list:<br />
    echo "Processes now running:" >>$tmpfile<br />
    ps f -ef >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current MySQL info:<br />
    echo "Results from mytop:" >>$tmpfile<br />
    /usr/bin/mytop -u $dbusr -p $dbpw -b -d $db >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>Notice with the top command, we are writing to two temp files.  One is for the much smaller message to cell phone.  If you don&#8217;t want the urgency of cell phone alerts at three in the morning, you can take this out (and take out the second mailing routine later in the script).</p>
<blockquote><p><code><br />
    # Show current top:<br />
    echo "top now shows:" >>$tmpfile<br />
    echo "top now shows:" >>$topfile<br />
    /usr/bin/top -b -n1 >>$tmpfile<br />
    /usr/bin/top -b -n1 >>$topfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>More checks:</p>
<blockquote><p><code><br />
    # Show current connections:<br />
    echo "netstat now shows:" >>$tmpfile<br />
    /bin/netstat -p >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Check disk space<br />
    echo "disk space:" >>$tmpfile<br />
    /bin/df -k >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</code>
</p></blockquote>
<p>Then write the temporary file contents to a more permanent log file and email the results to the appropriate parties.  The second mailing is the pared down results consisting simply of the standard out of `top`:</p>
<blockquote><p><code>    # Send results to log file:<br />
    /bin/cat $tmpfile >>$logfile</p>
<p>    # And email results to sysadmin:<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" -a $mysqlLog -a $msgLog $mailstop <$tmpfile<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" $mailstop1 <$topfile</p>
<p>    echo "**************************************" >>$logfile<br />
</code></p></blockquote>
<p>And then some housekeeping and exit:</p>
<blockquote><p><code>    # And then remove the temp file:<br />
    rm $tmpfile<br />
    rm $topfile<br />
fi</p>
<p>#<br />
exit 0 </code></p></blockquote>
<p>Hopefully this helps someone out there.  Fully assembled script is:</p>
<blockquote><p><code>#!/bin/bash<br />
#<br />
# Script to check system load average levels to try to determine what processes are<br />
# taking it overly high...<br />
#<br />
# set environment<br />
dt=`date +%d%b%Y-%X`<br />
# Obviously, change the following directories to where your log files actually are kept<br />
tmpfile="/tmp/checkSystemLoad.tmp"<br />
logfile="/tmp/checkSystemLoad.log"<br />
msgLog="/var/log/messages"<br />
mysqlLog="/var/log/mysqld.log"<br />
# the first mailstop is standard email for reports.  Second one is for cell phone (with a pared down report)<br />
mailstop="sysadmin@mydomain.com"<br />
mailstop1="15555555555@mycellphone.com"<br />
machine=`hostname`<br />
# The following three are for mytop use - use a db user that has decent rights<br />
dbusr="username"<br />
dbpw="password"<br />
db="yourdatabasename"<br />
# The following is the load level to check on - 10 is really high, so you might want to lower it.<br />
levelToCheck=10<br />
# Set variables from system:<br />
loadLevel=`cat /proc/loadavg | awk '{print $1}'`<br />
loadLevel=$( printf "%0.f" $loadLevel )</p>
<p># if the load level is greater than you want, start the script process. Otherwise, exit 0</p>
<p>if [ $loadLevel -gt $levelToCheck ]; then<br />
    echo "" > $tmpfile<br />
    echo "**************************************" >>$tmpfile<br />
    echo "Date: $dt                             " >>$tmpfile<br />
    echo "Check System Load &#038; Processes         " >>$tmpfile<br />
    echo "**************************************" >>$tmpfile</p>
<p>    # Get more variables from system:<br />
    httpdProcesses=`ps -def | grep httpd | grep -v grep | wc -l`</p>
<p>    # Show current load level:<br />
    echo "Load Level Is: $loadLevel" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile</p>
<p>    # Show number of httpd processes now running (not including children):<br />
    echo "Number of httpd processes now: $httpdProcesses" >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show process list:<br />
    echo "Processes now running:" >>$tmpfile<br />
    ps f -ef >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current MySQL info:<br />
    echo "Results from mytop:" >>$tmpfile<br />
    /usr/bin/mytop -u $dbusr -p $dbpw -b -d $db >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current top:<br />
    echo "top now shows:" >>$tmpfile<br />
    echo "top now shows:" >>$topfile<br />
    /usr/bin/top -b -n1 >>$tmpfile<br />
    /usr/bin/top -b -n1 >>$topfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Show current connections:<br />
    echo "netstat now shows:" >>$tmpfile<br />
    /bin/netstat -p >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Check disk space<br />
    echo "disk space:" >>$tmpfile<br />
    /bin/df -k >>$tmpfile<br />
    echo "*************************************************" >>$tmpfile<br />
    echo "" >>$tmpfile</p>
<p>    # Send results to log file:<br />
    /bin/cat $tmpfile >>$logfile</p>
<p>    # And email results to sysadmin:<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" -a $mysqlLog -a $msgLog $mailstop <$tmpfile<br />
    /usr/bin/mutt -s "$machine has a high load level! - $dt" $mailstop1 <$topfile</p>
<p>    echo "**************************************" >>$logfile</p>
<p>    # And then remove the temp file:<br />
    rm $tmpfile<br />
    rm $topfile<br />
fi</p>
<p>#<br />
exit 0 </code></p></blockquote>
<p><br/><a href="http://sysadmingeek.com/articles/diagnose-linux-server-load-problems-with-a-simple-script/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/diagnose-linux-server-load-problems-with-a-simple-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Replace Text in Plain Text Files from the Command Line</title>
		<link>http://sysadmingeek.com/articles/replace-text-in-plain-text-files-from-the-command-line/</link>
		<comments>http://sysadmingeek.com/articles/replace-text-in-plain-text-files-from-the-command-line/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 10:00:50 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[Windows Server]]></category>
		<category><![CDATA[batch scripts]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[windows server 2003]]></category>
		<category><![CDATA[windows server 2008]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=1194</guid>
		<description><![CDATA[<p>A very useful function which is missing from the Windows library of command line tools is the ability to replace text in plain text files. A function like this can be used for a variety of practical tasks which many system admin’s perform, such as:</p>
<ul>
<li>Update configuration/INI files to replace UNC paths.
<li>Mass update user information stored in INI files on a Terminal/Citrix server.
<li>Use in conjunction with scripts to deploy ‘templated’ data and then apply values to the copied files.</li>
</ul>
<p>Our solution is a VBScript which interfaces with the Visual Basic Replace function. By placing this script into a location in your Windows PATH variable, you now have this functionality available at your disposal.</p>
<h3>Uses</h3>
<p>Once on your system, you can call the script by simply using the ReplaceText command. A few examples will illustrate ways you can use this:</p>
<p>Replace the word “null” with “n/a” in the C:\Data\Values.csv file:</p>
<blockquote><p>ReplaceText &#8220;C:\Data\Values.csv&#8221; null n/a</p>
</blockquote>
<p>Scan all INI files in the C:\Users (+ sub directories) folder replacing all occurrences of “Server=Old” with “Server=New” using a case insensitive search:</p>
<blockquote><p>FORFILES /P &#8220;C:\Users&#8221; /M *.ini /S /C &#8220;Cmd /C ReplaceText @path Server=Old Server=New /I&#8221;</p>
</blockquote>
<p>Scan all CFG files in the current user’s profile replacing “p@ssw0rd” with “PA$$woRd” using a case sensitive search:</p>
<blockquote><p>FORFILES /P &#8220;%UserProfile%&#8221; /M *.cfg /S /C &#8220;Cmd /C ReplaceText @path p@ssw0rd PA$$woRd&#8221;</p>
</blockquote>
<p>As you can see below, the script is very simple and can easily be modified to accommodate any special situations you may have. Alternately, you may want to create copies of the script which hardcode particular values so you can execute the command with a double-click and/or allow you to easily distribute it to others.</p>
<h3>The Script</h3>
<p><code>
<p>'Replace Text<br />'Written by: Jason Faulkner<br />'SysadminGeek.com
<p>'This script should be placed in a folder specified in your system's PATH variable.
<p>'Usage (WScript):<br />'ReplaceText FileName OldText NewText [/I]
<p>' /I (optional) - Text matching is not case sensitive
<p>Set oArgs = WScript.Arguments
<p>intCaseSensitive = 0<br />For i = 3 to oArgs.Count-1<br />&#160;&#160;&#160; If UCase(oArgs(i)) = "/I" Then intCaseSensitive = 1<br />Next
<p>Set oFSO = CreateObject("Scripting.FileSystemObject")
<p>If Not oFSO.FileExists(oArgs(0)) Then<br />&#160;&#160;&#160; WScript.Echo "Specified file does not exist."<br />Else<br />&#160;&#160;&#160; Set oFile = oFSO.OpenTextFile(oArgs(0), 1)<br />&#160;&#160;&#160; strText = oFile.ReadAll<br />&#160;&#160;&#160; oFile.Close
<p>&#160;&#160;&#160; strText = Replace(strText, oArgs(1), oArgs(2), 1, -1, intCaseSensitive)
<p>&#160;&#160;&#160; Set oFile = oFSO.OpenTextFile(oArgs(0), 2)<br />&#160;&#160;&#160; oFile.WriteLine strText<br />&#160;&#160;&#160; oFile.Close<br />End If</p>
<p></code><br />
<h3>Additional Notes</h3>
<p>By default, Windows uses WScript to execute VBScript (VBS) files. The only problem this can cause is any errors and/or messages from the script will appear as popup boxes. For a command line tool, it is best these messages be displayed in the console. There are a couple of ways you can accomplish this.</p>
<p>Change the default handler of VBScript files to CScript by running this command from command prompt (with Administrator rights):</p>
<blockquote><p>CScript //H:CScript</p>
</blockquote>
<p>Run the ReplaceText script explicitly using the CScript command:</p>
<blockquote><p>CScript &#8220;C:\Path\To\ReplaceText.vbs&#8221; //B FileName OldText NewText [/I]</p>
</blockquote>
<p>As a special case, executing ReplaceText from a batch script typically implies CScript as the engine used regardless of the default handler. You will definitely want to test this though prior to relying on this functionality.</p>
<p>&#160;</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/Script-ReplaceText.zip">Download ReplaceText Script from SysadminGeek.com</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/replace-text-in-plain-text-files-from-the-command-line/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>A very useful function which is missing from the Windows library of command line tools is the ability to replace text in plain text files. A function like this can be used for a variety of practical tasks which many system admin’s perform, such as:</p>
<ul>
<li>Update configuration/INI files to replace UNC paths.
<li>Mass update user information stored in INI files on a Terminal/Citrix server.
<li>Use in conjunction with scripts to deploy ‘templated’ data and then apply values to the copied files.</li>
</ul>
<p>Our solution is a VBScript which interfaces with the Visual Basic Replace function. By placing this script into a location in your Windows PATH variable, you now have this functionality available at your disposal.</p>
<h3>Uses</h3>
<p>Once on your system, you can call the script by simply using the ReplaceText command. A few examples will illustrate ways you can use this:</p>
<p>Replace the word “null” with “n/a” in the C:\Data\Values.csv file:</p>
<blockquote><p>ReplaceText &#8220;C:\Data\Values.csv&#8221; null n/a</p>
</blockquote>
<p>Scan all INI files in the C:\Users (+ sub directories) folder replacing all occurrences of “Server=Old” with “Server=New” using a case insensitive search:</p>
<blockquote><p>FORFILES /P &#8220;C:\Users&#8221; /M *.ini /S /C &#8220;Cmd /C ReplaceText @path Server=Old Server=New /I&#8221;</p>
</blockquote>
<p>Scan all CFG files in the current user’s profile replacing “p@ssw0rd” with “PA$$woRd” using a case sensitive search:</p>
<blockquote><p>FORFILES /P &#8220;%UserProfile%&#8221; /M *.cfg /S /C &#8220;Cmd /C ReplaceText @path p@ssw0rd PA$$woRd&#8221;</p>
</blockquote>
<p>As you can see below, the script is very simple and can easily be modified to accommodate any special situations you may have. Alternately, you may want to create copies of the script which hardcode particular values so you can execute the command with a double-click and/or allow you to easily distribute it to others.</p>
<h3>The Script</h3>
<p><code>
<p>'Replace Text<br />'Written by: Jason Faulkner<br />'SysadminGeek.com
<p>'This script should be placed in a folder specified in your system's PATH variable.
<p>'Usage (WScript):<br />'ReplaceText FileName OldText NewText [/I]
<p>' /I (optional) - Text matching is not case sensitive
<p>Set oArgs = WScript.Arguments
<p>intCaseSensitive = 0<br />For i = 3 to oArgs.Count-1<br />&nbsp;&nbsp;&nbsp; If UCase(oArgs(i)) = "/I" Then intCaseSensitive = 1<br />Next
<p>Set oFSO = CreateObject("Scripting.FileSystemObject")
<p>If Not oFSO.FileExists(oArgs(0)) Then<br />&nbsp;&nbsp;&nbsp; WScript.Echo "Specified file does not exist."<br />Else<br />&nbsp;&nbsp;&nbsp; Set oFile = oFSO.OpenTextFile(oArgs(0), 1)<br />&nbsp;&nbsp;&nbsp; strText = oFile.ReadAll<br />&nbsp;&nbsp;&nbsp; oFile.Close
<p>&nbsp;&nbsp;&nbsp; strText = Replace(strText, oArgs(1), oArgs(2), 1, -1, intCaseSensitive)
<p>&nbsp;&nbsp;&nbsp; Set oFile = oFSO.OpenTextFile(oArgs(0), 2)<br />&nbsp;&nbsp;&nbsp; oFile.WriteLine strText<br />&nbsp;&nbsp;&nbsp; oFile.Close<br />End If</p>
<p></code><br />
<h3>Additional Notes</h3>
<p>By default, Windows uses WScript to execute VBScript (VBS) files. The only problem this can cause is any errors and/or messages from the script will appear as popup boxes. For a command line tool, it is best these messages be displayed in the console. There are a couple of ways you can accomplish this.</p>
<p>Change the default handler of VBScript files to CScript by running this command from command prompt (with Administrator rights):</p>
<blockquote><p>CScript //H:CScript</p>
</blockquote>
<p>Run the ReplaceText script explicitly using the CScript command:</p>
<blockquote><p>CScript &#8220;C:\Path\To\ReplaceText.vbs&#8221; //B FileName OldText NewText [/I]</p>
</blockquote>
<p>As a special case, executing ReplaceText from a batch script typically implies CScript as the engine used regardless of the default handler. You will definitely want to test this though prior to relying on this functionality.</p>
<p>&nbsp;</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/Script-ReplaceText.zip">Download ReplaceText Script from SysadminGeek.com</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/replace-text-in-plain-text-files-from-the-command-line/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/replace-text-in-plain-text-files-from-the-command-line/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Batch Script to Conditionally Restart an Application</title>
		<link>http://sysadmingeek.com/articles/batch-script-to-conditionally-restart-an-application/</link>
		<comments>http://sysadmingeek.com/articles/batch-script-to-conditionally-restart-an-application/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 10:00:35 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[Windows Server]]></category>
		<category><![CDATA[batch scripts]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[windows server 2003]]></category>
		<category><![CDATA[windows server 2008]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=630</guid>
		<description><![CDATA[<p>Common system and/or environmental events such as resuming from standby or losing network connection can cause problems for certain applications which expect to be always on and connected. So if you have a certain application which crashes or goes into “not responding” mode somewhat frequently and a restart is the only fix for it, we have a simple fix for you in the form of a customizable batch script to simply kill the application and restart it.</p>
<p>In addition to the obvious situation above, this script can be used for a variety of useful tasks, such as:</p>
<ul>
<li>Easily restart an application by double-clicking or using a hot key.</li>
<li>Restart a program only when it is hung or not responding.</li>
<li>Run as a scheduled task to make sure an application is always running.</li>
<li>Anywhere else you want to automate conditional restarting of an application.</li>
</ul>
<p>Customizing the script should be pretty self explanatory by the comments, so just configure the script appropriately and you are all set.</p>
<h2>The Script</h2>
<pre>@ECHO OFF
ECHO Restart Application
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

SETLOCAL EnableExtensions

REM Enter the application information.
SET AppName=Application Name
SET ExeFile=FileToLaunch.exe
SET ExePath=C:\Path\To\Application

REM Select the conditions to kill the application.
REM A value of 1 = Yes, 0 = No
SET KillIfRunning=1
SET KillIfNotResponding=1
SET KillIfUnknownStatus=1

REM Specify when to start the application:
REM 1 = Start only if the process was previous killed.
REM 0 = Start the application regardless.
SET StartOnlyIfKilled=1

SET KillStatus="%TEMP%\KillStatus.tmp.txt"
SET Success=0

ECHO Killing existing %AppName% instance...
IF {%KillIfRunning%}=={1} CALL :CheckKillStatus "%ExeFile%" "RUNNING"
IF {%KillIfNotResponding%}=={1} CALL :CheckKillStatus "%ExeFile%" "NOT RESPONDING"
IF {%KillIfUnknownStatus%}=={1} CALL :CheckKillStatus "%ExeFile%" "UNKNOWN"
ECHO.

IF {%StartOnlyIfKilled%}=={1} (
	IF {%Success%}=={0} GOTO End
)
ECHO Restarting %AppName%...
START "%ExeFile%" "%ExePath%\%ExeFile%"
ECHO.

IF EXIST %KillStatus% DEL /F /Q %KillStatus%

ENDLOCAL

:CheckKillStatus
ECHO Killing with status: %~2
TASKKILL /FI "STATUS eq %~2" /IM "%~1" /F &#62; %KillStatus%
SET /P KillResult= &#60; %KillStatus%
FOR /F "tokens=1,* delims=:" %%A IN ("%KillResult%") DO (
	ECHO %%A:%%B
	IF /I {%%A}=={SUCCESS} SET /A Success=%Success%+1
)

:End
</pre>
<h2>Conclusion</h2>
<p>While you can find applications out there which perform basically the same function, using a simple script such as this avoids having “yet another program” running in the background.</p>
<p><br/><a href="http://sysadmingeek.com/articles/batch-script-to-conditionally-restart-an-application/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>Common system and/or environmental events such as resuming from standby or losing network connection can cause problems for certain applications which expect to be always on and connected. So if you have a certain application which crashes or goes into “not responding” mode somewhat frequently and a restart is the only fix for it, we have a simple fix for you in the form of a customizable batch script to simply kill the application and restart it.</p>
<p>In addition to the obvious situation above, this script can be used for a variety of useful tasks, such as:</p>
<ul>
<li>Easily restart an application by double-clicking or using a hot key.</li>
<li>Restart a program only when it is hung or not responding.</li>
<li>Run as a scheduled task to make sure an application is always running.</li>
<li>Anywhere else you want to automate conditional restarting of an application.</li>
</ul>
<p>Customizing the script should be pretty self explanatory by the comments, so just configure the script appropriately and you are all set.</p>
<h2>The Script</h2>
<pre>@ECHO OFF
ECHO Restart Application
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

SETLOCAL EnableExtensions

REM Enter the application information.
SET AppName=Application Name
SET ExeFile=FileToLaunch.exe
SET ExePath=C:\Path\To\Application

REM Select the conditions to kill the application.
REM A value of 1 = Yes, 0 = No
SET KillIfRunning=1
SET KillIfNotResponding=1
SET KillIfUnknownStatus=1

REM Specify when to start the application:
REM 1 = Start only if the process was previous killed.
REM 0 = Start the application regardless.
SET StartOnlyIfKilled=1

SET KillStatus="%TEMP%\KillStatus.tmp.txt"
SET Success=0

ECHO Killing existing %AppName% instance...
IF {%KillIfRunning%}=={1} CALL :CheckKillStatus "%ExeFile%" "RUNNING"
IF {%KillIfNotResponding%}=={1} CALL :CheckKillStatus "%ExeFile%" "NOT RESPONDING"
IF {%KillIfUnknownStatus%}=={1} CALL :CheckKillStatus "%ExeFile%" "UNKNOWN"
ECHO.

IF {%StartOnlyIfKilled%}=={1} (
	IF {%Success%}=={0} GOTO End
)
ECHO Restarting %AppName%...
START "%ExeFile%" "%ExePath%\%ExeFile%"
ECHO.

IF EXIST %KillStatus% DEL /F /Q %KillStatus%

ENDLOCAL

:CheckKillStatus
ECHO Killing with status: %~2
TASKKILL /FI "STATUS eq %~2" /IM "%~1" /F &gt; %KillStatus%
SET /P KillResult= &lt; %KillStatus%
FOR /F "tokens=1,* delims=:" %%A IN ("%KillResult%") DO (
	ECHO %%A:%%B
	IF /I {%%A}=={SUCCESS} SET /A Success=%Success%+1
)

:End
</pre>
<h2>Conclusion</h2>
<p>While you can find applications out there which perform basically the same function, using a simple script such as this avoids having “yet another program” running in the background.</p>
<p><br/><a href="http://sysadmingeek.com/articles/batch-script-to-conditionally-restart-an-application/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/batch-script-to-conditionally-restart-an-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Export Your Windows Server’s DNS Records to a Web Page</title>
		<link>http://sysadmingeek.com/articles/how-to-export-your-windows-server%e2%80%99s-dns-records-to-a-web-page/</link>
		<comments>http://sysadmingeek.com/articles/how-to-export-your-windows-server%e2%80%99s-dns-records-to-a-web-page/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 10:00:58 +0000</pubDate>
		<dc:creator>Jason Faulkner</dc:creator>
				<category><![CDATA[General Networking]]></category>
		<category><![CDATA[Windows Desktop]]></category>
		<category><![CDATA[Windows Server]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[web-servers]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[windows server 2003]]></category>
		<category><![CDATA[windows server 2008]]></category>

		<guid isPermaLink="false">http://sysadmingeek.com/?p=1189</guid>
		<description><![CDATA[<p>If you run a Windows Server which takes advantage of the built in DNS Server, you have a nice graphical interface for viewing and managing your DNS records. However, the vast majority of the time you probably just look at these records as opposed to updating them. This process is not difficult, but can be a hassle as you have to connect to the DNS Server machine through remote desktop, open DNS controls and locate the record. Wouldn’t it be easier if you could simply see this information over the web?</p>
<p>To make this functionality possible, we have a very simple script which exports your current DNS Server records to text files and makes them available via a simple indexed HTML file which can be accessed from any device with a web browser.</p>
<h3>Configuration</h3>
<p>Overall, the script’s configuration options are very straight forward. You simply need to configure the output location where you would like the destination files to end up. This folder will be populated with a ‘default.htm’ and ‘[domain].dns.zone.txt’ files. These names can be customized in the script as needed.</p>
<p>The script makes the assumption that you have named your DNS files using the default naming convention the Windows DNS Server uses ([domain].dns). <em><strong>If you are not using the default naming convention, the script will not work properly.</strong></em></p>
<p>As an additional function, the script can delete unused DNS record files which are no longer active in your DNS Server. If enabled (off by default), when the export procedure fails for a DNS record file, meaning the domain was not found in the DNS Server, it is deleted. These unlinked DNS record files do not do any harm or consume any resources, so it is safe to leave them alone.</p>
<p>If you update your DNS records often, you can configure the script to run regularly through a scheduled task so you know the information you are viewing is always current. The output of the script is read-only so any changes made to the resulting files will not be reflected in your DNS Server.</p>
<h2>How it Works</h2>
<p>The script simply reads your current DNS files from the default Windows location and then interfaces with the DNSCmd command line tool to produce the output files. The DNSCmd tool is included with Server 2008, but Server 2003 machines must install the Resource Kit Tools to put this utility on your system.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image13.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb12.png" width="496" height="209"></a> </p>
<p>The ‘[domain].dns.zone.txt’ are the output produced by the ZoneExport command.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image14.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb13.png" width="457" height="136"></a> </p>
<p>You can access the listing by viewing the output ‘default.htm’ file in a browser. If you have configured the script to export to a publically available location, you can view the output from anywhere.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image15.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb14.png" width="489" height="516"></a> </p>
<p>By clicking on a domain, you can see all the DNS information from your DNS Server for that domain.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image16.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb15.png" width="596" height="602"></a> </p>
<h3>The Script</h3>
<p><code>
<p>@ECHO OFF<br />TITLE DNS Dump to HTML<br />ECHO DNS Dump to HTML<br />ECHO Written by: Jason Faulkner<br />ECHO SysadminGeek.com<br />ECHO.<br />ECHO.
<p>SETLOCAL EnableDelayedExpansion
<p>REM Directory where the HTML pages should be generated.<br />SET OutPath=C:\inetpub\wwwroot\dns<br />SET HTMLPage=default.htm
<p>REM HTML page title/header.<br />SET Title=DNS Records
<p>REM Delete DNS record files which are not currently loaded in the DNS server (1=Yes, 0=No)<br />SET DeleteNotFound=0
<p>DEL /Q "%OutPath%\*"<br />SET OutFile="%OutPath%\%HTMLPage%"
<p>REM HTML header info. Customize as needed.<br />ECHO ^&#60;HTML^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;HEAD^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;TITLE^&#62;%Title%^&#60;/TITLE^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;/HEAD^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;BODY^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;H1^&#62;%Title%^&#60;H1^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;H3^&#62;Machine Name: %ComputerName%^&#60;/H3^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;H5^&#62;Generated on: %Date% %Time%^&#60;/H5^&#62; &#62;&#62; %OutFile%
<p>SET DNSDir=%WinDir%\system32\dns<br />FOR /F %%A IN ('DIR /A:-D /B /L %DNSDir%\*.dns') DO (<br />&#160;&#160;&#160; SET Zone=%%A<br />&#160;&#160;&#160; SET Zone=!Zone:.dns=!<br />&#160;&#160;&#160; SET ZoneFile=!Zone!.dns.zone.txt<br />&#160;&#160;&#160; ECHO Exporting: !Zone!<br />&#160;&#160;&#160; DNSCmd . /ZoneExport !Zone! !ZoneFile!<br />&#160;&#160;&#160; IF NOT EXIST %DNSDir%\!ZoneFile! (<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ECHO !Zone! is not currently loaded in DNS Server.<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; IF {%DeleteNotFound%}=={1} DEL /F /Q %DNSDir%\%%A<br />&#160;&#160;&#160; ) ELSE (<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ECHO ^&#60;A HREF="!ZoneFile!"^&#62;!Zone!^&#60;/A^&#62;^&#60;BR/^&#62; &#62;&#62; %OutFile%<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; REM Output is always to DNS directory, so move the file to the HTML dir.<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; MOVE /Y %DNSDir%\!ZoneFile! "%OutPath%\!ZoneFile!"<br />&#160;&#160;&#160; )<br />&#160;&#160;&#160; ECHO.<br />)
<p>ECHO ^&#60;BR/^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;/BODY^&#62; &#62;&#62; %OutFile%<br />ECHO ^&#60;/HTML^&#62; &#62;&#62; %OutFile%
<p>ENDLOCAL</p>
<p></code>
</p>
</p>
</p>
<p>&#160;</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/Script-DNSDump.zip">Download DNS Dump to HTML Script from SysadminGeek.com</a></p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9d467a69-57ff-4ae7-96ee-b18c4790cffd">Download Windows Server 2003 Resource Kit Tools from Microsoft</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-export-your-windows-server%e2%80%99s-dns-records-to-a-web-page/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></description>
			<content:encoded><![CDATA[<p>If you run a Windows Server which takes advantage of the built in DNS Server, you have a nice graphical interface for viewing and managing your DNS records. However, the vast majority of the time you probably just look at these records as opposed to updating them. This process is not difficult, but can be a hassle as you have to connect to the DNS Server machine through remote desktop, open DNS controls and locate the record. Wouldn’t it be easier if you could simply see this information over the web?</p>
<p>To make this functionality possible, we have a very simple script which exports your current DNS Server records to text files and makes them available via a simple indexed HTML file which can be accessed from any device with a web browser.</p>
<h3>Configuration</h3>
<p>Overall, the script’s configuration options are very straight forward. You simply need to configure the output location where you would like the destination files to end up. This folder will be populated with a ‘default.htm’ and ‘[domain].dns.zone.txt’ files. These names can be customized in the script as needed.</p>
<p>The script makes the assumption that you have named your DNS files using the default naming convention the Windows DNS Server uses ([domain].dns). <em><strong>If you are not using the default naming convention, the script will not work properly.</strong></em></p>
<p>As an additional function, the script can delete unused DNS record files which are no longer active in your DNS Server. If enabled (off by default), when the export procedure fails for a DNS record file, meaning the domain was not found in the DNS Server, it is deleted. These unlinked DNS record files do not do any harm or consume any resources, so it is safe to leave them alone.</p>
<p>If you update your DNS records often, you can configure the script to run regularly through a scheduled task so you know the information you are viewing is always current. The output of the script is read-only so any changes made to the resulting files will not be reflected in your DNS Server.</p>
<h2>How it Works</h2>
<p>The script simply reads your current DNS files from the default Windows location and then interfaces with the DNSCmd command line tool to produce the output files. The DNSCmd tool is included with Server 2008, but Server 2003 machines must install the Resource Kit Tools to put this utility on your system.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image13.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb12.png" width="496" height="209"></a> </p>
<p>The ‘[domain].dns.zone.txt’ are the output produced by the ZoneExport command.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image14.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb13.png" width="457" height="136"></a> </p>
<p>You can access the listing by viewing the output ‘default.htm’ file in a browser. If you have configured the script to export to a publically available location, you can view the output from anywhere.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image15.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb14.png" width="489" height="516"></a> </p>
<p>By clicking on a domain, you can see all the DNS information from your DNS Server for that domain.</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/image16.png"><img style="border-right-width: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px" border="0" alt="image" src="http://sysadmingeek.com/wp-content/uploads/2010/08/image_thumb15.png" width="596" height="602"></a> </p>
<h3>The Script</h3>
<p><code>
<p>@ECHO OFF<br />TITLE DNS Dump to HTML<br />ECHO DNS Dump to HTML<br />ECHO Written by: Jason Faulkner<br />ECHO SysadminGeek.com<br />ECHO.<br />ECHO.
<p>SETLOCAL EnableDelayedExpansion
<p>REM Directory where the HTML pages should be generated.<br />SET OutPath=C:\inetpub\wwwroot\dns<br />SET HTMLPage=default.htm
<p>REM HTML page title/header.<br />SET Title=DNS Records
<p>REM Delete DNS record files which are not currently loaded in the DNS server (1=Yes, 0=No)<br />SET DeleteNotFound=0
<p>DEL /Q "%OutPath%\*"<br />SET OutFile="%OutPath%\%HTMLPage%"
<p>REM HTML header info. Customize as needed.<br />ECHO ^&lt;HTML^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;HEAD^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;TITLE^&gt;%Title%^&lt;/TITLE^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;/HEAD^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;BODY^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;H1^&gt;%Title%^&lt;H1^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;H3^&gt;Machine Name: %ComputerName%^&lt;/H3^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;H5^&gt;Generated on: %Date% %Time%^&lt;/H5^&gt; &gt;&gt; %OutFile%
<p>SET DNSDir=%WinDir%\system32\dns<br />FOR /F %%A IN ('DIR /A:-D /B /L %DNSDir%\*.dns') DO (<br />&nbsp;&nbsp;&nbsp; SET Zone=%%A<br />&nbsp;&nbsp;&nbsp; SET Zone=!Zone:.dns=!<br />&nbsp;&nbsp;&nbsp; SET ZoneFile=!Zone!.dns.zone.txt<br />&nbsp;&nbsp;&nbsp; ECHO Exporting: !Zone!<br />&nbsp;&nbsp;&nbsp; DNSCmd . /ZoneExport !Zone! !ZoneFile!<br />&nbsp;&nbsp;&nbsp; IF NOT EXIST %DNSDir%\!ZoneFile! (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ECHO !Zone! is not currently loaded in DNS Server.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IF {%DeleteNotFound%}=={1} DEL /F /Q %DNSDir%\%%A<br />&nbsp;&nbsp;&nbsp; ) ELSE (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ECHO ^&lt;A HREF="!ZoneFile!"^&gt;!Zone!^&lt;/A^&gt;^&lt;BR/^&gt; &gt;&gt; %OutFile%<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; REM Output is always to DNS directory, so move the file to the HTML dir.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MOVE /Y %DNSDir%\!ZoneFile! "%OutPath%\!ZoneFile!"<br />&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp; ECHO.<br />)
<p>ECHO ^&lt;BR/^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;/BODY^&gt; &gt;&gt; %OutFile%<br />ECHO ^&lt;/HTML^&gt; &gt;&gt; %OutFile%
<p>ENDLOCAL</p>
<p></code>
</p>
</p>
</p>
<p>&nbsp;</p>
<p><a href="http://sysadmingeek.com/wp-content/uploads/2010/08/Script-DNSDump.zip">Download DNS Dump to HTML Script from SysadminGeek.com</a></p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9d467a69-57ff-4ae7-96ee-b18c4790cffd">Download Windows Server 2003 Resource Kit Tools from Microsoft</a></p>
<p><br/><a href="http://sysadmingeek.com/articles/how-to-export-your-windows-server%e2%80%99s-dns-records-to-a-web-page/" target='_blank'><img src="http://www.howtogeek.com/public/images/jointhediscussion.png" title="Got an opinion to share? Click here to join the discussion" alt="Got an opinion to share? Click here to join the discussion" border="0" /></a><br/></p>]]></content:encoded>
			<wfw:commentRss>http://sysadmingeek.com/articles/how-to-export-your-windows-server%e2%80%99s-dns-records-to-a-web-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 0.223 seconds. --><!-- Cached page generated by WP-Super-Cache on 2010-09-08 06:02:31 -->
