Console2 Alternative to CMD

Posted by Dan | Posted in AutoHotKey, Automation / Scripting, Systems, Windows | Posted on 02-13-2010

0

You know what, I tried PowerShell and I guess I never got used to it. I’ve been using DOS for the longest time that I prefer its simplicity when navigating through files. As far as scripting with it – forget it – it’s very cryptic and limiting, not to mention awkward. That’s why for scripting now I’m using Python. Nonetheless though, I sometimes need a playing field to run the scripts for, or running console utilities. That’s where Console2 comes in.

Console2 is a great tool that provides tabbing (you can tab through multiple consoles) and several ways to customize the UI. Here’s an example:



I prefer this configuration:


How I Have It Setup



Download Console2:

I have the Console2 open up when I hit CTR+\ via AutoHotkey. Here’s the snippet for this to happen in AutoHotkey. I have this run when Window starts (it must stay in memory).

^\::Run C:\dan-local\dos-win\Console.exe

Change the CMD prompt by creating a PROMPT system variable:




Download the Console2 Config File

Other Tips


Autocomplete
Good tip about command console = CTRL+I
can select files in the current directory, kinda like autofill-in
you can also put in parts of the file and it autoputs it for you

Rename tab
CTRL+R

New Tab with default transparency
CTRL+F1

New Tab with lighter transparency
CTRL+F2

Switch to NEXT adjacent tab
CTRL+TAB

Switch to Previous adjacent tab
CTRL+SHIFT+TAB

CTRL+[NUMBER]
Goes to the tab instance. To make it easier, it’s best if you rename your tabs,

[INSTANCE NAME].[NAME OF TAB]

So for example,

1.Batch File
2.wget list
3.ftp the files

Get Latest File

Posted by Dan | Posted in Automation / Scripting, Python | Posted on 02-04-2010

0

In my last post, I made a quick script that checks for the date. It was very limiting, since it used the dir command. This one uses several date/time Python modules and is more capable.

import os, os.path, stat, time
from datetime import date, timedelta, datetime
 
# Reference
# http://docs.python.org/library/datetime.html
# http://docs.python.org/library/time.html
 
def getFileDate( filenamePath ):    
 
  used = os.stat( filenamePath ).st_mtime      
  year, day, month, hour, minute, second = time.localtime(used)[:6]
  objDateTime = datetime(year, day, month, hour, minute, second)
 
  return objDateTime
 
  # Ways to reference this DateTime Object
  # objDateTime.strftime("%Y-%m-%d %I:%M %p")
  # objDateTime.year
  # objDateTime.month
 
 
def isDaysOldFromNow( filenamepath, days ):
 
  # Checks how old a file is. Is it older than "days" [variable] days?
  inTimeRange = False  
  timeDeltaDiff = ( datetime.now()-getFileDate( filenamepath ) ).days
 
  # Check if the file's date is days old or less:
  if ( timeDeltaDiff >= days ):
    inTimeRange = True  
 
  return inTimeRange
 
fname = "C:/temp/decision2.pdf"  
 
# Set this variable to check if the file is this days old
howOld = 3
 
 
if ( isDaysOldFromNow( fname, howOld ) ):
  print fname, "is more than", howOld, "days old"
else:
  print fname, "is NOT more than", howOld, "days old"

Output:

Compress and Move Log Files

Posted by Dan | Posted in Automation / Scripting, Python, Systems, Windows | Posted on 01-30-2010

0

Sometimes log files bog a system down. For one of our servers, I made this little Python script that compresses (via WinRAR) the log files in a directory, and then moves them to a backup location. The only little catch is that I wanted to leave the latest log files for in that directory. Log files are created daily, so the the latest log files have a datestamp of today. Here’s how I did it.

First Create the Python Script:

import os
import datetime
 
dateStamp  = datetime.datetime.now().strftime("%Y-%m-%d") 
imsLogPath = 'd:\\LogFiles\\'                     
# Don't use a mapped drive but use UNC for network drives. Task Schedule seems to choke when it calls Python.
newRARPath = '"\\\\192.168.1.2\\Root\\backups\\' + dateStamp + '.rar"'
rarPath    = '"C:\\Program Files\\WinRAR\\rar.exe" a -m5 ' + newRARPath 
 
# Get Latest Files
smtpLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "SMTP*.log").read().splitlines()[-1]
postLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "POST*.log").read().splitlines()[-1]
ischedLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "iSched*.log").read().splitlines()[-1]
relayLatest  = os.popen(r"dir /od /a-d /b " + imsLogPath + "Relay*.log").read().splitlines()[-1]
qengLatest   = os.popen(r"dir /od /a-d /b " + imsLogPath + "Qeng*.log").read().splitlines()[-1]
 
