注:同一局域网内的测试
环境:python3.6.4,win10
代码如下
1、服务端(账号xxx,密码xx请换成自己的)
#!/D:/python/Anaconda/python.exe
# coding:utf-8
__author__ = 'wzq'
import socket
import os
# windows上拨号重连服务端
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8080))
s.listen(5) # 等待监听
print('Waiting for connection...')
while True:
conn, address = s.accept() # 获得连接与客户端ip
print("...接收到连接:", address)
conn.sendall(b'GOT IT')
while address:
data_bytes = conn.recv(1024) # 接收数据
data_str = str(data_bytes, encoding="utf-8")
if data_str == 'c':
print('start change ip')
# 断开拨号
os.system('rasdial /dis')
# 拨号
os.system('rasdial net_home xxx xx') # 输入拨号账号密码
conn.sendall(b'ip change success')
elif data_str == 'q':
conn.close()
break
else:
print(data_str, 'Not Useful Input')
conn.sendall(b'Not Useful Input')
s.close()
break
print('over')
2、客户端
#!/D:/python/Anaconda/python.exe
# coding:utf-8
__author__ = 'wzq'
import socket
import time
# windows上拨号重连客户端
obj = socket.socket()
obj.connect(("127.0.0.1", 8080))
ret_bytes = obj.recv(1024)
ret_str = str(ret_bytes, encoding="utf-8")
print("...接收到连接:", ret_str)
while True:
aa = input()
obj.sendall(bytes(aa, encoding="utf-8"))
data = obj.recv(1024)
data_str = str(data, encoding="utf-8")
print(data_str)
if data_str == 'ip change success':
obj.sendall(b'q')
time.sleep(1)
obj.close()
break
输出如下:
客户端:
...接收到连接: GOT IT
1
Not Useful Input
c
ip change success
Process finished with exit code 0
服务端:
Waiting for connection...
...接收到连接: ('127.0.0.1', 64327)
1 Not Useful Input
start change ip
命令已完成。
正在连接到 net_home...
正在验证用户名及密码...
正在网络上注册你的计算机...
已连接 net_home。
命令已完成。
over
Process finished with exit code 0
测试多次发现拨号不一定成功(尽管显示成功,最好自己发url测试)