Last active
December 9, 2019 00:52
-
-
Save tseijp/caab3149c3c9fcbe1e45c466c1f41a53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import time | |
import socket | |
import argparse | |
import subprocess | |
class Socket: | |
def __init__(self,opt): | |
self.port= opt.port if opt.port else 7001 | |
self.cmd = opt.cmd if opt.cmd else "python --version" | |
self.msg = opt.msg.strip('"') if opt.msg else "" | |
self.dir = opt.dir.strip('"').strip(' ') if opt.dir else DIRECTORY | |
self.ip = opt.ip .strip('"').strip(' ') if opt.ip else "127.0.0.1" | |
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
self.sleep=float(opt.sleep) if opt.sleep else 0 | |
def send_msg(self, msg='no message'): | |
text = msg.encode('utf-8') if type(msg) is str else msg | |
self.s.sendto(text, (self.ip, int(self.port))) | |
def run(self): | |
self.send_msg('%sstarted%s'%('*'*20,'*'*20)) | |
self.send_msg('port:%s,ip:%s,cmd:%s'%(self.port,self.ip,self.cmd)) | |
# main process --------------------------------------------------------- | |
if 1:#try: | |
self.send_msg('%s'%self.cmd) | |
proc = subprocess.Popen(self.cmd,#cmd_list, | |
cwd=self.dir, shell=True, | |
stdout = subprocess.PIPE, | |
universal_newlines=True, | |
bufsize=0)#[ref](https://janakiev.com/blog/python-shell-commands/) | |
self.send_msg('pid:%s is running'%(proc.pid)) | |
if self.sleep>0: | |
time.sleep(self.sleep) | |
while True: | |
line = proc.stdout.readline() | |
if line: | |
self.send_msg(line) | |
if not line and proc.poll() is not None: | |
break | |
self.send_msg('%sfinished%s'%('*'*20,'*'*20)) | |
class SocketOption: | |
def __init__(self): | |
self.parser = argparse.ArgumentParser() | |
def initialize(self): | |
self.parser.add_argument('-p', '--port' ,type=str ,default='') | |
self.parser.add_argument('-c', '--cmd' ,type=str ,default='') | |
self.parser.add_argument('-m', '--msg' ,type=str ,default='') | |
self.parser.add_argument('-d', '--dir' ,type=str ,default='') | |
self.parser.add_argument('-i', '--ip' ,type=str ,default='') | |
self.parser.add_argument('-s', '--sleep',type=str ,default='') | |
def parse(self, save=True): | |
self.initialize() | |
self.opt = self.parser.parse_args() | |
return self.opt | |
def main(): | |
opt = SocketOption().parse() | |
soc = Socket(opt) | |
soc.run() | |
if __name__=='__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment