Revision 0232b768 lib/utils/io.py

b/lib/utils/io.py
828 828
  return None
829 829

  
830 830

  
831
_SSH_KEYS_WITH_TWO_PARTS = frozenset(["ssh-dss", "ssh-rsa"])
832

  
833

  
834
def _SplitSshKey(key):
835
  """Splits a line for SSH's C{authorized_keys} file.
836

  
837
  If the line has no options (e.g. no C{command="..."}), only the significant
838
  parts, the key type and its hash, are used. Otherwise the whole line is used
839
  (split at whitespace).
840

  
841
  @type key: string
842
  @param key: Key line
843
  @rtype: tuple
844

  
845
  """
846
  parts = key.split()
847

  
848
  if parts and parts[0] in _SSH_KEYS_WITH_TWO_PARTS:
849
    # If the key has no options in front of it, we only want the significant
850
    # fields
851
    return (False, parts[:2])
852
  else:
853
    # Can't properly split the line, so use everything
854
    return (True, parts)
855

  
856

  
831 857
def AddAuthorizedKey(file_obj, key):
832 858
  """Adds an SSH public key to an authorized_keys file.
833 859

  
......
837 863
  @param key: string containing key
838 864

  
839 865
  """
840
  key_fields = key.split()
866
  key_fields = _SplitSshKey(key)
841 867

  
842 868
  if isinstance(file_obj, basestring):
843 869
    f = open(file_obj, "a+")
......
848 874
    nl = True
849 875
    for line in f:
850 876
      # Ignore whitespace changes
851
      if line.split() == key_fields:
877
      if _SplitSshKey(line) == key_fields:
852 878
        break
853 879
      nl = line.endswith("\n")
854 880
    else:
......
870 896
  @param key: string containing key
871 897

  
872 898
  """
873
  key_fields = key.split()
899
  key_fields = _SplitSshKey(key)
874 900

  
875 901
  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
876 902
  try:
......
880 906
      try:
881 907
        for line in f:
882 908
          # Ignore whitespace changes while comparing lines
883
          if line.split() != key_fields:
909
          if _SplitSshKey(line) != key_fields:
884 910
            out.write(line)
885 911

  
886 912
        out.flush()

Also available in: Unified diff