0

I am currently trying to get ip address from text. But the code I tried is only getting the last line from the file. I am using the following code

import paramiko
import time
import getpass
import sys
import socket
import re

user = raw_input("Enter you username: ")
password = getpass.getpass()
inp = open(r'ipaddressrouter.txt', 'r') 


for line in inp:
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=line,username=user,password=password)
        print "Successful Connection to " + line + '\n'
        stdin, stdout, stderr = ssh_client.exec_command('sh ip int b \n')
        output = stdout.read()
        out = open('out.txt', 'a')
        out.write(line + '\n')  
        out.write(output + '\n')
        out.write('\n')
    except (socket.error, paramiko.AuthenticationException):
            status = 'fail' 

ssh_client.close

help would be appreciated

Update:

When I removed except

I got the following error

File "C:\Users\abc\Desktop\Python Test Scripts\newstest2.py", line 20, in

ssh_client.connect(hostname=host,username=user,password=password)

File "C:\Python27\lib\site-packages\paramiko\client.py", line 329, in connect to_try = list(self._families_and_addresses(hostname, port)) File "C:\Python27\lib\site-packages\paramiko\client.py", line 200, in _families_and_addresses hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)socket.gaierror: [Errno 11004] getaddrinfo failed

Can some one help me out ?

6
  • what is an example file? Commented Jul 5, 2018 at 15:52
  • try using regex to match the string of the ip address pattern Commented Jul 5, 2018 at 15:55
  • Its ip address list Commented Jul 5, 2018 at 15:57
  • Like 10.0.0.1 10.0.0.2 Commented Jul 5, 2018 at 15:57
  • 1. How many times do you see Successful Connection to...? Do you see a message for each entry in ipaddressrouter.txt or only the last one too? 2. You open the file out.txt multiple times but never close it. Try with open('out.txt', 'a') as out: 3. You open the file ipaddressrouter.txt twice and use only one (and also never close it). Commented Jul 5, 2018 at 16:10

2 Answers 2

1
for line in inp:

will store the next line of inp in line including the terminating new line character '\n'. When you pass this unmodified to ssh_client.connect(), then the host name will include '\n'. The reason that you get a successful connection with the last line of your input file is very likely that the last line is not terminated by '\n'.

One way to remove the '\n' is:

line = line.strip()

To put it all together, including my comments to your question regarding the recommended use of with:

import socket

import paramiko

# get user/password as in the question code (not repeated here)
# ....

status = 'OK'

with open(r'ipaddressrouter.txt', 'r') as inp:
    for line in inp:
        line = line.strip()
        with paramiko.SSHClient() as ssh_client:
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                ssh_client.connect(hostname=line, username=user, password=password)
                print("Successful Connection to " + line)
                stdin, stdout, stderr = ssh_client.exec_command('target command here')
                output = stdout.read()
                with open('out.txt', 'a') as out:
                    out.write(line + '\n')
                    out.write(str(output, encoding='utf-8') + '\n')
                    out.write('\n')
            except (socket.error, paramiko.AuthenticationException) as e:
                print("Failed connection to " + line)
                status = 'fail'

Note:

I modified your example to work with Python3. Some of my changes are probably not necessary for Python2. If you are not forced to use Python2, I would always recommend to use Python3 for new projects. See End of support for python 2.7?

Sign up to request clarification or add additional context in comments.

Comments

0
import re
lis_of_ip = ['10.1.1.1','10.1.1']
for ip in lis_of_ip:
    if(re.match('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|$)){4}', ip)):
        print(ip,'true')
    else:
        print(ip,'false')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.