# Get List of All Files
allFiles     = os.popen(r"dir /od /a-d /b " + imsLogPath + "*.log").read().splitlines()
 
# Remove Latest Files from All Files List
allFiles.remove( smtpLatest )
allFiles.remove( postLatest )
allFiles.remove( ischedLatest )
allFiles.remove( relayLatest )
allFiles.remove( qengLatest )
 
# allFiles Array Has the list of files
 
# Flatten Array allFiles to be used as a parameter in system command
flatLogPathList = ""
for filenameWithPath in allFiles:
  flatLogPathList = flatLogPathList + imsLogPath + filenameWithPath + " "
 
 
# Execute WinRar
path = rarPath + " " + flatLogPathList.rstrip()
os.system( '"' + path + '"' )
 
# Delete all log files
os.system( '"del ' + flatLogPathList.rstrip() + '"' )

Then I set up the Scheduled Task:

With these Settings:

Convert Minutes to Hours

Posted by Dan | Posted in Automation / Scripting, Perl, iPhone | Posted on 01-28-2010

0

I often use both Winamp and my iPhone to listen to music. These two, unfortunately, show the time differently in the songs. Winamp displays the time in minutes (mm) while the iPhone does it hour/minutes (hh:mm). Here’s a quick little script I whipped together because I’m too lazy to do this in my head, especially for audio books where an audio book can be over 500 minutes, and I need to convert to iPhone time because I want to continue listening where I had just left off on Winamp.

use POSIX qw(ceil floor); # used for the floor function
 
sub GetToken {
  # @_ = flatten args list from an array
  # @_[0] = first argument
 
  $data      = @_[0];
  $delimiter = @_[1];
  $token     = @_[2] - 1;
 
  @tokens_array = split($delimiter, $data);   
 
  return @tokens_array[$token]; 
}
 
sub chr_conver_min {  
  if (length(@_[0]) == 1) {
    return "0".@_[0];
  }
  else {
    return @_[0];
  }   
}
 
 
sub iphone_time_convert {
 
  # converts winamp time to iphone - winamp stores time only in minutes.  
  # @_[0]   =  winamp_time, e.g. 124:34
  # $hour   = floor($winamp_time/60);
  # $minute = $winamp_time % 60;
 
  $winamp_hour_min = GetToken(@_[0], ":", 1);  
  $winamp_seconds  = GetToken(@_[0], ":", 2);  
 
  return floor($winamp_hour_min/60).":".chr_conver_min( ($winamp_hour_min % 60) ).":".$winamp_seconds;
 
}
 
 
sub winamp_time_convert {  
 
  # converts iphone time to winamp  
  # @_[0] = iphone_time, e.g. 3:43:34    
  $iphone_hour     = GetToken(@_[0], ":", 1);  
  $iphone_min      = GetToken(@_[0], ":", 2);    
  $iphone_seconds  = GetToken(@_[0], ":", 3);
 
  return (($iphone_hour * 60) + $iphone_min).":".$iphone_seconds;
 
}
 
sub show_help {
  print "\nDisplays the conversion of time between winamp and iPhone.\n\n";
  print "   winamptime [-w2i|-i2p] [mm:ss][hh:mm:ss]\n\n";
  print "Example to convert winamp time to iPhone: \n\n";
  print "   winamptime -w2i 212:41\n\n";
  print "Example to convert iPhone time to winamp, seconds being optional: \n\n";
  print "   winamptime -i2w 2:31:41\n";
  print "   winamptime -i2w 2:31\n\n";
}
 
 
# START
 
# Optimize this:
if( $ARGV[0] eq "-w2i" ) 
{
  # winamp to iphone time
  if ( length($ARGV[1]) > 0 ) {
    print "iPhone Time: ".iphone_time_convert( $ARGV[1] )."\n";
  }
}
elsif( $ARGV[0] eq "-i2w" ) 
{
  # iphone to winamp time
  if ( length($ARGV[1]) > 0 ) {
    print "Winamp Time: ".winamp_time_convert( $ARGV[1] )."\n";
  }
}
else 
{
  show_help();
}

Output:

Handling Images from the Command Line

Posted by Dan | Posted in Automation / Scripting, Web Design | Posted on 12-30-2009

0

Recently, I needed to do some work from the Windows Command Line, and I needed to deal with a few images. Along the way, I found some great tools. All these tools are free. Can come in useful when automating.

Manipulation

ImageMagick – This is a collection of command line tools. You can do image conversion, view properties, transform, transparency, join, overlay, add special special effects, and tons more. Also has APIs for C, C++, Java, .NET, Perl, PHP, Python, Ruby, and others. Highly recommend it.

Screen Capture


CmdCapture – Takes a screenshot of your desktop from the command line.

