python 脚本之批量更改主机名

   今天接到上面工作任务,让更改多台主机的主机名称。使用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

python 脚本之批量更改主机名,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。