You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python ftplib登录FTP服务器报错:无法拼接str与list对象

问题分析与解决方案

嘿,我来帮你捋清楚这个问题~你遇到的TypeError: cannot concatenate 'str' and 'list' objects错误,根源其实出在你读取用户名和密码的方式上!

错误原因

你用了readlines()方法读取文件:

us = user.readlines()
pa = passw.readlines()

这个方法的返回值不是字符串,而是一个列表——列表里的每个元素对应文件中的一行(还包含每行末尾的换行符\n)。而FTP.login()方法要求传入的用户名和密码必须是字符串类型,当ftplib内部尝试执行'USER ' + user时,就会把字符串和列表拼接,自然触发类型错误啦。

你说“并未声明任何列表”,其实readlines()已经悄悄帮你创建了列表哦😉

解决方案

根据你的文件内容情况,有两种处理方式:

情况1:文件里只有一行用户名/密码

如果usss.txt和passs.txt里各只存了一个账号和密码,直接用read()读取全部内容,再用strip()去掉多余的换行符和空白字符:

from ftplib import FTP

ip = raw_input("Enter ip: ")
# 用with语句自动管理文件,避免忘记关闭
with open("usss.txt","r") as user_file:
    us = user_file.read().strip()
with open("passs.txt","r") as pass_file:
    pa = pass_file.read().strip()

conection = FTP(ip)
try:
    state_ftp = conection.login(us, pa)
    print state_ftp
    print "[+]CONECTION SUCCESSFUL!"
except Exception as e:
    print f"Login failed: {str(e)}"
finally:
    conection.quit()

情况2:文件里有多组用户名/密码

如果你的文件里每行一个账号/密码,需要遍历尝试的话,就先把列表里的每个元素处理成干净的字符串,再循环登录:

from ftplib import FTP

ip = raw_input("Enter ip: ")
with open("usss.txt","r") as user_file:
    # 读取每行并去除空白和换行,同时跳过空行
    users = [line.strip() for line in user_file if line.strip()]
with open("passs.txt","r") as pass_file:
    passwords = [line.strip() for line in pass_file if line.strip()]

# 假设用户名和密码是一一对应的
for us, pa in zip(users, passwords):
    try:
        conection = FTP(ip)
        state_ftp = conection.login(us, pa)
        print f"Success! Login with {us}: {state_ftp}"
        print "[+]CONECTION SUCCESSFUL!"
        conection.quit()
        break  # 成功后停止尝试
    except Exception as e:
        print f"Failed with {us}: {str(e)}"
        conection.close()

小提示

使用with语句操作文件是更推荐的方式,它会在代码块结束后自动关闭文件,避免资源泄漏哦~

内容的提问来源于stack exchange,提问作者Jhonatan Zu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:42:38