首页 > 文章列表 > 如何用脚本批量修改hostname

如何用脚本批量修改hostname

386 2025-03-25

如何用脚本批量修改hostname

本文介绍如何使用脚本批量修改多台主机的计算机名,分别针对Linux和Windows系统提供解决方案。


Linux系统批量修改主机名

以下方法假设你已准备一个名为hosts_list.txt的文件,包含主机IP和对应主机名,格式如下:

192.168.1.10 host1
192.168.1.11 host2
192.168.1.12 host3

方法一:Bash脚本

以下Bash脚本读取hosts_list.txt,逐一修改主机名:

#!/bin/bash

HOST_LIST="hosts_list.txt"

while IFS=' ' read -r ip hostname; do
  echo "正在修改主机名:$hostname (IP: $ip)"
  echo "$hostname" | sudo tee /etc/hostname > /dev/null
  sudo sed -i "s/^$ip.*/$ip $hostname/g" /etc/hosts
  sudo systemctl restart networking
  echo "主机名 $hostname 修改完成"
done < "$HOST_LIST"

步骤:

  1. 创建并编辑hosts_list.txt文件。
  2. 将以上脚本保存为可执行文件(例如rename_hosts.sh),并赋予执行权限:chmod +x rename_hosts.sh
  3. 以root用户身份运行脚本:sudo ./rename_hosts.sh

方法二:Ansible自动化工具

对于大量主机,Ansible更有效率。 需先安装Ansible:pip install ansible

创建Ansible Playbook文件rename_hosts.yml

---
- name: 批量修改主机名
  hosts: your_group
  become: yes
  tasks:
    - name: 修改 /etc/hostname
      replace:
        path: /etc/hostname
        regexp: '^.*$'
        replace: "{{ inventory_hostname }}"
    - name: 修改 /etc/hosts
      replace:
        path: /etc/hosts
        regexp: '192.168.1.{{ inventory_ip }}s+.*'
        replace: '{{ inventory_ip }} {{ inventory_hostname }}'
    - name: 重启网络服务
      systemd:
        name: networking
        state: restarted

运行Playbook:ansible-playbook -i inventory_file rename_hosts.yml (你需要一个名为inventory_file的Ansible清单文件,定义主机组your_group)


Windows系统批量修改计算机名

假设你已准备一个名为computers.csv的CSV文件,包含IP和主机名两列:

IP,Hostname
192.168.1.10,PC1
192.168.1.11,PC2
192.168.1.12,PC3

方法一:PowerShell脚本

以下PowerShell脚本读取computers.csv,远程修改计算机名:

$csvPath = "computers.csv"
$computers = Import-Csv -Path $csvPath

foreach ($computer in $computers) {
  $ip = $computer.IP
  $hostname = $computer.Hostname
  $session = New-PSSession -ComputerName $ip -Credential (Get-Credential)
  Invoke-Command -Session $session -ScriptBlock {
    param($newHostname)
    Rename-Computer -NewName $newHostname -Force
    Clear-DnsClientCache
  } -ArgumentList $hostname
  Remove-PSSession -Session $session
  Write-Host "已成功将 $ip 的计算机名更改为 $hostname"
}

步骤:

  1. 创建并编辑computers.csv文件。
  2. 保存以上脚本为.ps1文件(例如rename_windows_hosts.ps1)。
  3. 以管理员身份运行PowerShell,并执行脚本:.rename_windows_hosts.ps1 (脚本会提示输入目标计算机的用户名和密码)。

重要提示:

  • 在执行任何脚本之前,务必备份相关配置文件。
  • 确保拥有足够的权限来修改主机名和网络配置。
  • 在生产环境中运行脚本前,请在测试环境中充分测试。
  • 远程修改计算机名需要目标计算机开启远程管理功能。

希望以上信息对您有所帮助。