今天接到上面工作任务,让更改多台主机的主机名称。使用python paramiko Module,随手写了一个批量修改主机名的脚本。
#!/usr/bin/env python #-*- coding:utf-8 -*- import paramiko HOSTNAME=‘root‘ PORT=22 PASSWD=‘123456‘ NUM=range(139, 144) def changNetwork(): """ change /etc/sysconfig/network HOSTNAME. """ name = 1 for i in NUM: NM = "dcache-ct3-node%s.et.letv.com" % name HOST = "10.180.91.%s" % i ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(HOST, port=PORT, username=HOSTNAME, password=PASSWD) ssh.exec_command(‘sed -i "s/HOSTNAME=.*/HOSTNAME=%s/" /etc/sysconfig/network‘ % NM) ssh.close() name +=1 def changeHostName(): """ change hostname. """ name = 1 for i in NUM: NM = "dcache-ct3-node%s.et.letv.com" % name HOST = "10.180.91.%s" % i ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(HOST, port=PORT, username=HOSTNAME, password=PASSWD) ssh.exec_command(‘hostname %s ‘ % NM) ssh.close() name +=1 def showNetwork(): """ show /etc/sysconfig/network HOSTNAME. """ name = 1 for i in NUM: HOST = "10.180.91.%s" % i ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(HOST, port=PORT, username=HOSTNAME, password=PASSWD) stdin, stdout, stderr = ssh.exec_command(‘cat /etc/sysconfig/network | grep "^HOSTNAME="‘) for i in stdout: print i print HOST ssh.close() #print "dcache-zb6-node%s.et.letv.com" % name #name +=1 def showHostName(): """ show hostname. """ name = 1 for i in NUM: HOST = "10.180.91.%s" % i ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(HOST, port=PORT, username=HOSTNAME, password=PASSWD) stdin, stdout, stderr = ssh.exec_command(‘hostname‘) for i in stdout: print i print HOST ssh.close() if __name__ == "__main__": changNetwork() changeHostName() showNetwork() showHostName()
本文出自 “系统运维” 博客,请务必保留此出处http://davidbj.blog.51cto.com/4159484/1382808