socket方式快速部署服务

socket方式非ssh运行linux系统命令

需求
  • 1、行内、相关保险等行业,在部署服务时,监管不让使用ssh分发批量执行相关命令。
  • 2、快速批量执行命令,提高部署相率
  • 3、通过每台服务器上面部署一个socket服务端,用于接收socket 客户端发送的命令,执行命令,并将结果返回给socket客户端。
  • 4、增加特殊标识判断,避免任意命令都去执行,风险较高。
实现
  • 1、编写socket 客户端和服务端脚本。
  • 2、通过每台服务器上面部署一个socket服务端,用于接收socket 客户端发送的命令,执行命令,并将执行结果返回给socket客户端。
代码实现
  • socket服务端脚本
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import socket
import subprocess

# 创建一个socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP地址和端口
server_socket.bind(('0.0.0.0', 8185))

# 开始监听
server_socket.listen(1)

print("server is starting ,wati client conn...")

while True:
    # 接受客户端连接
    client_socket, client_address = server_socket.accept()
    print(f"client {client_address} is conn")

    # 接收客户端发送的命令
    command = client_socket.recv(1024).decode('utf-8')
    ccod_command = ""
    print(f"Receive command: {command}")
    if "socket_command"  == command.split("==>")[0]:
        ccod_command = command.split("==>")[1]
        # # 在服务器端执行命令
        print(f"running command: {ccod_command}")
        # 在服务器端执行命令
        process = subprocess.Popen(ccod_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()

        # 将命令执行结果发送回客户端
        if process.returncode == 0:
            result = stdout
            try:
                if result.decode('utf-8') == "":
                    result = "<<< "+ ccod_command +" >>> command exe ok"
                    print(result)
                    client_socket.send(result.encode('utf-8'))
                else:
                    result = stdout
                    client_socket.send(result)
            except  Exception as e:
                print(str(e))
                msg = f"send command exception return msg: {stderr.decode('utf-8')}"
                client_socket.send(msg.encode('utf-8'))
        else:
            result = f"<<< {ccod_command} >>> command exe erorr, error info: {stderr.decode('utf-8')}"
            client_socket.send(result.encode('utf-8'))

    # 关闭客户端连接
    client_socket.close()
  • socket客户端脚本
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import socket

def command_run(ip,port,command):
    socket_conn_status = True
    # 创建一个socket对象
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到服务器
    try:
        client_socket.settimeout(5)
        client_socket.connect((str(ip), int(port)))
    except socket.timeout:
        print(ip + " conn timeout")
        socket_conn_status = False
        
    except Exception as e:
        socket_conn_status = False
        print( ip + f" conn error {e}")

    if socket_conn_status:
        client_socket.send(command.encode('utf-8'))

        # 接收服务器返回的结果
        try:
            result = client_socket.recv(1024).decode('utf-8')
            print(f"{ip} server host msg return:")
            print(result)
            print("=================================================================================")
        except socket.timeout:
            print(ip + " recv msg timeout")
        # 关闭socket连接
        client_socket.close()
    else:
        print("=================================================================================")

if __name__ == "__main__":
    nginx_host_list = "127.0.0.1,122.0.0.2,127.0.0.1"
    exe_ip_range = nginx_host_list
    port = 8185
    # kill server 
    # shell_command = "socket_command==> kill -9 `ps -ef|grep ./socket_server.py |grep -v grep |awk '{print $2}'`"
    # shell_command = "socket_command==>  ifconfig"
    shell_command = "socket_command==>   source ~/.bash_profile"
    for ip in exe_ip_range.split(','):
        command_run(ip,port,shell_command)
脚本运行详情
  • 运行命令加载环境变量命令
#### 运行 source ~/.bash_profile ####
[devops@my-dev socket]$ ./socket_client.py 
127.0.0.1 server host msg return:
<<<  source ~/.bash_profile >>> command exe ok
=================================================================================
122.0.0.2 conn timeout
=================================================================================
127.0.0.1 server host msg return:
<<<  source ~/.bash_profile >>> command exe ok
=================================================================================

#### 运行 ifconfig111 ####
[devops@my-dev socket]$ ./socket_client.py 
127.0.0.1 server host msg return:
<<<  ifconfig111 >>> command exe erorr, error info: /bin/sh: ifconfig111: command not found
=================================================================================
122.0.0.2 conn timeout
=================================================================================
127.0.0.1 server host msg return:
<<<  ifconfig111 >>> command exe erorr, error info: /bin/sh: ifconfig111: command not found
=================================================================================

#### 运行 ls -htrl socket_command.tar.gz ####
[devops@my-dev ABC]$ ./socket_client.py 
127.0.0.1 server host msg return:
-rw-rw-r-- 1 devops devops 1.3K Oct  9 15:02 socket_command.tar.gz
=================================================================================
122.0.0.2 conn timeout
=================================================================================
127.0.0.1 server host msg return:
-rw-rw-r-- 1 devops devops 1.3K Oct  9 15:02 socket_command.tar.gz
=================================================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平凡的运维之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值