如何使用 python fabric 在远程服务器上的文件上创建 changes/edit?

How to make changes/edit on a file present on remote server using python fabric?

我在远程服务器中有一个 .yml 文件,我想使用 python 结构对其进行更改。如果可以与其他 python 库一起完成,请随时分享。 谢谢

您正在尝试编辑文件中间的一行,但我认为这是不可能的。 您可以做的是使用您想要更改的所需值在本地计算机上制作远程文件的副本,然后将其发送回远程服务器。

from fabric import Connection as connection, task

@task
def executeTask(ctx):
    with connection(host=dev_server, user=myuser) as c:
         c.put('PATH_TO_YOUR_YML_FILE_LOCALLY', 'PATH_TO_YOUR_REMOTE_YML_FILE')

别忘了:

  1. dev_servermyuser替换为远程服务器IP和用户名就可以了
  2. 将上面的代码放在一个名为 fabfile.py 的文件中,然后您 运行 从命令行 fab executeTask

以上代码 fabric 2.4 兼容

编辑: 由于权限问题,您可以执行以下操作:

@task
def executeTask(ctx):
    with connection(host=dev_server, user=myuser) as c:
         c.put("PATH_TO_YOUR_YML_FILE_LOCALLY") # implicit to remote $HOME
         c.sudo("mv YOUR_FILE_NAME YOUR_DESIRED_LOCATION") # again implicitly with a CWD of $HOME 
         c.sudo("chown root:root YOUR_REMOTE_FILE") 

参考: https://github.com/fabric/fabric/issues/1750#issuecomment-406043571

如果您只需要更改端口号,您可以像这样使用 sed

def change_port(filename):
    with cd('/location'):
         run('sed -i "s/old_port_number/new_port_number/g" ' +filename)