gpt4 book ai didi

python - 从txt文件读取IP并在python中连接到ftp

转载 作者:行者123 更新时间:2023-12-01 02:50:27 25 4
gpt4 key购买 nike

我正在尝试用 python 编写一个脚本,它连接到我们所有的 ftp,并告诉我它们已启动并在连接时列出它们的目录。

我将尝试使用一个名为“ips.txt”的文件,其中包含我们所有的 ip - 每行一个和以下脚本:

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...")

但脚本似乎跳过了所有内容,只打印“超时...”:(

我是一个该死的Python初学者,所以请耐心等待。

编辑:删除外部 try/except 后,我​​得到了回溯:

    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 都有新行

最佳答案

根据您提供的文件,当您进行 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将为您删除字符串的换行符,因此您还需要在打开的对象上调用 read 。像这样:

for server in open("ips.txt", "r").read().splitlines():

关于python - 从txt文件读取IP并在python中连接到ftp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com