如何使用Fabric编辑hostname文件
我修改了我的 hosts 文件,那么如何更改主机名呢?我的系统是 Ubuntu。
192.168.0.100 host1.mydomain.com
192.168.0.101 host2.mydomain.com
我想把 /etc/hostname 下的 host1 的主机名改成 host1.mydomain.com,把 host2 的主机名改成 host2.mydomain.com。
我该如何使用 fabric 来做到这一点?我需要通过 SSH 登录每个主机并编辑主机名文件,fabric 能做到这一点吗?
我不是想用 hostname
命令,而是想编辑 /etc/hostname 文件。我想知道如何用 fabric 来实现这个:
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 地址?因为 fabric 会在每个主机上执行任务,而主机名是对应每个主机的。我需要知道任务正在在哪个主机上运行,然后获取该主机的 IP 地址,再根据这个 IP 地址找到对应的主机名,最后更新主机名文件。

3 个回答
在你的Fabric脚本中,你需要...
通过SSH登录到机器,使用一个有权限编辑hosts文件的用户(这可以通过权限或用户组来设置)。如果你需要用
sudo
切换到另一个用户,可以在StackOverflow上搜索关于sudo和Fabric的问题——你需要调整你的fabfile,以避免在运行时要求输入密码。Fabric处理读取、写入和打开文件的方式可能有点麻烦。你最好先用
cd
命令进入正确的目录。比如说...with cd('/etc/') run('echo new_hostname hostname')
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")
这段代码会根据你的选择来更改主机名。
Fabric其实就是一个SSH的封装工具,所以你看到的内容是跟LINUX系统有关的,不是特别针对fabric或者python的。
from fabric.api import run
run('hostname your-new-name')
run('echo your-new-hostname > /etc/hostname')
你可以根据你的linux版本来运行(..编辑..)这个命令吗?
或者你可以直接这样做:
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连接到每台机器,并把指定的主机名发送到那台机器上。