Home > Software engineering >  Python3 pass variable to paramiko
Python3 pass variable to paramiko

Time:12-24

So i'm taking all ips from the range 1.1.1.0 to 1.1.1.10 and individually connecting to ssh with each ip. When I run "print(host1)" it gives me the ip but when I use the variable host1 in ssh.connect I get the error "getaddrinfo() argument 1 must be string or None" and if I put the variable host1 into quotes I get the error "can only concatenate str (not "IPv4Address") to str"

    start_ip = ipaddress.IPv4Address('1.1.1.0')
    end_ip = ipaddress.IPv4Address('1.1.1.10')
    for ip_int in range(int(start_ip), int(end_ip)):
    host1 = ipaddress.IPv4Address(ip_int)
    print(ipaddress.IPv4Address(ip_int))
    print(host1)
    def ssh_connect(password, code=0):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            ssh.connect(host1, port=22, username=username, password=password, timeout=5)

CodePudding user response:

Python is tab dependent. So you had to be careful about that when you code out your control structures. The indentation tells Python which statements should be included in your loops. My advice is to remove the function definition until you get this piece of code working and then if you wanted to generalize the functionality later when you know Python better, better to have a piece of code that works than a piece of code that you don't quite grasp. But spacing at the beginning of the line is used to indicate the scope of control structures. I never saw that before I started coding with Python and it was the hardest thing for me to grasp. It looks like you might be having trouble with that too.

If you look for the subheading 'Using IP Addresses with other modules' you'll see that you had to typecast the hostname returned by IPv4Address as a string by using str(...)

https://docs.python.org/3/howto/ipaddress.html

  • Related