Python 3.6 socket 简单远程命令CS

本文介绍如何使用Python的socket模块实现一个简单的远程命令执行工具。该工具包含Server端和Client端,通过Client端发送命令到Server端并在Server端执行,最后将执行结果返回给Client端。Server端运行于本地回环地址127.0.0.1的8888端口,接收来自Client端的命令并利用subprocess模块执行。整个过程涉及socket连接建立、命令收发及结果返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果大家对python的socket不是很熟,或者网络通信过程不了解的话请先百度一下,我这里直接上示例了

Server 端

# -----------------------
# __Author : tyran
# __Date : 17-11-15
# -----------------------

# Server
import socket
import subprocess

# 创建套接字
listen_fd = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
# 绑定ip和port
listen_address = ('127.0.0.1', 8888)
listen_fd.bind(listen_address)
# 设置套接字是否阻塞,一般都是阻塞的,如果不写也可以,默认就是阻塞
listen_fd.setblocking(True)
# 启动监听,参数是排队数量,不包括已经连上的一个,我在linux下测试失败了。。。。一直都是5
listen_fd.listen(2)
while True:
    # 开始监听,accept()如果没有客户端连上来,会阻塞
    # 返回值是有两个值,第一个是通信套接字,第二个是客户端信息
    connected_fd, client_address = listen_fd.accept()
    print(connected_fd)
    print(client_address)
    print('=============================================')
    """
    这里我会做一个远程命令调用,我的平台是linux
    """
    while True:
        # 然后接收客户端传来的命令
        command_data = connected_fd.recv(1024)
        # 如果客户端断开,会发送过来一个空字符串’‘
        if not command_data:
            # 关闭套接字
            connected_fd.close()
            break
        # subprocess可以重启一个新的进程执行命令
        command_obj = subprocess.Popen(str(command_data, encoding='utf-8'), shell=True, stdout=subprocess.PIPE)
        # stdout_data就是命令执行以后的输出
        stdout_data = command_obj.stdout.read()
        # 先把一共发送多少个字节数据发过去
        connected_fd.send(bytes(str(len(stdout_data)), encoding='utf-8'))
        # 这里需要防止粘连
        connected_fd.recv(1024)
        # 发送命令行输出的数据
        connected_fd.sendall(stdout_data)


Client 端

# -----------------------
# __Author : tyran
# __Date : 17-11-15
# -----------------------


# Client
import socket

connect_fd = socket.socket()
connect_fd.connect(('127.0.0.1', 8888))

while True:
    cmd = input('>>>>')
    if cmd == 'exit':
        connect_fd.close()
        break
    # 发送命令
    connect_fd.send(bytes(cmd, encoding='utf-8'))
    # 获取字节数
    data_len = int(str(connect_fd.recv(1024),encoding='utf-8'))
    # 防止粘连
    connect_fd.send(bytes('ok', encoding='utf-8'))
    # 显示数据
    data = ''
    while len(data) < data_len:
        data += str(str(connect_fd.recv(1024),encoding='utf-8'))
    print(data)


[root@lck my_wordpress]# docker-compose up -d /usr/local/lib/python3.6/site-packages/paramiko/transport.py:32: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6. from cryptography.hazmat.backends import default_backend Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 723, in urlopen chunked=chunked, File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 416, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib64/python3.6/http/client.py", line 1254, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib64/python3.6/http/client.py", line 1300, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib64/python3.6/http/client.py", line 1249, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib64/python3.6/http/client.py", line 1036, in _send_output self.send(msg) File "/usr/lib64/python3.6/http/client.py", line 974, in send self.connect() File "/usr/local/lib/python3.6/site-packages/docker/transport/unixconn.py", line 30, in connect sock.connect(self.unix_socket) FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 450, in send timeout=timeout File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 803, in urlopen method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] File "/usr/local/lib/python3.6/site-packages/urllib3/util/retry.py", line 552, in increment raise six.reraise(type(error), error, _stacktrace) File "/usr/local/lib/python3.这是什么问题如何解决
最新发布
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值