socket方式运行linux系统命令
需求
- 1、行内、相关保险等行业,在部署服务时,监管不让使用ssh分发批量执行相关命令。
- 2、快速批量执行命令,提高部署效率。
- 3、通过每台服务器上面部署一个socket服务端,用于接收socket 客户端发送的命令,执行命令,并将结果返回给socket客户端。
- 4、增加特殊标识判断,避免任意命令都去执行
实现
- 1、编写socket 客户端和服务端脚本。
- 2、通过每台服务器上面部署一个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()
#!/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
=================================================================================
评论区