Ssh

From Enso Wiki

Jump to: navigation, search
  • NOTE: This command is written for Command Server not as a stand alone command

Contents

[edit] Information

Enables access to Putty sessions.

[edit] Usage

  • ssh {session}

or

  • putty {session}

[edit] Installation

  • Create file command_ssh.py or command_putty.py containing the code below. Put it into commands/ directory in Command Server directory.

[edit] Code

from base import BaseCommand
 
 
class Command(BaseCommand):
    def __init__(self, *args):
        BaseCommand.__init__(self, *args)
        self._puttyPath = None
        self._registerCommands(self._getSessions())
 
 
    def _registerCommands(self, sessions):
        try:
            self.removeCommand("ssh {session}")
            self.removeCommand("putty {session}")
        except:
            pass
        self.newBoundedCommand("ssh {session}",
                                self._ssh,
                                "Open SSH session.",
                                "<p>Enables access to the Putty SSH sessions.</p>",
                                sessions
        )
        self.newBoundedCommand("putty {session}",
                                self._ssh,
                                "Open SSH session.",
                                "<p>Enables access to the Putty SSH sessions.</p>",
                                sessions
        )
 
    
    def _ssh(self, session):
        # Refresh sessions from registry
        sessions = self._getSessions()
 
        # Re-register commands to see fresh sessions next time
        self._registerCommands(sessions)
 
        if len(session) == 0:
            return
        if len(sessions) == 0:
            self.displayMessage("No sessions available")
            return
 
        # Try to run putty with cached path
        if  self._puttyPath and self._runProgram(self._puttyPath, '-load "%s"' % session):
            return True
 
        # If there is no cached path, try several
        # Try just the executable, user might have put it to the PATH
        path = "putty.exe"
        if self._runProgram(path, '-load "%s"' % session):
            # success, cache this path
            self._puttyPath = path
            return True
        
        # Not worked, try to get the installation dir from uninstall info in registry
        path = self._getRegKeySZ(
                "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PuTTY_is1\\InstallLocation")
        if path:
            path = "%sputty.exe" % path
            if self._runProgram(path, '-load "%s"' % session):
                # success, cache this path
                self._puttyPath = path
                return True
 
        # Didn't worked, try to guess typical location
        path = "c:\\program files\\putty\\putty.exe"
        if self._runProgram(path, '-load "%s"' % session):
            # success, cache this path
            self._puttyPath = path
            return True
 
        # No luck, report error
        self.displayMessage("Error executing Putty")
        return False
 
 
    def _runProgram(self, cmd, parm):
        try:
            import win32api
            win32api.ShellExecute(0, 'open', cmd , parm, None, 1)
            return True
        except:
            return False
 
 
    def _getSessions(self):
        sessions = []
        try:
            reghandle = None
            import _winreg
            reghandle = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
            #print reghandle
            regkey = _winreg.OpenKey(reghandle, "Software\\SimonTatham\\PuTTY\\Sessions")
            print regkey
            index = 0
            try:
                while True:
                    sessions.append(_winreg.EnumKey(regkey, index).replace('%20',' ').lower())
                    index = index + 1
            except:
                pass
        except:
            print "Problem opening HKCU\\Software\\SimonTatham\\PuTTY\\Sessions regkey"
        finally:
            if reghandle:
                _winreg.CloseKey(reghandle)
        print sessions
        return sessions
 
 
    def _getRegKeySZ(self, key):
        try:
            reghandle = None
            import _winreg
            if key.startswith('HKEY_L'):
                mainKey = _winreg.HKEY_LOCAL_MACHINE
            else:
                mainKey = _winreg.HKEY_CURRENT_USER
            reghandle = _winreg.ConnectRegistry(None, mainKey)
            #print reghandle
            name = key[key.rfind('\\')+1:]
            key = key[key.find('\\')+1:key.rfind('\\')]
            #print "name: %s, key: %s" % (name, key)
            regkey = _winreg.OpenKey(reghandle, key)
            print regkey
            value = _winreg.QueryValueEx(regkey, name)
            if value:
                print value[0]
                return value[0]
            else:
                return None
        except:
            print "Problem opening %s regkey" % key
        finally:
            if reghandle:
                _winreg.CloseKey(reghandle)
 
# vim:set tabstop=4 shiftwidth=4 expandtab

[edit] Known issues

Command guesses the putty.exe file location when executing it. It probes following, in given order:

  1. Run putty.exe directly. This works in case you have Putty directory on your PATH.
  2. Get Putty directory from registry uninstall key. This works in case you have installed Putty with provided installer.
  3. Typical "c:\\program files\\putty\\putty.exe" as a last resort.

If you have putty.exe installed manually (there is no uninstall registry record), or you installed it into other than program files directory, you will have to add putty directory into the PATH system variable, or change the path in the script.

[edit] Contact

Contact me in case of any bugs, ideas or suggestions you may have --Blackdaemon 09:09, 14 February 2008 (PST)