Using python to update PuTTY sessions

Posted:

Putty has been the gold standard for free Windows SSH utilities for almost a decade now. As you might expect from a win32 application, it keeps its stored sessions (the connection meta-data used to connect to various hosts) in the Windows Registry:

HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions

You may find it desirable to create or update a stored session. While you can use many tools to do this, Python offers a convenient way to do this using the _winreg module. The following is an example of how to iterate through the list of existing Putty sessions.

import _winreg

subkey = 'Software\SimonTatham\PuTTY\Sessions'
H = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, subkey)
info = _winreg.QueryInfoKey(H);
if info[0] < 1 :
   print "No saved sessions\n";
   exit;

print "Found the following saved sessions:"
i=0;
trg = None;
while i < info[0] :
    s = _winreg.EnumKey(H, i)
    k2 = subkey + '\\' + s 
    H2 = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, k2, 0, _winreg.KEY_ALL_ACCESS)
    host = _winreg.QueryValueEx(H2, "HostName")
    print "\t%s - %s" % (s, host[0])
    _winreg.CloseKey(H2)
    i += 1;

The Windows Registry has five “databases” that you can connect to:

  • HKEY_CLASSES_ROOT
  • HKEY_CURRENT_USER
  • HKEY_LOCAL_MACHINE
  • HKEY_USERS
  • HKEY_CURRENT_CONFIG

In this case, the app data is stored in HKEY_CURRENT_USER, so that’s the base to connect to. Then the subkey can be appended to get to the right place in the hierarchy for the Putty sessions.

Of course, sometimes there are no sessions, so that case must be handled.

The Registry is also a little weird in that what it calls “keys” actually contain many subkeys. Each subkey of “Sessions” will be a saved session. Here’s what my registry looks like:

The subkeys are enumerated in the info hash in order. So, it is a simple matter to walk through the this list, get the meta-data for that key and extract useful values from it. Each saved session, for example, as a string “value” called “HostName” that contains the address used to connect to the host. There are many, many values for each saved session, but you’ll have to consult the putty source code to figure out what each does.

To change a “value”, you need to open the key that owns it. Then invoke the right SetValue() method on it. See the _winreg docs for more. In this case, to change the address of a saved session, to code might look like this:

newIP = "1.2.3.4"
_winreg.SetValueEx(KeyToSession, "HostName", None, _winreg.REG_SZ, newip)
_winreg.CloseKey(KeyToSession)

This code assumes that KeyToSession has already been opened.