IECapt – Capture Internet Explorer’s rendering of a web page into a BMP, JPEG or PNG image file.

Cutycapt – Capture WebKit’s rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP.

wkhtmltopdf – Convert HTML to PDF using the Webkit rendering engine, and Qt.

Unlock Files Through the Command Console

Posted by Dan | Posted in Automation / Scripting, Windows | Posted on 12-18-2009

0

If you want to unlock files in Windows many of us know to use Unlocker. It’s a handy tool that I use often when a pesky process has a handle on a file. But what if you want to write a script that unlocks files from the command line. Welcome the tool “Handle” from Sysinternals by Mark Russinovich.

1

2

3

Then you could loop through the list of files by doing so.

Automate FTP Uploads

Posted by Dan | Posted in Automation / Scripting, Systems, Windows | Posted on 10-04-2009

0

I thought this might be useful for those who are constantly uploading the same files. Whether you need to deploy a project live or constantly upload the same group of files, you can do this by creating a batch file in Windows using ftp.exe.

First of all, if you’re not familiar with FTP.exe, it’s just a command console way to upload/download files from an FTP server. You can run this program and start typing away…. OR, you can load a text file filled with FTP commands in FTP.exe. For example, the following are commands in a file called upload.bs:

1
2
3
4
5
6
7
8
9
open western.dreamhost.com
username
password
binary
hash
send index.htm
send frame.htm
send car.jpg
bye

