Python batch execution script (server side and client establish TCP connection)

Source: Internet
Author: User

There are a lot of open source batch deployment tools that can be used, such as puppet, Ansible, Saltstack, chef.

But these tools have their own set of grammar rules, you have to follow his syntax to write programs, and then batch execution.

Is there a way to write bash or Python scripts directly and then execute them in batches?

The method of course is that you need to write your own program to transfer scripts, copy files, complex points, you can customize scripted synchronization or asynchronous execution, custom to execute the host group, and so on, need to according to their own business needs to think.

This is just a point, I use a socket (TCP) connection to execute the script in bulk.

Server-side scripting, Cat server.py


#!/usr/bin/env python

# This script was used to as server, which could transfer script to agents, copy files to agents

Import OS

Import socket

Import threading


HostList = {

' 10.1.214.10 ': 10001,

' 10.1.214.105 ': 10001,

' 10.1.214.106 ': 10001

}

Class Loadscript (object):

def __init__ (self):

Pass

def get_input (self):

Input_str = raw_input (' Please input the script (Absolute Path): ')

Return INPUT_STR

def check_input (self):

While 1:

Input_str = Self.get_input ()

If Input_str is None or Os.path.isfile (INPUT_STR) is False:

Print "Wrong Path for script!\n"

Else

Print "Your script is%s"% Input_str

Return INPUT_STR

def read_script (self):

Script = Self.check_input ()

Try

f = open (script, ' R ')

Content = F.readlines ()

CONTENT_STR = ". Join (content)

Return CONTENT_STR

Except

Print "Open script%s error!"% script

Sys.exit (1)


Class Socketserver (object):

def __init__ (self, host, port):

Self.sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)

Self.host = Host

Self.port = Port

def connect (self):

Self.sock.connect ((Self.host, Self.port))

def send (self, content):

#content = Loadscript (). Read_script ()

Print "Content:", content

Self.sock.send (content)

def receive (self):

result = SELF.SOCK.RECV (10000)

Print result

def close (self):

Self.sock.close ()

def run (self, content):

Self.connect ()

Self.send (content)

Self.receive ()

Self.close ()

Content = Loadscript (). Read_script ()

Print content

For key in Hostlist.keys ():

Server = Socketserver (key, Hostlist[key])

t = Threading. Thread (target = server.run, args = (content))

T.start ()


Client script, Cat agent.py

#!/usr/bin/env python

# This script was used to as server, which could transfer script to agents, copy files to agents

Import socket

Import subprocess

Import OS


Class Socketagent (object):

def __init__ (self, port):

Self.port = port;


Self.sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)

Self.sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)

Self.sock.bind (("", Port)

Self.sock.listen (5)

def listen (self):

Pass

def receive (self):

Self.clisock, (remote_host, remote_port) = Self.sock.accept ()

Content = SELF.CLISOCK.RECV (10000)

#clisock. Close ()

return content

def set_file (self, file = "/var/tmp/script"):

Return file

def convert_to_script (self):

Content = Self.receive ()

Script = Self.set_file ()

f = open (script, ' W ')

F.write ("#!/usr/bin/bash\n" + content + "\ n")

F.close ()

def execute (self):

Script = Self.set_file ()

cmd = ' bash%s '% str (script)

p = subprocess. Popen (cmd, stdout=subprocess. PIPE, Shell=true)

Out, err = P.communicate ()

Print "Output:", out

Print "ERR:", err

return err

def response (self):

If Self.execute () is None:

Self.clisock.send ("Script run Successfully")

Else

Self.clisock.send ("Script Run Failed")

Agent = Socketagent (10001)

Agent.convert_to_script ()

Agent.execute ()

Agent.response ()


Run the client script first, executing the service-side script and specifying the script to execute on the server.

Considering the method of establishing socket connection is not very convenient, subsequent consideration will be changed to other protocols, such as FTP.

If you have any ideas, please feel free to message communication.

This article from "Linux operation and Maintenance" blog, declined reprint!

Python batch execution script (server side and client establish TCP connection)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.