python telnetlib.telnet() not connecting using variables - python

I am working on a script to pull configs from Cisco devices in GNS3. The script should be looping through a text file and slicing the IP & Port from each line into variables. These variable are then fed into the telnet connection as the IP & Port parameters of Telnetlib.
import telnetlib
#Open file with list of switches
f = open ("C:\ProgramData\ports.txt")
#Telnet to each switch and configure it
for line in f:
linePort = line[10:]
lineIP = line[:-6]
print "Getting running-config " + lineIP + " " + linePort
tn = telnetlib.Telnet(lineIP,linePort)
However using the variables always ends up in an error being thrown (see below) but if I hard code the same values I am able to create the connection without issue. As it works with a hard coded value I tried forcing a string type with str() on the two variables but it didn't change the result and it still throws the below error.
C:\Users\SomeUser>python %userprofile%\desktop\config.py
Getting running-config 127.0.0.1 5000
Traceback (most recent call last):
File "C:\Users\Michael\desktop\config.py", line 11, in <module>
tn = telnetlib.Telnet(lineIP,linePort)
File "C:\python27amd64\lib\telnetlib.py", line 211, in __init__
self.open(host, port, timeout)
File "C:\python27amd64\lib\telnetlib.py", line 227, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\python27amd64\lib\socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed
The error being thrown is socket.gaierrr: [Errno 10109] getaddrinfo failed which I have tried looking into but have not been able to find a resolution for that works for me. Given that this process is supposed to be automated and in a loop it is vital to get it working with variable. As such any help that you all could provide would be much appreciated.

I stumbled across the answer to this in another question and it makes me feel like an idiot for the oversight.
When using variables for the parameters of Telnet the port needs to be an integer. As such the solution was to force it by using int(var) and then it connected without issue. The now working code is as follows.
import telnetlib
#Open file with list of switches
f = open ("C:\ProgramData\ports.txt")
#Telnet to each switch and configure it
for line in f:
linePort = line[10:]
lineIP = line[:-6]
print "Getting running-config " + lineIP + " " + linePort
tn = telnetlib.Telnet(lineIP,int(linePort))

Related

ConnectionRefusedError: [Errno 111] Connection refused

I was trying to use ftp and I am getting the following error:
>>> ftp = ftplib.FTP('192.168.248.108')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/ftplib.py", line 118, in __init__
self.connect(host)
File "/usr/lib/python3.5/ftplib.py", line 153, in connect
source_address=self.source_address)
File "/usr/lib/python3.5/socket.py", line 711, in create_connection
raise err
File "/usr/lib/python3.5/socket.py", line 702, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
I was trying to take it step by step since the whole client and server codes were not running. Help please. Thank you.
EDIT:
This is the client side code:
from ftplib import FTP
ftp = FTP('192.168.248.128')
ftp.login(user='username', passwd = 'password')
ftp.cwd('/Desktop/FTP')
def placeFile():
filename = 'myfile.txt'
ftp.storbinary('STOR '+filename, open(filename, 'rb'))
ftp.quit()
placeFile()
First of all check this ip to see if ftp service is available, and if it is check the port that it is listening on, cause it maybe (rare but possible) is configured to listen on a different port than the standard one - 21 . Also maybe the connection is blocked by a firewall, and that is why connection gets refused.
Also haven't seen the whole code of yours but I think another/different problem is this: def placeFile() should be changed to this instead def placeFile(ftp) - cause the function placeFile doesn't really know that ftp references to the ftp client you created above.

Transferring files via Python's ftplib nondeterministically times out

I'm trying to use ftplib to transfer a set of files from my computer (running 64-bit Windows 7) to a Linux server. The process is similar to this snippet of test code (server address, username, and password changed, obviously):
import ftplib
import os.path
import os
host = "some.ftp.server.com"
username = "username"
password = "password"
outDir = "/some/output/directory"
def transfer_files():
ftp = ftplib.FTP(host, username, password)
ftp.cwd(outDir)
names = ftp.nlst()
if "transferred" not in names:
ftp.mkd("transferred")
ftp.cwd("transferred")
names = ftp.nlst()
# Transfrer arbitrary files to the server
filesToTransfer = os.listdir('.')
for fName in filesToTransfer:
if not os.path.isfile(fName):
continue
if fName in names:
ftp.delete(fName)
with open(fName, 'r') as f:
ftp.storbinary("STOR %s" % fName, f)
print fName
ftp.quit()
print "Done"
if __name__ == "__main__":
transfer_files()
The behavior I'm seeing is that most files transfer quickly and successfully, but randomly a file will instead time out and raise the following exception:
Traceback (most recent call last):
File "Test.py", line 37, in <module>
transfer_files()
File "Test.py", line 29, in transfer_files
ftp.storbinary("STOR %s" % base, f)
File "C:\Python27\Lib\ftplib.py", line 471, in storbinary
conn = self.transfercmd(cmd, rest)
File "C:\Python27\Lib\ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "C:\Python27\Lib\ftplib.py", line 335, in ntransfercmd
conn = socket.create_connection((host, port), self.timeout)
File "C:\Python27\Lib\socket.py", line 575, in create_connection
raise err
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
The file that times out is different each time I run the program, but it always seems to happen to one file or another. Why could the transfer be randomly timing out, and what can I do to prevent this?
When working with network requests in bulk, it's completely normal to get a certain number of timeouts - it's even expected. Rather than try to prevent timeouts from happening (because they always will), you should add logic to your application to handle cases where timeouts occur. Since you're uploading files in bulk, that probably looks like re-attempting the upload when that exception gets raised.

