Python编写的Linux网络设置脚本,Debian Wheezy上测试通过

   2023-02-09 学习力0
核心提示:   阿里百川梦想创业大赛,500万创投寻找最赞的APP技术细节参见Linux网络设置高级指南注意事项参见程序注释快速使用指南:根菜单下,直接回车意味着刷新其它输入的时候,除了标明特定含义外,直接回车通常意味着取消或者跳过net-config.py?123456789101112
 
 
 

阿里百川梦想创业大赛,500万创投寻找最赞的APP

Python编写的Linux网络设置脚本,Debian Wheezy上测试通过

Python编写的Linux网络设置脚本,Debian Wheezy上测试通过

技术细节参见Linux网络设置高级指南

注意事项参见程序注释

快速使用指南:

  1. 根菜单下,直接回车意味着刷新
  2. 其它输入的时候,除了标明特定含义外,直接回车通常意味着取消或者跳过

net-config.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
网络设置脚本
在debian wheezy环境下测试通过
依赖命令:ip, iw, wpa_supplicant, wpa_cli, dhclient
注意:
- /etc/network/interfaces里面仅保留lo设备配置
- 与Gnome Network Manager/Wicd是否冲突未知
"""
__author__ = 'M@llon'
__version__ = ''
 
import os
import sys
import traceback
 
import net
 
 
def test(v):
    test.result = v
    return v
 
 
def select_interface(interfaces):
    """
    选择一个已知接口
    返回接口名
    直接回车返回空字符串
    """
    while True:
        name = input('Enter interface name: ')
        if name == '' or name in interfaces:
            return name
 
 
def connect_wireless(interface_name):
    """
    连接无线
    """
    ssid = None
    while True:
        ssid = input('Enter SSID, RETURN for scanning: ')
        if not ssid:
            for s in net.get_ssids(interface_name):
                print(s)
        else:
            break
 
    sec = input('Select security method Open/WEP/WPA [0,1,2]: ')
    if sec == '0':
        net.connect_wireless(interface_name, ssid)
    elif sec == '1':
        keys = input('Enter comma separated keys: ').split(',')
        net.connect_wireless_with_wep(interface_name, ssid, keys)
    elif sec == '2':
        key = input('Enter key: ')
        net.connect_wireless_with_wpa(interface_name, ssid, key)
 
 
def setup_ip_gateway_dns(interface_name):
    """
    手工设置IP地址、默认网关和DNS
    """
    if test(input('Enter comma separated ip addresses: ')):
        ip_addresses = test.result.split(',')
        net.set_ip_addresses(interface_name, ip_addresses)
    if test(input('Enter gateway address: ')):
        ip_address = test.result
        net.set_default_route(interface_name, ip_address)
    if test(input('Enter comma separated dns addresses: ')):
        name_servers = test.result.split(',')
        net.set_name_servers(name_servers)
 
 
if __name__ == '__main__':
    # 提升到root权限
    if os.geteuid():
        args = [sys.executable] + sys.argv
        # 下面两种写法,一种使用su,一种使用sudo,都可以
        #os.execlp('su', 'su', '-c', ' '.join(args))
        os.execlp('sudo', 'sudo', *args)
 
    # 显示根菜单
    while True:
        try:
            interfaces = net.get_interfaces()
 
            os.system('clear')
            net.print_state(interfaces, net.get_default_route(), net.get_name_servers())
        except Exception as ex:
            traceback.print_exc()
            break
 
        print('Root Menu:')
        print('    0 - Quit')
        print('    1 - cleanup all settings')
        print('    2 - enable interface')
        print('    3 - disable interface')
        print('    4 - connect interface')
        print('    5 - disconnect interface')
        print('    6 - setup ip, gateway and dns using dhcp')
        print('    7 - setup ip, gateway and dns manually')
        print('    8 - load preset')
        print()
 
        try:
            choice = input('Enter your choice: ')
            if choice == '0':
                break
            elif choice == '1':
                if input('Are you sure? [y/n]: ').lower() == 'y':
                    net.cleanup_all(interfaces)
            elif choice in ('2', '3', '4', '5', '6', '7') and test(select_interface(interfaces)):
                name = test.result
                if choice == '2':
                    if not interfaces[name]['enabled']:
                        net.enable_interface(name)
                elif choice == '3':
                    if interfaces[name]['enabled']:
                        if interfaces[name]['connected'] and interfaces[name]['wireless']:
                            net.disconnect_wireless(name)
                        net.disable_interface(name)
                elif choice == '4':
                    if interfaces[name]['enabled'] and interfaces[name]['wireless'] and (
                        not interfaces[name]['connected']):
                        connect_wireless(name)
                elif choice == '5':
                    if interfaces[name]['connected'] and interfaces[name]['wireless']:
                        net.disconnect_wireless(name)
                elif choice == '6':
                    if interfaces[name]['connected']:
                        net.set_dhcp(name)
                elif choice == '7':
                    setup_ip_gateway_dns(name)
        except KeyboardInterrupt as ex:
            print()
            break
        except Exception as ex:
            traceback.print_exc()
            input('Press any key to continue...')

net.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
常用网络命令的python封装
"""
__author__ = 'M@llon'
__version__ = ''
 
