python實例

python實例

一、RHEL7/CentOS7主機有四塊網卡,eth0/eth1/eth2/eth3。爲四塊網卡配置IP地址及主機名。

#!/usr/bin/env python
import re
import sys
import subprocess

#定義配置ip地址函數
def configip(fname,ip_addr,if_ind):
    content = '''TYPE=Ethernet
BOOTPROTO=none      
NAME=eth%s
DEVICE=eth%s
ONBOOT=yes
IPADDR=%s
PREFIX=24
''' % (if_ind,if_ind,ip_addr)
    with open(fname,'w') as fobj:
        fobj.write(content)

#定義檢測ip地址是否合法函數
def check_ip(ip_addr):     
    m = re.match(r'(\d{1,3}\.){3}\d{1,3}$',ip_addr)    
    if not m:
        return False
    return True

#定義配置主機名函數
def config_hostname():
    fhostname = '/etc/hostname'
    hostname = raw_input('Input You Hostname: ')
    with open(fhostname,'w') as fobj:
        fobj.write(hostname)
    subprocess.Popen('hostname %s ' % hostname,shell=True)

#定義顯示菜單函數
def show_menu():
    prompt = '''Configure IP Address:
(0)eth0
(1)eth1
(2)eth2
(3)eth3
Your choice(0/1/2/3):'''
    try:
        if_ind = raw_input(prompt).strip()[0]
    except:
        print 'Invalid raw_input.'
        sys.exit(1)

    if if_ind not in '0123':
        print 'Wrong Selection. Use 0/1/2/3/'
        sys.exit(2)

    fname = '/etc/sysconfig/network-scripts/ifcfg-eth%s' % if_ind
    ip_addr = raw_input('ip address: ').strip()
    result = check_ip(ip_addr)
    if not result:
        print 'Invalid ip address!'
        sys.exit(3)
    configip(fname,ip_addr,if_ind)

    subprocess.Popen('systemctl restart network',shell=True)
    print '\033[32;1mConfigure ip address done. \033[0m'

if __name__ == '__main__':
    main_menu = '''(0)config_hostname
(1)config_ipaddr
Your choice(0/1)'''
    try:
        ind = raw_input(main_menu).strip()[0]
    except:
        print 'Invalid raw_input.'
        sys.exit(4)
    if ind not in '01':
        print 'Wrong Selection. Use 0/1'
        sys.exit(5)
    if ind == '0':
        config_hostname()
    show_menu()
備註:
1.  通過指定方式的辦法來獲取地址,如果未指定的化可能會出現問題,有三種模式:static 靜態ip;dhcp 動態ip;none 無(不指定)。
2.  m = re.match(r'(\d{1,3}\.){3}\d{1,3}$',ip_addr)    # r 表示 raw string(原始字符串常量),用於規避反斜槓的轉義。
3.  python2 中 raw_input() 可以接收字符串、中文;input()只接收數字。python3 中無 raw_input() 只有input(),接收字符串、數字、中文,相當於python2中raw_input()和input()的結合。

二、編寫九九乘法表

for i in range(1 ,10):
    for j in range(1 ,i+1):
        print('%sx%s=%s ' % (j, i, j*i),end='')
    print()

三、並行批量管理遠程服務器

import sys
import getpass
import paramiko
import threading
import os

def remote_com(host,pwd,command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host,username='root',password=pwd)
    stdin,stdout,stderr = ssh.exec_command(command)
    out = stdout.read()
    error = stderr.read()
    if out:
        print('[%s] OUT:\n%s' % (host,out.decode('utf8')))
    if error:
        print('[%s] ERROR:\n%s' % (host,error.decode('utf8')))
    ssh.close()

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: %s ipaddr_file "command"' % sys.argv[0])
        exit(1)
    if not os.path.isfile(sys.argv[1]):
        print('No such file:', sys.argv[1])
        exit(2)
    fname = sys.argv[1]
    command = sys.argv[2]
    pwd = getpass.getpass()
    with open(fname) as fobj:
        ips = [line.strip() for line in fobj]

    for ip in ips:
        t = threading.Thread(target=remote_com,args=(ip,pwd,command))
        t.start()
備註:
1. 執行方式< python3  腳本名稱  遠程服務器地址文件  "需要的執行命令" >
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章