Skip to content

Instantly share code, notes, and snippets.

@geeksunny
Created August 17, 2012 07:17
Show Gist options
  • Save geeksunny/3376694 to your computer and use it in GitHub Desktop.
Save geeksunny/3376694 to your computer and use it in GitHub Desktop.
parseSshConfig: My first ever from-scratch Objective-C program. Parses the contents of your .ssh config file into a dictionary variable. To be used in a future project. -- UPDATED: 2012-09-27 00:13:12 - Rewrote parsing logic to be much more flexible!
//
// main.m
// parseSshConfig
//
// "A very simple .ssh config file parser."
//
// Created by Justin Swanson on 8/17/12.
// Copyright (c) 2012 h4xful.net. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"--- SSH PARSER ---");
NSString *configFile = @"~/.ssh/config";
configFile = [configFile stringByExpandingTildeInPath];
NSFileManager *fileMgr = [[NSFileManager alloc] init];
if ([fileMgr fileExistsAtPath: configFile]) {
NSLog(@"The file exists!");
// Get file contents into fh.
NSString *fh = [NSString stringWithContentsOfFile:configFile encoding:NSUTF8StringEncoding error:nil];
// Initialize our server list as an empty dictionary variable.
NSMutableDictionary *servers = [NSMutableDictionary dictionaryWithObjects:nil forKeys:nil];
// Initialize our placeholder variable for the current server's host value.
NSString *host = @"";
// Loop through each line and parse the file.
for (NSString *line in [fh componentsSeparatedByString:@"\n"]) {
// Find the position of the first space in the line.
NSRange spacePos = [line rangeOfString:@" "];
// If no space is found, skip this line.
if (spacePos.location == NSNotFound) {
continue;
}
// Grab the key and the value.
NSString *key = [line substringToIndex:spacePos.location];
NSString *value = [line substringFromIndex:spacePos.location+1];
// Add the values to the servers dictionary object.
// ... if key is "Host", establish a new sub-dictionary object.
if ([key isEqualToString:@"Host"]) {
host = value;
[servers setObject:[NSMutableDictionary dictionaryWithObjects:nil forKeys:nil] forKey:host];
}
// Now setting the value
[[servers objectForKey:host] setObject:value forKey:key];
}
// Now to walk through the server list and see the data we found
for (NSString *line in servers) {
NSLog(@"Now listing parameters for server named: %@", line);
for (NSString *embeddedLine in [servers objectForKey:line]) {
NSLog(@"Parameter %@: %@", embeddedLine, [[servers objectForKey:line] objectForKey:embeddedLine]);
}
NSLog(@" "); // blank line on the terminal
}
}
else {
NSLog(@"You don't have a .ssh config file!");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment