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

如何在telnet write命令中嵌入变量以动态生成文件名?

解决方案:用Host变量动态生成TFTP文件名

当然可行!你只需要利用Python的字符串格式化功能,把host变量的值嵌入到copy命令里就行。这里推荐用f-string(Python 3.6+支持),语法简洁直观,非常适合这种动态拼接字符串的场景。

修改后的完整代码

import telnetlib
import sys
import getpass

host = "192.168.1.1"
tn = telnetlib.Telnet(host, "23")

tn.write((" \n").encode('ascii'))
tn.write((" \n").encode('ascii'))
tn.write(("terminal length 1000 \n").encode('ascii'))
tn.write(("terminal width 24 \n").encode('ascii'))

# 用f-string动态替换文件名,自动匹配host变量的值
copy_command = f"""copy command-output "show tech all" tftp 192.168.1.10 {host}.txt \n"""
tn.write(copy_command.encode('ascii'))

tn.write(("exit \n").encode('ascii'))
tn.write(("exit \n").encode('ascii'))
tn.write(("y").encode('ascii'))

print(tn.read_all())

关键细节说明

  • 我们把copy命令单独提取出来,用{host}占位符嵌入到文件名位置,运行时会自动替换成你设置的服务器IP,比如host值为192.168.1.1时,文件名就变成192.168.1.1.txt。
  • 如果你的Python版本低于3.6,也可以用str.format()方法替代f-string,写法如下:
    copy_command = """copy command-output "show tech all" tftp 192.168.1.10 {}.txt \n""".format(host)
    
  • 注意保持命令里的引号、空格和原格式一致,避免设备无法识别命令。

这样修改后,每次调整host变量的IP值,TFTP服务器上生成的文件名就会自动对应目标设备,完美满足你的需求~

内容的提问来源于stack exchange,提问作者Kaushik Hande

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:26