The above should be straightforward. The “open” command is used to connect to the FTP server. The “username” should be your usename and “password” should be your actual password. “binary” is how your data should be handled on transfer – if it’s not text, it’s binary data, and should be “binary.” “hash” makes the console display pound signs (#) to serve as a progress bar as it’s uploading to the server. The “send” commands are used to upload the files. “bye” is exits the FTP session.

That was just a FTP script session file. You now need to call that file from FTP.exe on WindowsXP. You do that as follows:

1
@%windir%\system32\ftp.exe -s:upload.bs

You can include that call in a file called “upload.bat” – To learn more about FTP scripting and how to merge the two files into just one batch file, you can check out this site. Also, there’s more information about this found here: tinyapps.org.

ANT Script to Deploy

Posted by Dan | Posted in Automation / Scripting, Development, Systems | Posted on 10-03-2009

0

A friend of mine asked to post a simple to show the power of ANT. Here’s an ANT script with comments that shows some of the things you can do with ANT. To read how to set up ANT and run scripts, please read my earlier post on doing so.

This script gets the latest from an SVN repo, deploys using FTP, then sends an email using a Gmail account. Here’s the ant script (deploy.ant), followed by a properties file (i.e. the config file, deploy.properties), which the ANT script pulls from:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?xml version="1.0"?>
<!-- ======================================================== -->
<!-- Sample build file used to retrieve svnant's sources -->
<!-- ======================================================== -->
 
<!-- TODO: Mail if the script failed --> 
 
<project name="STAGING-Deploy" basedir="." default="empty">
 
  <property file="STAGING-Deploy.properties" />            
  <!-- Import SVNAnt tasks from jar files.  -->
  <typedef resource="org/tigris/subversion/svnant/svnantlib.xml" />
 
  <target name="Deploy"> 
    <!-- Step 1: Export the latest files from the repo to local machine. -->
    <antcall target="export" />
 
    <!-- Step 2: FTP the files from the local machine to STAGING. -->
    <antcall target="ftp_files" />
 
    <!-- Step 3: Cleanup. -->
    <antcall target="cleanup" />  
  </target>  
 
 
  <!-- SVN Checkout (Latest) -->
  <target name="checkout_latest">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <checkout url="${svnant.projectrunk.url}" revision="${svnant.checkout.revision}" destPath="${svnant.checkout.destpath}" />
    </svn>    
  </target>   
 
  <!-- SVN Update -->
  <target name="update_latest">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <update dir="${svnant.update.directory}" recurse="${svnant.update.recurse}" revision="${svnant.update.revision}" />
    </svn>    
  </target>  
 
  <!-- SVN Export  -->
  <target name="export">
    <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
      <export srcUrl="${svnant.export.srcurl}" destPath="${svnant.export.destpath}" force="${svnant.export.force}" />
    </svn>    
  </target>
 
  <!-- FTP the export of the latest revision to STAGING. -->  
  <target name="ftp_files">    
    <!-- Import FTP tasks from jar files.  -->
    <taskdef classname="org.apache.tools.ant.taskdefs.optional.net.FTP" name="ftp" />
 
    <ftp server="${ftp.server}" port="${ftp.port}" remotedir="${ftp.destination}" userid="${ftp.userid}" password="${ftp.password}" 
         passive="${ftp.passive}" depends="${ftp.depends}" binary="${ftp.binary}" retriesAllowed="${ftp.retriesallowed}" verbose="${ftp.verbose}">
 
      <fileset dir="${svnant.export.destpath}" />
 
    </ftp>    
  </target>  
 
  <!-- Cleans Up: Remove temp info, etc. -->
  <target name="cleanup">  
    <delete includeEmptyDirs="true">
      <fileset dir="${svnant.export.destpath}"/>      
    </delete>
 
    <!-- Email Notification -->
    <mail mailhost="${mail.host}" mailport="${mail.port}" subject="${mail.subjectalert}" ssl="${mail.ssl}" user="${mail.username}" password="${mail.password}">
      <from address="${mail.from}"/>      
      <to address="${mail.to}"/>
      <message>The nightly build has completed.</message>
    </mail>
 
    <echo>Cleanup complete. </echo>
  </target>
 
  <target name="empty">    
    <echo>Pass in a default target to call </echo>    
  </target>
 
</project>

Now let’s check out the properties file (deploy.properties):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -----------------------------------------------------------------------------
# STAGING-DEPLOY
# Variables are initialized here.
# -----------------------------------------------------------------------------
#
# NOTE: Backslashes have to be escaped with another backslash (on Windows)
#
 
# === INIT =====================================================================
svnant.projectrunk.url=svn://192.168.3.142/TESTING/trunk
svnant.repository.user=YOURUSERNAME
svnant.repository.passwd=YOURPASSWORD
 
# === CHECKOUT (INITIAL) =======================================================
# Check out a working copy of the latest to a local directory.
svnant.checkout.destpath=C:\\testing123
svnant.checkout.revision=HEAD
 
# === UPDATE TO LATEST =========================================================
# Update the working copy of your local directory to latest revision
svnant.update.directory=C:\\Experiments\\Firehawk\\src_latest
svnant.update.revision=HEAD
svnant.update.recurse=true
 
 
# === EXPORT ===================================================================
# Copies From Source Repo:
svnant.export.srcurl=${svnant.projectrunk.url}
 
# Into a temporary directory in your ant home (that will be FTP'd):
svnant.export.destpath=${ant.home}\\export-temp
 
# Overwrite (needs to in case the file changed)? 
svnant.export.force=true
 
PBNStagingFTP
# == FTP INFO ==================================================================
# FTP what was exported (latest version) to this location on staging:
ftp.destination=/testing/
ftp.server=TESTING
ftp.port=21
ftp.userid=USERNAME
ftp.password=PASSWORD
ftp.passive=yes
ftp.depends=yes
ftp.binary=yes
ftp.retriesallowed=5
ftp.verbose=yes
 
# == MAIL INFO ==================================================================
# Currently using GMAIL for now.
mail.host=smtp.gmail.com
mail.port=465
mail.subjectalert=[STAGING ANT Build] Test build
mail.ssl=yes
mail.username=USERNAME
mail.password=PASSWORD
mail.from=someone@somewhere.com
mail.to=someone@somewhere.com

Executable Extension

Posted by Dan | Posted in Automation / Scripting, Systems, Windows | Posted on 10-02-2009

0

Want to run a script in the command console that is not of type EXE, COM, BAT by just typing in the name of the script? Have a script in Perl or Python that you have that you want to run without typing the name of the interpreter with switches? It's pretty easy to do in Windows.

  1. Open up System Properties and click on Environment Variables:



  2. Select the PATHEXT System variable and click on the Edit button.



  3. Add the extension you want. In this case, let's add the extension for .PL so we can run Perl scripts without typing in the name of the Perl interpreter:



  4. Hit OK on the Windows.

  5. In an Explorer Window, Go to Tools -> Folders



  6. In the Folder Options Window, click on the File Types tab, and then click New:



  7. Type .PL for the File Extension



  8. Click OK then Click on the Advanced button to open up the Edit File Type and click on New...



  9. Enter the name of the interpreter:



  10. Hit OK for all Windows.

  11. You're set and good to go.

Now let's test it. Make a .pl file under c:\ called "add.pl". Make add.pl be:

1
2
$sum = $ARGV[0] + $ARGV[1];
print "\nSum of the numbers is: $sum\n\n";

 

Now let’s call it via the console by typing:

1
add 5 5

9

JavaScript for the Windows Command Console

Posted by Dan | Posted in Automation / Scripting, Databases, JavaScript, Systems | Posted on 09-26-2009

0

JSDB is a great JavaScript interpreter based on Mozilla’s Spidermonkey JavaScript engine. If you like working off the command console, I suggest you give it a go. Of course, not everything is supported, as there is no HTML/DOM context in the console. To compensate for it, the author of this tool has added some great features, like being able to connect to databases, use includes ( easily via the load(“file.js”) function ), and other network facilities, like fetching HTML content from other websites.