【发布时间】:2020-07-10 11:19:35
【问题描述】:
我想使用 python 在 Linux 服务器的文本文件中编辑一行。该过程涉及以下步骤
- Telnet 到服务器(使用 telnetlib)
- 进入需要的目录
- 打开目录下的文本文件
- 根据需求设置或取消设置文本文件中变量的标志(YES或NO)
- 保存文件并退出
我能够在第 2 步之前实现自动化。但是,我被困在第 3 步到第 5 步。
我试图模仿我手动执行的步骤(使用 vim 编辑器)。但我无法执行“ESC”、替换和“:wq!”脚步。是否有替代程序来编辑文件或模仿手动过程进行改进的任何方法
我在这里添加了我的代码
host = input("Enter the IP address:")
port = input("Enter the port:")
tn = telnetlib.Telnet(host,port)
tn.write(b'\n')
tn.read_until(b"login:")
tn.write(b"admin" + b'\n')
tn.read_until(b"Password:")
tn.write(b"admin" + b'\n')
tn.write(b"version" + b'\n')
tn.write(b"path/to/file/" + b'\n')
# OPEN THE FILE and SET or RESET THE FLAG and CLOSE
with in_place.InPlace('filename.txt') as file:
for line in file:
line = line.replace('line_to_change', 'changed_data')
file.write(line)
print('Task executed')
我尝试使用就地库来设置标志,但程序正在我的本地机器而不是服务器中查找文件。因此它会抛出一条错误消息,指示该文件不存在。
【问题讨论】:
标签: python linux server automation file-handling