2

I have two lists, the first list is hostnames to ssh to, the second list is a tunnel to look for on the given hostname. I need the first item in list hostnames to run only the first item in list tunnels. Then I need the second item in list hostnames to run only the second item in list tunnels. Below is a sample of what I was using, but clearly isn't working for me.

hostnames = ["router1", "router2"]
tunnels = ["Tu1000", "Tu5000"
for i in range (0, len(hostnames)):
 try:

        ssh1 = paramiko.SSHClient()
        ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh1.connect(hostnames[i], port=22, username=username, password=password, look_for_keys=False, allow_agent=False)
        print "SSH connection to %s established.\n" % hostnames[i].upper()
        ssh = ssh1.invoke_shell()
        for j in range(0, len(tunnels)):

            ssh.send("!\n")
            ssh.send("en\n")
            ssh.send(password)
            ssh.send("\n!\n")
            time.sleep(1)
            output = ssh.recv(65535)

            ssh.send("sh int desc | i " + tunnels[j] + "\n")
            time.sleep(1)
            output = ssh.recv(65535)
            output = output.split(" ")
            cli_hostname = output[55]
Byeongguk Gong
  • 113
  • 1
  • 9
Chicostix89
  • 367
  • 2
  • 5
  • 2
    When you ask a mechanic for help to diagnose a problem with your car hopefully you don't just point at your car and say "it doesn't work". – janos Dec 02 '17 at 13:19
  • 1
    By the way, `for host in hostnames` looks cleaner – OneCricketeer Dec 02 '17 at 13:27
  • 3
    Possible duplicate of [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – OneCricketeer Dec 02 '17 at 13:29

3 Answers3

7

You could try something like this -

hostnames = ["router1", "router2"]
tunnels = ["Tu1000", "Tu5000"]
for hostname, tunnel in zip(hostnames, tunnels):
  # Do stuff with `hostname` and `tunnel`
  ....

Read about zip function here.

Read about tuple unpacking here.

Yasser Hussain
  • 854
  • 7
  • 21
  • Sorry for the duplicate question, I wasn't able to find this hence my submission. I'm going to look into this but it appears to help a lot. This is better than the below answer because I believe I can use hostname at one point through the loop and the tunnel at a different point in the same loop instance. – Chicostix89 Dec 02 '17 at 17:17
3
>>> for i in zip(hostnames, tunnels):
...   print i
...
('router1', 'Tu1000')
('router2', 'Tu5000')
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can define the router with its route directly as a tuple

data = [("router1", "Tu1000"),  ("router2", "Tu5000")]

for host, tunnel in data:
    # ssh to host 
    # send command to tunnel 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245