如何使用fabric编辑主机名文件

时间:2013-02-05 16:11:52

标签: python fabric

我已更改主机文件,因此如何更改hostname.my系统是ubuntu。 例如我的主持人档案:

192.168.0.100 host1.mydomain.com
192.168.0.101 host2.mydomain.com

我想将host1的/ etc / hostname下的主机名文件发送到host1.mydomain.com,将host2的主机名文件发送到host2.mydomain.com

如何使用面料做到这一点? 我必须ssh每个主机并编辑主机名文件,结构可以这样做吗?

我不是要使用hostname命令,而是编辑/ etc / hostname文件。 我的意思是如何使用面料来做到这一点: 如:

def update_hostname():
  get("/etc/hosts","hosts")
  hosts_content = file("hosts")
  **hostname = ·get the hostname corespond to ip·**
  get("/etc/hostname","hostname")
  update `hostname file`
  put("hostname","/etc/hostname")

如何获得IP?因为结构在每个主机上完成工作,主机名对应于每个主机。我需要知道作业正在哪个主机工作,然后获取ip,然后获取主机名对应的ip,最后更新主机名文件。 enter image description here

3 个答案:

答案 0 :(得分:1)

Fabric只是一个SSH包装器,所以你所看到的是LINUX特定的,而不是frabric或python特定的。

from fabric.api import run
run('hostname your-new-name')
run('echo your-new-hostname > /etc/hostname')

根据你的linux dist进行运行(..编辑..)

或者只是这样做:

from subprocess import Popen, PIPE
hosts = open('/etc/networking/hosts', 'rb')
for hostline in hosts.readlines():
    ip, name = hostline.split(' ')
    command = ['ssh', '-t', 'root@' + host.strip('\r\n ,;), ' ', "echo " + name.strip('\r\n ,;) + " > /etc/hostname",]
    stdout, stderr = Popen(command, stdout=PIPE, stderr=PIPE).communicate()
hosts.close()

注意: / etc / networking / hosts可能会放在其他地方。 这里的重要部分是你遍历/ hosts文件,并ssh到每台机器,回显给定机器的给定主机名。

答案 1 :(得分:1)

def hostname():

   '''
   function to change the hostname of the ubuntu server
   '''

   server_hostname = prompt ("The Hostname for the server is :")

   sed ("/etc/hostname", before='current hostname', after='%s' % (server_hostname), use_sudo=True,backup='')

   sudo ("init 6")

这将根据您的选择更改主机名。

答案 2 :(得分:0)

在你的结构脚本中

你需要......

  • 以允许编辑hosts文件的用户(通过权限或组)ssh进入计算机。如果您需要sudo进入用户,请搜索StackOverflow以查找有关sudo和Fabric的问题 - 您需要调整fabfile以不提示输入密码。

  • fabric可以有一种处理读/写/打开文件的尴尬方式。你可能会被cd带到正确的目录中。类似......

    用cd('/ etc /')     run('echo new_hostname hostname')