mbudisic / cl-goodies

Command line goodies! Small shell scripts I've made to make my life easier.

Clone this repository (size: 39.4 KB): HTTPS / SSH
$ hg clone http://bitbucket.org/mbudisic/cl-goodies/
commit 27: 2cb4e220c5eb
parent 26: 97f3785ab921
branch: default
tags: tip
Backup
Marko Budisic / mbudisic
5 months ago
cl-goodies / remotespy
r27:2cb4e220c5eb 150 loc 4.1 KB embed / history / annotate / raw /
#!/usr/bin/env python

"""
    Remotespy -- command line script for remote monitoring of processes.
    Copyright (C) 2009 Marko Budisic

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    See 
    http://bitbucket.org/mbudisic/cl-goodies/wiki/Remotespy
    for documentation.

    In short, run 
    remotespy --help for list of options.
    
    The command script has lines of format:
    TITLE ## COMMAND ## COMMENT

"""


from optparse import OptionParser
from os.path import basename
from time import asctime
from sys import exit
import commands

#### ARGUMENT AND SCRIPT PARSING #############

# parse command line
parser = OptionParser(usage="%prog [options] CMDFILE HTMLFILE",
                      description="Run commands from FILE and add their outputs to a HTML file.")
    
defhelp = "; [%default]"

parser.add_option( "--license", action="store_true", default=False)
parser.add_option( "-t", "--title", type="string", default="Simulation monitor", help="Report title"+defhelp)
parser.add_option( "-r", "--refresh", type=int, default=20, help="Delay between automatic refresh of page in seconds"+defhelp)
parser.add_option( "--hidecmd", action="store_true", default=False, help="Command names are not printed to output file."+defhelp )
parser.add_option( "--scpdest", metavar="DEST", type="string", default="", help="If set, the output is uploaded to a server by 'scp HTMLFILE DEST'. ssh private-pub exchange has to be set if this command is used in batch mode")

(options, files) = parser.parse_args()

if options.license:
    print """
    remotespy  Copyright (C) 2009 Marko Budisic
    This program comes with ABSOLUTELY NO WARRANTY; for details type `--help'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; see GPL license http://www.gnu.org/licenses/.
"""
    exit(0)



# read commands from the command file
f = open(files[0],'r')

try:
    cmdqueue = []
    for line in f:
        if line=="":
            continue
        try:
            tokens = line.split("##")
            cmdqueue.append({'title':tokens[0].strip(), 'exec':tokens[1].strip()})
        except:
            continue
finally:
    f.close()

#### HTML TEMPLATES #########################

# main html code boilerplate
htmlwrapper = \
"""
<html>
<head>
<noscript>
<meta name="robots" content="noindex"></noscript>
<meta http-equiv="refresh" content="%(refresh)d">
<title>%(stitle)s - simulation monitor</title>
</head>
<body>
<h1>%(stitle)s</h1>
<h2>%(sdate)s</h2>
%(sbody)s
</body>
</html>
"""

# formatting of command output
instance = \
"""
<h3>%s</h3>
<p>
<b><code>%s</code></b><br>
<pre>
%s
</pre>
<hr>
</p>
"""

#### RUN COMMANDS AND GENERATE HTML CODE #############

# generate code for each command
sbody = ""
for cmd in cmdqueue:
    out = commands.getoutput(cmd['exec'])
    if options.hidecmd:
        cmdexec = "command hidden"
    else:
        cmdexec = cmd['exec']
    sbody += ( instance % (cmd['title'], cmdexec, out) )

# generate cumulative code
stitle = options.title
refresh = options.refresh

sdate = asctime()
htmltext = htmlwrapper % vars()

#### WRITE HTML FILE AND COPY IT REMOTELY ###########
if len(files)>1:

    # save 
    f = open(files[1],'w')
    f.write(htmltext)
    f.close()    

    # upload output to a remote destination
    if not options.scpdest == "" :
        scpcommand = "scp -o 'BatchMode yes' %s %s" % (files[1],options.scpdest)
        status, out = commands.getstatusoutput( scpcommand )
        if status > 0:
            print "scp reported: " + out

else:
    print htmltext