python脚本 实现 telnet 远程进去之后判断某个文件是否存在

以下是一个使用 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 服务器响应进行一些调整。

复制重新生成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值