[PYTHON]Email and file connection error

I tried to find some topic related, found some, tried some suggested solution, but seems not to work.
I'm trying to figure out where I did it wrong, I'm basically listing a directory and putting the output into a text file that I want to send via smtp to dest address.
#!/usr/bin/python
import os, sys
import smtplib
from email.mime.text import MIMEText
# GRABE LISTED DIRECTORY AND CREATE THE FILE #
#open folder and list it
Winpath = "C:\"
dirs = os.listdir(Winpath)
#Put it into file
fo = open("activitygraber.txt", "w+")
for file in dirs:
fo.write(file + "\n")
# EMAIL IT TO GIVEN ADDRESS #
msg = MIMEText(fo.read())
fo.close()
msg["Subject"] = "Test ActivityGrab"
msg["From"] = "test#test.me"
msg["To"] = "dest#dest.com"
s = smtplib.SMTP("localhost")
s.sendmail("test#test.me", "dest#dest.com", msg.as_string())
s.quit()
That's simple code mostly from Python documentation (I'm in the learning curve).
The file is being created and ready to send I guess, but somehow the connection is not being created. I guess it's because my smtp port in not open ? should I tried to connect to a mail service ? then send it from there ?
Here the message I get when I try to send it:
Traceback (most recent call last):
File "C:\Users\PC\Desktop\testfile.py", line 33, in <module>
s = smtplib.SMTP("localhost")
File "C:\Python27\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\lib\smtplib.py", line 310, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 285, in _get_socket
return socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
Any help of hint would really be appreciated thanks !
Meanwhile I'm gonna continue to search the cause.
Cheers,
s = smtplib.SMTP("localhost") isn't going to work unless you have a running SMTP server on your local machine (which you probably don't...).
If you do, make sure it's listening on port 25.
If you don't, you will have to use a remote SMTP server. You can use google's if you have a gmail account, or find a free one that is set up as a mail relay (that means you can use it anonymously), but these are very rare these days.

python - use pyftpdlib for file transfer

I am working on file transfer in python. I've been searching a lot but still haven't found a simple demo of a working ftp client-server using pyftpdlib. I think this library is very useful but I don't know how to start using it.
Thank you so much for any help!
EDIT:
OK, I followed the tutorial. My goal is to be able to send/receive files within local machine first.
I run the basic_ftpd.py and get this:
[I 14-07-09 15:08:27] >>> starting FTP server on 127.0.0.1:2121, pid=7000 <<<
[I 14-07-09 15:08:27] poller: <class 'pyftpdlib.ioloop.Select'>
[I 14-07-09 15:08:27] masquerade (NAT) address: None
[I 14-07-09 15:08:27] passive ports: None
Then I run winnt_ftpd.py and I get error:
Traceback (most recent call last):
File "***\lib\winnt_ftpd.py", line 41, in <module>
from pyftpdlib.authorizers import WindowsAuthorizer
ImportError: cannot import name WindowsAuthorizer
Let's assume that I want to send some file in C:/share and in local address I think it should be 127.0.0.1:2121 or localhost:2121. Then from client side I want to get directory listing:
import ftplib
ftp = ftplib.FTP("127.0.0.1:2121")
ftp.login("user", "12345")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
But this is not working, I get following error:
Traceback (most recent call last):
File "C:\Users\***\src\client1.py", line 8, in <module>
ftp = ftplib.FTP("127.0.0.1:2121")
File "C:\Python27\lib\ftplib.py", line 117, in __init__
self.connect(host)
File "C:\Python27\lib\ftplib.py", line 132, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout)
File "C:\Python27\lib\socket.py", line 551, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
EDIT:
I changed
ftp = ftplib.FTP("127.0.0.1:2121")
to
ftp = ftplib.FTP("127.0.0.1")
Then I get this error:
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
Any suggestion?
What about trying this:
conn = ftplib.FTP()
conn.connect('127.0.0.1', 2121)
conn.login('user','12345')
the FTP() constructor accept only the hostname or IP address, instead if you pass nothing and then you configure all with connect() you can pass a tuple with (IP, port)
This should make the trick

handling telnetlib timeout error in python

I am trying to write a python script to establish a telnet connection (using telnetlib) to a range of hosts:
for i in range(len(HOST)):
print "scanning " + HOST[i] + " ...\n"
tn = telnetlib.Telnet(HOST[i],23,3)
The problem is when one of the connections times out, the script executions interrupts and returns the following error:
Traceback (most recent call last):
File "C:\Python27\telnet.py", line 24, in <module>
tn = telnetlib.Telnet(HOST[i],23,3)
File "C:\Python27\lib\telnetlib.py", line 209, in __init__
self.open(host, port, timeout)
File "C:\Python27\lib\telnetlib.py", line 225, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.timeout: timed out
Anyone knows how to skip this error and continue the script?
You need to use a try...except block to catch the exception and tell the interpreter to ignore it. For example:
import socket
for i in range(len(HOST)):
print "scanning " + HOST[i] + " ...\n"
try:
tn = telnetlib.Telnet(HOST[i],23,3)
except socket.timeout:
pass
In this case it's a good idea to explicitly state which exception you want to catch (socket.timeout). Sockets can throw many different types of exceptions so using a generic except: statement might mask a problem with opening, reading or writing to the socket.

Categories

Resources