以下是一个使用 telnetlib
库实现通过 Telnet 远程登录后判断文件是否存在的 Python 脚本示例:
python
import telnetlib
import time
def check_file_exists_via_telnet(host, port, username, password, file_path):
tn = telnetlib.Telnet(host, port)
# 等待登录提示符
tn.read_until(b"login: ", timeout=5)
tn.write(username.encode('ascii') + b"\n")
# 等待密码提示符
tn.read_until(b"Password: ", timeout=5)
tn.write(password.encode('ascii') + b"\n")
# 发送命令判断文件是否存在
tn.write(f"if [ -f {file_path} ]; then echo 'File exists'; else echo 'File does not exist'; fi\n".encode('ascii'))
# 等待命令执行结果
time.sleep(1)
result = tn.read_very_eager().decode('ascii')
if "File exists" in result:
return True
elif "File does not exist" in result:
return False
else:
raise Exception("无法确定文件是否存在")
# 示例用法
host = "your_host"
port = 23
username = "your_username"
password = "your_password"
file_path = "/your_file_path"
exists = check_file_exists_via_telnet(host, port, username, password, file_path)
if exists:
print("文件存在")
else:
print("文件不存在")
在上述代码中,您需要将以下内容替换为实际的值:
your_host
:远程主机的地址。your_username
:登录用户名。your_password
:登录密码。/your_file_path
:要检查的文件路径。
请注意,此代码可能需要根据实际的 Telnet 服务器响应进行一些调整。
复制重新生成