import os
import re
 
 
def test(v):
    test.result = v
    return v
 
 
def get_interfaces():
    """
    获取所有网络接口信息
    遇到任何错误均抛出异常
    """
    interfaces = dict()
 
    # 获取接口名、索引号、启停状态、连接状态、硬件地址、IPv4地址
    for line in os.popen('ip -o addr show'):
        if test(re.match('^(\d+):\s+(\w+):\s+<(.+?)>\s+.+?state\s+(\w+)\s+.+?link/(\w+)\s+(\S+)\s+.+?\n$', line)):
            m = test.result
            # 这些标记的含义参见“/linux/if.h”中的“IFF_...”宏
            flags = m.group(3).split(',')
            # 去掉回环接口
            if 'LOOPBACK' in flags:
                continue
            interfaces[m.group(2)] = {
                'index': int(m.group(1)),
                'enabled': 'UP' in flags,
                'connected': {'UP': True, 'DOWN': False}.get(m.group(4)),
                'hardware_address': m.group(6),
                'wireless': False,
                'ip_addresses': list()
            }
        elif test(re.match('^\d+:\s+(\w+)\s+inet\s+(\S+)\s+.+?\n$', line)):
            m = test.result
            name = m.group(1)
            interface = interfaces.get(name)
            if not interface:
                # 此处就排除了上面去掉的接口,例如loopback接口
                continue
            interface['ip_addresses'].append(m.group(2))
 
    # 获取无线类型的接口
    for line in os.popen('iw dev'):
        if test(re.match('^\s+Interface\s+(\w+)\s*?\n$', line)):
            # 接口是否为wireless
            interfaces[test.result.group(1)]['wireless'] = True
 
    # 获取无线类型的接口的连接信息
    for name in interfaces:
        interface = interfaces[name]
        if interface['wireless']:
            for line in os.popen('iw dev %s link' % name):
                # 此处也可以通过“Connected ...”行判断是否已连接,但是上面已经判断了
                if test(re.match('^\s+SSID:\s+(\S+)\s*?\n$', line)):
                    # 获取SSID
                    interface['ssid'] = test.result.group(1)
 
    return interfaces
 
 
def get_default_route():
    """
    获取默认路由信息
    """
    default_route = None
 
    for line in os.popen('ip route show'):
        if test(re.match('^\s*default\s+via\s+(\S+)\s+dev\s+(\S+)\s*\n$', line)):
            m = test.result
            default_route = {
                'ip_address': m.group(1),
                'interface_name': m.group(2)
            }
            break
 
    return default_route
 
 
def get_name_servers():
    """
    获取域名服务器IP地址列表
    """
    name_servers = list()
 
    for line in open('/etc/resolv.conf'):
        if test(re.match('^\s*nameserver\s+(\S+)\s*\n$', line)):
            name_servers.append(test.result.group(1))
 
    return name_servers
 
 
