Some python ssh packages are available if you are wanting to execute
commands on a machine that has ssh.  ssh servers are available for
windows, but they aren't necessarily so well supported.

Here's a simple approach that works on ssh servers:

import commands
hostname = commands.getoutput('ssh [EMAIL PROTECTED]  hostname')
print hostname

Alternatively, you could run a Python-based web server from a simple
script like the one below, allowing you to execute a few commands
anonymously.  This is the sort of thing you might and to do on LANs for
a windows computer you don't want to run SSH on. 



"""
This is a small Web server that will allow remote clients to run
commands on this server and get the output.

Usage:  python <thisscript>

Client Usage:
lynx http://localhost:8000/hostname

On Windows this can be installed as a service with WinServ:  winserv
install py_http_serv C:\Python23\python.exe C:\_admin\httpd_monitor.py
 - make sure that this service is set to restart the process if it fails


Things I could improve:  I could have it download a new dict of commands
which would have to be GPG signed.
  - I could add a feature that would allow it to give me it's public gpg
key...and I could encrypt messages for it.

Perhaps I could even have it push out a shell of some sort.

"""

import BaseHTTPServer, shutil, os
from cStringIO import StringIO
import os

class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    # HTTP paths we serve, and what commandline-commands we serve them with

    # Note: I could run smtp commands...and pop commands to verify that
the mail server is still working

    import os
    if os.name == 'nt':
        cmds = {
            '/ping': 'ping www.google.com',
            '/netstat' : 'netstat -a',
            '/tracert' : 'tracert www.thinkware.se',
            '/srvstats' : 'net statistics server',
            '/wsstats' : 'net statistics workstation',
            '/route' : 'route print',
        '/unlock_sgeiger' : 'net user sgeiger /active:yes',  # maybe I
should make that more cryptic
        '/lssvc' : 'lssvc.exe',  # list processes
        '/sclist' : 'sclist',    # list processes (resource kit)
        '/exchange_status' : 'lssvc | grep MSExch',
        '/diruse' : 'diruse',
        '/now' : 'now',
        '/uptime' : 'uptime',
        }
    elif os.name == 'posix':         # includes Mac, Linux
        cmds = {
            '/hostname' : 'hostname',
            '/ping': 'ping -c 3 www.google.com',
            '/netstat' : 'netstat -rn',
            '/tracert' : 'traceroute www.google.com',
            #'/srvstats' : 'net statistics server',
            #'/wsstats' : 'net statistics workstation',
            '/route' : 'route -rn',   # this might be different on the
mac...
        }


    def do_GET(self):
        """ Serve a GET request. """
        f = self.send_head()
        if f:
            f = StringIO()
            machine = os.popen('hostname').readlines()[0]
            if self.path == '/':
                heading = "Select a command to run on %s" % (machine)
                body = (self.getMenu() +
                    "<p>The screen won't update until the select "
                        "command has finished.  Please be patient.")
            else:
                heading = "Execution of ''%s'' on %s" %
(self.cmds[self.path], machine)
                cmd = self.cmds[self.path]
                body = '<a href="/">Main Menu</a><pre>%s</pre>\n' %
os.popen(cmd).read()
                # Translation CP437 -> Latin 1 needed for Swedish Windows.
                #body = body.decode('cp437').encode('latin1')
            f.write("<html><head><title>%s</title></head>\n" % heading)
            f.write("<body><h1>%s</h1>\n" % (heading))
            f.write(body)
            f.write("</body></html>\n")
            f.seek(0)
            self.copyfile(f, self.wfile)
            f.close()
        return f

    def do_HEAD(self):
        """ Serve a HEAD request. """
        f = self.send_head()
        if f:
            f.close()

    def send_head(self):
        path = self.path
        if not path in ['/'] + self.cmds.keys():
            head = 'Command "%s" not found.  Try one of these:<ul>' %path
            msg = head + self.getMenu()
            self.send_error(404, msg)
            return None
        self.send_response(200)
        self.send_header("Content-type", 'text/html')
        self.end_headers()
        f = StringIO()
        f.write("A test %s\n" % self.path)
        f.seek(0)
        return f

    def getMenu(self):
        keys = self.cmds.keys()
        keys.sort()
        msg = []
        for k in keys:
            msg.append('<li><a href="%s">%s => %s</a></li>' %(k, k,
self.cmds[k]))
        msg.append('</ul>')
        return "\n".join(msg)

    def copyfile(self, source, outputfile):
        shutil.copyfileobj(source, outputfile)

def main(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    main()



vinoj davis wrote:
> hi all,
>           i am new to python, can anyone tell me how can i connect to
> a remote machine using python and execute commands.
>
> Thanking you..........
>
> Regards,
>    
>      ---ViNOJ DAViS---
>
>
> ------------------------------------------------------------------------
> Chat on a cool, new interface. No download required. Click here.
> <http://in.rd.yahoo.com/tagline_webmessenger_10/*http://in.messenger.yahoo.com/webmessengerpromo.php>



-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to