Search code examples
pythonsocketsdictionarysshsocks

Generate dictionary in python with SSH command


I have a python script that does the following storyline:

  • First check all IPS that do not need VPN for connection, connect by SSH and run CAT command

  • Then check everyone who needs VPN, connect to VPN, and SSH to run CAT command

This part is functional, my problem is to assign the output of this ssh to a python dictionary

#!/usr/bin/python
# -*- coding: utf-8 -*-

from datetime import datetime, date, time, timedelta
import socket
import socks
import paramiko
import sys
import re

# create script head
print ('-----------------------------------------------------------------------------------------')
print ('Initializing UP/DOWN script in: '+str(date.today()))
print ('-----------------------------------------------------------------------------------------')

Ips = {'123.45.44.33': {'customer' : 'webservice'}}
IPsocks = {'176.25.0.61': {'customer' : 'hosting'}}

output = []
outputSocks = []
outfinally = []
outfinallySocks = []
lds_data = {}

for ip in Ips:

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip, username='admin', password="admin")
    output.append((ssh.exec_command('cat /tmp/hosts.txt')[1]).read().decode())
    ssh.close()

    outfinally.append([re.split(r'\s*#\s*',line) for line in output[0].splitlines()])

    for a, b in zip(Ips, outfinally):
        lds_data.update({b[:1] : {'hostname' : b[1:5], 'customer' : Ips[a]['customer']}})

for ip in IPsocks:

    sock=socks.socksocket()
    sock.set_proxy(
        proxy_type=socks.SOCKS5,
        addr='10.0.1.10',
        port=1080,
        username="vpn",
        password="vpn102030"
    )
    sock.connect((ip, 22))

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('ignored without host key verification', username='admin', password='admin', sock=sock)
    outputSocks.append((ssh.exec_command('cat /tmp/hosts.txt')[1]).read().decode())
    ssh.close()

    outfinallySocks.append([re.split(r'\s*#\s*',line) for line in outputSocks[0].splitlines()])

    for a, b in zip(IPsocks, outfinallySocks):
        lds_data.update({b[:1] : {'hostname' : b[1:5], 'customer' : IPsocks[a]['customer']}})

    print(lds_data)

print ('-----------------------------------------------------------------------------------------')
print ('Script successfully completed')
print ('-----------------------------------------------------------------------------------------')

OUTPUT

  File "SCRIPT.py", line 36, in <module>
    lds_data.update({tuple(b[:1]) : {'hostname' : b[1:5], 'customer' : Ips[a]['customer']}})
TypeError: unhashable type: 'list'

ARCHIVE HOSTS

192.168.0.1 #SRVNET
192.168.0.254 #SRVDATA
192.168.0.254 #SRVDATA

Solution

  • This is difficult to reproduce, but assuming that b is a list of lists, we can replace the instances of this line:

    lds_data.update({b[:1] : {'hostname' : b[1:5], 'customer' : IPsocks[a]['customer']}})
    

    with this:

    lds_data.update({tuple(b[0]) : {'hostname' : b[1:5], 'customer' : Ips[a]['customer']}})
    

    This replaces the list of lists with a flattened tuple - this is because keys in dictionaries can't be lists, as they are mutable. The underlying problem with your code is that you are trying to set a dictionary key to be a list.