【问题标题】:How to edit text file in server using python如何使用python在服务器中编辑文本文件
【发布时间】:2020-07-10 11:19:35
【问题描述】:

我想使用 python 在 Linux 服务器的文本文件中编辑一行。该过程涉及以下步骤

  1. Telnet 到服务器(使用 telnetlib)
  2. 进入需要的目录
  3. 打开目录下的文本文件
  4. 根据需求设置或取消设置文本文件中变量的标志(YES或NO)
  5. 保存文件并退出

我能够在第 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


    【解决方案1】:

    如果您能够连接到远程服务器,其余的应该如下工作:

    with open('path/to/file','r') as fr:
        data = fr.readlines() # returns list of lines
        changed_data = ["changed_data\n" if line=="line_to_change\n" else line 
                       for line in data]
    
    with open('path/to/file','w') as fw:
        for line in changed_data:
            fw.write(line) # write the lines back to the back   
    

    【讨论】:

    • 它仅附加到不是所需任务的现有文本。我想替换一行并覆盖现有文件。我认为在编写 f.close() 后必须关闭文件
    • r+ 应该覆盖该文件。您是否使用了正确的模式?
    • @Ganesh,我已经更新了答案并在我的本地机器上检查了它。让我知道它对你不起作用......
    • 代码重写了整个 txt 文件,并带有这一行 -'the_line_you_want_to_change'。仅供参考,我没有给出文件的任何路径,我只是给出了文件名
    • @Ganesh 更新了我的解决方案,请检查一下。 path/to/file 是文件的完整位置。如果您从文件所在的文件夹中运行 python 代码,您可以将filename
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2019-03-20
    • 2023-04-04
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多