本文介绍如何使用脚本批量修改多台主机的计算机名,分别针对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"
步骤:
hosts_list.txt
文件。rename_hosts.sh
),并赋予执行权限:chmod +x rename_hosts.sh
。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" }
步骤:
computers.csv
文件。.ps1
文件(例如rename_windows_hosts.ps1
)。.rename_windows_hosts.ps1
(脚本会提示输入目标计算机的用户名和密码)。重要提示:
希望以上信息对您有所帮助。