Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing .ssh/config for proxy information

I would like to parse the .ssh/config file for proxy information contained therein and display each host that has related proxy information with the proxy information. Hosts that do not have any proxy information should be filtered out. Man page for .ssh/config: http://man-wiki.net/index.php/5:ssh_config

This should be done from a Unix shell script under Bash, so a standard tool like Perl, awk or sed is preferred.

Example input file:

Host ssh.foo.com
    User ssh
    HostName ssh.foo.com
    Port 443
    ProxyCommand /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth

Host ci
    HostName 127.0.0.2
    User ci

Host nightly
    HostName 192.168.1.1
    User goodnight

Host foobar.org
    User git
    HostName foobar.org
    Port 443
    ProxyCommand /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth

Host integration
    HostName 192.168.1.2
    User int

The expected output should look like this:

Host: ssh.foo.com - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth
Host: foobar.org - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth

The difficulty here is that the search has to cover multiple lines.

like image 713
nwinkler Avatar asked Mar 14 '26 12:03

nwinkler


2 Answers

Try following awk command:

awk '
    $1 == "Host" { 
        host = $1 ": " $2; 
        next; 
    } 
    $1 == "ProxyCommand" { 
        $1 = ""; 
        sub( /^[[:space:]]*/, "" ); 
        printf "%s - Proxy: %s\n", host, $0;
    }
' .ssh/config

It yields:

Host: ssh.foo.com - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth
Host: foobar.org - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth
like image 97
Birei Avatar answered Mar 16 '26 03:03

Birei


an awk oneliner may work for your requirement:

awk -v RS="" '/Proxy/{gsub(/\n/,"");gsub(/\s*User.*ProxyCommand/,"- Proxy:");print}'file

test (a.txt is your input file)

kent$  awk -v RS="" '/Proxy/{gsub(/\n/,"");gsub(/\s*User.*ProxyCommand/,"- Proxy:");print}' a.txt                                                                  
Host ssh.foo.com    - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth
Host foobar.org    - Proxy: /usr/local/bin/corkscrew proxy 8080 %h %p ~/.ssh/proxyauth
like image 44
Kent Avatar answered Mar 16 '26 03:03

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!