我正在尝试在python中编写一个脚本,该脚本连接到我们所有的ftps并告诉我它们已经启动并在连接时列出它们的目录。
我会尝试使用名为“ips.txt”的文件,我们所有的ips都在其中 - 每行一行,以及以下脚本:
import socket
import ftplib
username = "xxx"
password = "xxx"
for server in open("ips.txt", "r").readlines():
try:
ftp = ftplib.FTP(server)
welcome = ftp.getwelcome()
print (welcome)
try:
attempt = ftp.login(user=username, passwd=password)
success = ("[****] Working " + server + '\n')
print(success)
data = []
ftp.dir(data.append)
for lines in data:
print (lines)
except:
print (server, username, password)
pass
except:
print ("Timeout...")
但似乎脚本正在跳过所有内容而只是打印“超时......”:(
我是一个血腥的蟒蛇初学者,所以请耐心等待。
编辑: 删除外部尝试后/除了我得到了追溯:
Traceback (most recent call last):
File "ftp.py", line 12, in <module>
ftp = ftplib.FTP(server)
File "C:\Python3.5.1\lib\ftplib.py", line 118, in __init__
self.connect(host)
File "C:\Python3.5.1\lib\ftplib.py", line 153, in connect
source_address=self.source_address)
File "C:\Python3.5.1\lib\socket.py", line 693, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "C:\Python3.5.1\lib\socket.py", line 732, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
ips.txt看起来像:
10.10.10.10
10.10.10.11
10.10.10.21
10.10.10.33
每个IP的新行
答案 0 :(得分:2)
根据您提供的文件,当您进行readlines
调用时,您仍然会在每个IP的末尾保留换行符。这很可能是为什么你得到了gaierror
。
在我的结尾复制,使用换行符,我的追溯产生:
>>> FTP('10.10.10.10\n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 118, in __init__
self.connect(host)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ftplib.py", line 153, in connect
source_address=self.source_address)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 693, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 732, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
简单地说:
FTP(server.strip())
然后,您将删除IP末尾的\n
,并且至少应该调用正确的 IP地址。
或者,您可以尝试查看splitlines
是否适合您,考虑到您正在处理单个IP地址列表,它可能是一个不错的选择。
splitlines会针对string
删除换行符,因此您还需要在打开的对象上调用read
。像这样:
for server in open("ips.txt", "r").read().splitlines():