python实例
admin
2023-07-20 16:22:30
0

python实例

一、RHEL7/CentOS7主机有四块网卡,eth0/eth2/eth3/eth4。为四块网卡配置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)eth2
(2)eth3
(3)eth4
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  脚本名称  远程服务器地址文件  "需要的执行命令" >

相关内容

热门资讯

原创 中... 尹希这个名字,或许并不是每个人都熟悉,但在科学圈内,他曾经是被反复提起的“少年天才”的典型代表。早在...
伊美谈判相关斡旋方21日在埃及... 新华社德黑兰6月19日电(记者陈霄 沙达提)据伊朗伊斯兰共和国广播电视台19日报道,埃及和巴基斯坦当...
减少国家干预,古巴通过170余... 据凤凰卫视报道,古巴总理马雷罗6月18日在会上公布了170多项举措,并获得一致通过。这些举措旨在减少...
郑州一汽车用品商城起火,有楼栋... 极目新闻记者 李贤诚6月19日晚,郑州市金水区居民陈先生反映,离他家百余米处的宏达国际车业广场突发火...
伊朗外长:美应对任何违反谅解备... 当地时间6月19日,伊朗外长阿拉格齐与巴基斯坦副总理兼外长达尔通电话。双方就地区局势交换了意见。通话...
科技创新如何改变普通人的生活 科技创新, 听起来好似实验室里那种高深莫测的课题, 事实上呢, 它已然静悄悄地走入了你我的平常生活里...
校长喊你吃饺子!大学最香最暖的... 又是一年毕业季,离别依依,情意浓浓。在这离别时刻,大连东软信息学院校长郭权走进食堂,挽起袖子,与毕业...
全球可用模型第一!智谱上线并开... 国产大模型慢慢追上来了! 6月17日,智谱上线并开源新一代旗舰大模型GLM-5.2,主攻“长程任务...
全球智能手机销量连续第九周同比... 【CNMO科技消息】市场研究机构Counterpoint Research最新发布的周度销量追踪数据...
2026年抱箍太阳能路灯区域深... 抱箍太阳能路灯是一种无需预埋基础、通过抱箍结构直接固定在现有灯杆上的太阳能照明产品,其安装灵活、适配...