def print_state(interfaces, default_route, name_servers):
    """
    打印所有网络接口、路由以及DNS信息
    """
    # 网络接口
    print('Network Interfaces:')
    print('    %10s  %8s  %17s  %s' % (
        'name',
        'type',
        'mac address',
        'state',
    ))
    print('    ----------  --------  -----------------  -----')
    for name in interfaces:
        interface = interfaces[name]
        state = list()
        if interface['enabled']:
            state.append('enabled')
        if interface['connected']:
            state.append('connected')
        if test(interface.get('ssid')):
            state.append('ssid:%s' % test.result)
        if len(interface['ip_addresses']):
            state.append('ip:%s' % ','.join(interface['ip_addresses']))
        print('    %10s  %8s  %17s  %s' % (
            name,
            'wireless' if interface['wireless'] else 'wired',
            interface['hardware_address'],
            ', '.join(state) if len(state) else 'N/A'
        ))
    print()
 
    # 默认路由
    print('Default Gateway:')
    if default_route:
        print('    ---> %s ---> %s' % (default_route['interface_name'], default_route['ip_address']))
    else:
        print('    N/A')
    print()
 
    # DNS
    print('DNS:')
    if len(name_servers):
        print('    %s' % ', '.join(name_servers))
    else:
        print('    N/A')
    print()
 
 
def cleanup_all(interfaces):
    """
    清理网络接口所有的设置、默认路由以及DNS
    """
    # 结束“supplicant”进程
    os.system('killall wpa_supplicant')
 
    # 禁用所有网络接口,删除所有IP地址以及路由
    for name in interfaces:
        os.system('ip link set %s down' % name)
        os.system('ip addr flush %s' % name)
 
    # 删除所有DNS地址
    open('/etc/resolv.conf', 'w').close()
 
 
def enable_interface(interface_name):
    """
    启用网络接口
    """
    os.system('ip link set %s up' % interface_name)
 
 
def disable_interface(interface_name):
    """
    禁用网络接口
    """
    os.system('ip link set %s down' % interface_name)
 
 
def get_ssids(interface_name):
    """
    扫描SSID
    """
    ssids = list()
 
    for line in os.popen('iw dev %s scan' % interface_name):
        if test(re.match('^\s+SSID:\s+(\S+)\s*?\n$', line)):
            ssids.append(test.result.group(1))
 
    return ssids
 
 
def connect_wireless(interface_name, ssid):
    """
    连接非加密的无线网
    """
    os.system('iw dev %s connect -w %s' % (interface_name, ssid))
 
 
def connect_wireless_with_wep(interface_name, ssid, keys):
    """
    连接WEP加密的无线网
    """
    os.system('iw dev %s connect -w %s key %s' % (interface_name, ssid, ' '.join(keys)))
 
 
def connect_wireless_with_wpa(interface_name, ssid, key):
    """
    连接WPA加密的无线网
    """
    os.system(
        'wpa_supplicant -i %s -D nl80211,wext -s -B -P /var/run/wpa_supplicant.%s.pid -C /var/run/wpa_supplicant' % (
            interface_name, interface_name
        ))
    os.system('wpa_cli -i %s add_network' % interface_name)
    os.system('wpa_cli -i %s set_network 0 ssid \'"%s"\'' % (interface_name, ssid))
    os.system('wpa_cli -i %s set_network 0 key_mgmt WPA-PSK' % interface_name)
    os.system('wpa_cli -i %s set_network 0 psk \'"%s"\'' % (interface_name, key))
    os.system('wpa_cli -i %s enable_network 0' % interface_name)
 
 
def disconnect_wireless(interface_name):
    """
    关闭无线连接
    """
    pattern = '^\s*\S+\s+(\S+)\s+.+?wpa_supplicant.%s.pid.+?\n$' % interface_name
    for line in os.popen('ps aux'):
        if test(re.match(pattern, line)):
            pid = test.result.group(1)
            os.system('kill -9 %s' % pid)
    os.system('iw dev %s disconnect' % interface_name)
 
 
def set_dhcp(interface_name):
    """
    使用DHCP设置接口
    """
    os.system('dhclient -r %s' % interface_name)
    os.system('dhclient %s' % interface_name)
 
 
def set_ip_addresses(interface_name, ip_addresses):
    """
    设置某网络接口的IP地址
    """
    os.system('ip addr flush %s' % interface_name)
    for ip_address in ip_addresses:
        os.system('ip addr add %s dev %s' % (ip_address, interface_name))
 
 
def set_default_route(interface_name, ip_address):
    """
    设置默认路由
    """
    os.system('ip route del default')
    os.system('ip route add default via %s dev %s' % (ip_address, interface_name))
 
 
