应用场景
- 树莓派连接在一个动态IP的环境,我们需要知道ip地址进行ssh连接或者sftp文件上传
- 远程执行命令,关机/杀进程/等
服务端 broadcast_server.py
# -*- coding:utf-8 -*-
import socket
import pickle
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 1060
s.bind(('', PORT))
print 'Listen...', s.getsockname()
def cmd(cmd):
p = os.popen(cmd,'r',1)
dat = p.read()
p.close()
return dat
def get_result(action,code,params,message,dat):
r = {
"action":action,
"params":params,
"code":code,
"data":dat,
"message":message
}
return r
while True:
data, address = s.recvfrom(65535)
rec = pickle.loads(data)
print('<-{}:{}'.format(address,rec ))
sent = ""
if rec['action'] == "cmd":
res = cmd(rec['params'])
sent = pickle.dumps(get_result("cmd",0,rec['params'],"操作成功",{'result':res.encode("utf-8")}))
print('-> {}'.format(address ))
s.sendto(sent.encode("utf-8"),address)
客户端 broadcast_client.py
import socket
import pickle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a','--action',help='the action you want to send')
parser.add_argument('-c','--cmd',help='the command you want to execute')
args = parser.parse_args()
print args.action,args.cmd
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 1060
network = '<broadcast>'
sent_data = {
'action':args.action,
'params':args.cmd
}
s.sendto(pickle.dumps(sent_data).encode('utf-8'), (network, PORT))
rec = s.recv(65535)
b = pickle.loads(rec)
print "data:",b['data']['result']
使用说明:服务端程序放在宿主电脑中,我们还必须设置其开启自动运行,可在~/.bashrc 中写入执行命令
nohup python broadcast_server.py &
我们可以定义自己的action,去操作不同的功能,更多功能请自行斟酌.这是一个好思路,比如应用于家庭中对灯,窗帘等控制
客户端执行例子:
python broadcast_client.py -a cmd -c 'ifconfig'
python broadcast_client.py -a cmd -c 'netstat'
python broadcast_client.py -a cmd -c 'ps -aux | grep python'
python broadcast_client.py -a cmd -c 'kill -9 22234'
python broadcast_client.py -a cmd -c 'shutdown'
本小项目未完待续
网友评论