def set_name_servers(name_servers):
    """
    设置域名服务器地址
    """
    with open('/etc/resolv.conf', 'w') as fp:
        for name_server in name_servers:
            fp.write('nameserver %s%s' % (name_server, os.linesep))
 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 【树莓派】树莓派(Debian)- root用户无法使用SSH登录
    【树莓派】树莓派(Debian)- root用户无法使用
    在树莓派4B上安装了最新的Debian64位系统默认账户密码:pi/raspberryroot/    ------无密码(通过sudo passwd root修改root密码后)问题root修改密码后还是无法登录解决这个系统默认不允许root使用SSH登录登录root用户su 打开配置文件 nano /etc/ssh/sshd_
    03-08
  • windows10环境下安装Linux子系统---debian
    windows10环境下安装Linux子系统---debian
    windows10环境下安装Linux子系统---debian一、前提1、在控制面板-程序-启用与关闭Windows功能中,勾选“适用于Linux的Windows子系统”  2、首先需要创建一个文件夹,用来存放子系统,在需要的位置创建即可,文件夹名任意3、手动下载Windows子系统发行版包,
    03-08
  • Debian 环境安装新版 nginx
    Debian 环境安装新版 nginx
    在 Debian 系统中,我们可以通过 apt-get 安装系统自带的 nginx,这样安装的 nginx 版本略旧。Nginx 官网提供了一些编辑绎好的 deb 安装包,我们只需更新安装源,就可以通过 apt-get 来安装最新的稳定版 Nginx 了。 加载安装源并导入key$ echo deb http://ng
    03-08
  • 使用apt-mirror建立本地debian仓库源
     先介绍一下环境:主机:Win7虚拟机:VirtualBox + Debian7由于软件源的体积比较大,所以我又给虚拟机添加了一块50GB的虚拟硬盘(给虚拟机添加虚拟硬盘的方法参见:http://www.cnblogs.com/pengdonglin137/p/3366589.html , 其中介绍了如何在Vmware和Virtua
    03-08
  • Debian其实有提供附带了各种桌面的安装镜像
    我之前试着装Debian,但它的安装程序我感觉很难用,装上去了之后也有许许多多的问题,比如中文不显示。今天我发现带Live CD的Debian镜像有带了各个桌面的版本,于是我就试着下载KDE版本的Debian。由于我房间的WLAN质量不佳,用500kb/s的速度下了几个小时,那
    02-10
  • Debian镜像使用帮助 Debian镜像下载
    Debian镜像使用帮助 Debian镜像下载
    http://mirrors.163.com/.help/debian.html
    02-10
  • Debian 11 安装Nvidia闭源驱动
    目录通过APT安装Nvidia驱动为Nvidia驱动注册Secure Boot参考文档本人的系统是Debian11,最近一阵子在捣鼓用apt安装英伟达的闭源驱动,同时支持Secure Boot,查阅了Debian Wiki之类的资料之后,在这里整理一下。通过APT安装Nvidia驱动首先,需要确保你的Debian
    02-10
  • Debian时区和时间自动同步
    时区和时间自动同步(1)时间设置及其同步#date  -s 07/26/2005 //2005年7月26日    //修改系统日期时间为当前正确时间#date -s 11:12:00     //11点12分0秒#vim /etc/default/rcS  //设定 BIOS 时间使用 UTC 时区将选项 UTC 的值设定成 yes
    02-10
  • debian/ubuntu系统vi无法删除字符的解决办法
    之前在 Linux 下操作,一直使用的是 Centos 系统,使用 vi 编辑命令一直很顺畅。 最近,入手了一台 debian 操作系统的 vps。在操作 vi 命令时,发现当输入 i 要进行文件编辑时,上下左右的光标无法移动,屏幕上总会出现字符,而且 backspace 只能后退,无法
    02-10
  • Debian安装JAVA环境 debian安装jdk11
     http://blog.csdn.net/gongora/archive/2009/05/15/4190469.aspxDebian官方没有维护专门的Java软件包,所以不能直接用apt-get工具来安装。在Debian系统中要安装Java,有两种方式,一种是用传统方式;一种是Debian方式。1. 传统方式在 sun 下载了最新的 JDK
    02-10
点击排行